unrust-codegen 0.1.6

The csharp codegenerator used by unrust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
use anyhow::Context;
use anyhow::Result;
use genco::fmt;
use genco::prelude::*;
use std::ffi::OsStr;
use std::fs::File;
use std::path::Path;

pub fn generate_csharp(path: &str, base_folder: &str) -> Result<()> {
    clear_contents(base_folder, "cs")?;

    let contents = std::fs::read_to_string(path)?;
    let ast = syn::parse_file(&contents)?;

    let custom_comps = generate_components_csharp(ast.clone(), base_folder)?;
    let custom_states = generate_states_csharp(ast.clone(), base_folder)?;
    generate_prefabs_csharp(ast.clone(), base_folder)?;

    generate_hooks(base_folder, custom_comps, custom_states)?;

    Ok(())
}

fn generate_hooks(
    base_folder: &str,
    custom_comps: csharp::Tokens,
    custom_states: csharp::Tokens,
) -> Result<()> {
    let runtime_initialize = &csharp::import("UnityEngine", "RuntimeInitializeOnLoadMethod");
    let runtime_initialize_load = &csharp::import("UnityEngine", "RuntimeInitializeLoadType");
    let unrust_native = &csharp::import("unrust.runtime", "NativeWrapper");
    let entity_manager = &csharp::import("Unity.Entities", "EntityManager");
    let entity = &csharp::import("Unity.Entities", "Entity");
    let create_callback = &csharp::import("unrust.runtime", "CustomCreateCallback");

    let hooks: csharp::Tokens = quote! {
        namespace unrust.userland
        {
            public static class UnrustHooks
            {
                [$runtime_initialize($runtime_initialize_load.BeforeSceneLoad)]
                static void Initialize()
                {
                    $unrust_native.CustomCreates = CreateCallback;
                }

                public static unsafe ulong CreateCallback($entity_manager manager, $entity entity, $create_callback cb)
                {
                    var count = 0;
                    var arr = new CustomData[CustomComponents.ComponentCount];

                    $(custom_comps)

                    var stateCount = 0;
                    var stateArr = new CustomState[CustomState.CustomStateCount];

                    $(custom_states)

                    fixed (void* ptr = arr)
                    {
                        fixed (void* state = stateArr)
                        {
                            return cb(ptr, (nuint)count, state, (nuint)stateCount);
                        }
                    }
                }
            }
        }
    };

    write_tokens_to_file(base_folder, "UnrustHooks.cs", hooks)
}

fn generate_prefabs_csharp(ast: syn::File, base_folder: &str) -> Result<()> {
    let monobehaviour = &csharp::import("UnityEngine", "MonoBehaviour");
    let baker = &csharp::import("Unity.Entities", "Baker");
    let spawnable = &csharp::import("unrust.runtime", "UnrustSpawnable");

    let enums = ast
        .items
        .iter()
        .filter_map(|item| match item {
            syn::Item::Enum(s) => Some(s),
            _ => None,
        })
        .filter(|item| {
            item.attrs
                .iter()
                .any(|attr| attr.path().is_ident("unity_prefab"))
        })
        .map(|item| {
            (
                item.ident.to_string(),
                item.variants.iter().map(|v| v.ident.to_string()),
            )
        })
        .enumerate()
        .map(|(index, (enum_name, variants))| {
            let variant_fields = variants.clone().map(|name| {
                quote! {
                    $['\r']public GameObject $(&name);
                }
            });

            let count = index;

            let author_fields = variants.map(|name| {
                quote! {
                    buffer.Add(GetEntity(authoring.$(&name), TransformUsageFlags.Dynamic));
                }
            });

            let comp: csharp::Tokens = quote! {
                namespace unrust.userland
                {
                    public class $(&enum_name)Authoring : $monobehaviour {
                        $(for n in variant_fields => $n)

                        public const int RESOURCE_ID = $count;

                        class Baker : $baker<$(&enum_name)Authoring>
                        {
                            public override void Bake($(&enum_name)Authoring authoring)
                            {
                                var containerEntity = GetEntity(TransformUsageFlags.None);
                                var buffer = AddBuffer<$spawnable>(containerEntity).Reinterpret<Entity>();

                                $(for n in author_fields => $n)

                                AddComponent<UnrustResourceID>(containerEntity, new UnrustResourceID { Value =  $count});
                            }
                        }
                    }
                }
            };

            (enum_name, comp)
        });

    enums.clone().try_for_each(|(name, comp)| {
        write_tokens_to_file(base_folder, &format!("{}Authoring.cs", name), comp)
    })?;

    Ok(())
}

fn generate_states_csharp(ast: syn::File, base_folder: &str) -> Result<csharp::Tokens> {
    let struct_layout = &csharp::import("System.Runtime.InteropServices", "StructLayout");
    let layout_kind = &csharp::import("System.Runtime.InteropServices", "LayoutKind");
    let monobehaviour = &csharp::import("UnityEngine", "MonoBehaviour");
    let component_data = &csharp::import("Unity.Entities", "IComponentData");

    let enums = ast
        .items
        .iter()
        .filter_map(|item| match item {
            syn::Item::Enum(s) => Some(s),
            _ => None,
        })
        .filter(|item| {
            item.attrs
                .iter()
                .any(|attr| attr.path().is_ident("bevy_state"))
        })
        .map(|item| (item.ident.to_string(), &item.variants))
        .map(|(enum_name, enum_variants)| {
            let enum_fields = enum_variants.iter();

            let name_list = enum_fields.clone().enumerate().map(|(index, v)| {
                quote! {
                    $['\r']$(v.ident.to_string()) = $index,
                }
            });

            let comp: csharp::Tokens = quote! {
                namespace unrust.userland
                {
                    [$(struct_layout)($layout_kind.Sequential)]
                    public struct $(&enum_name) : $component_data
                    {
                        public sbyte Value;
                    }

                    public class $(&enum_name)Authoring : $monobehaviour
                    {
                        public enum ENUM_$(&enum_name) : sbyte
                        {
                            $(for n in name_list => $n)
                        }

                        [SerializeField]
                        public ENUM_$(&enum_name) $(&enum_name);

                        class Baker : Baker<$(&enum_name)Authoring>
                        {
                            public override void Bake($(&enum_name)Authoring authoring)
                            {
                                var entity = GetEntity(TransformUsageFlags.None);
                                AddComponent(entity, new $(&enum_name)
                                {
                                        Value = (sbyte)authoring.$(&enum_name)
                                });
                            }
                        }
                    }
                }
            };

            (comp, enum_name)
        });

    enums.clone().try_for_each(|(comp, enum_name)| {
        write_tokens_to_file(base_folder, &format!("{}Authoring.cs", enum_name), comp)
    })?;

    let enum_types = enums.clone().enumerate().map(|(index, (_, name))| {
        quote! {
            $(&name) = $index
        }
    });

    let count = enums.clone().count();

    let generated_comps: csharp::Tokens = quote! {
        namespace unrust.userland
        {
            [$struct_layout($layout_kind.Sequential)]
            public struct CustomState
            {
                public const int CustomStateCount = $count;
                public CustomStateType ty;
                public sbyte value;
            }

            public enum CustomStateType: byte
            {
                $(for n in enum_types => $n)
            }
        }
    };

    write_tokens_to_file(base_folder, "UnrustState.cs", generated_comps)?;

    let add_enums = enums.clone().map(|(_, name)| {
        quote! {
            if (manager.HasComponent<$(&name)>(entity))
            {
                stateArr[stateCount] = new CustomState
                {
                    ty = CustomStateType.$(&name),
                    value = manager.GetComponentData<$(&name)>(entity).Value,
                };
                stateCount++;
            }


        }
    });

    Ok(quote! {
        $(for n in add_enums => $n)
    })
}

fn write_tokens_to_file(base: &str, name: &str, tokens: csharp::Tokens) -> Result<()> {
    let fmt = fmt::Config::from_lang::<Csharp>().with_indentation(fmt::Indentation::Space(4));
    let config = csharp::Config::default();

    let path = Path::new(base);

    let file = File::create(path.join(name)).context("failed to open file")?;
    let mut w = fmt::IoWriter::new(file);
    tokens
        .format_file(&mut w.as_formatter(&fmt), &config)
        .context("could not write to file")
}

fn generate_components_csharp(ast: syn::File, base_folder: &str) -> Result<csharp::Tokens> {
    let structs = find_structs_with_attr(ast, "unity_authoring")
        .into_iter()
        .map(generate_components_with_authoring);

    let fmt = fmt::Config::from_lang::<Csharp>().with_indentation(fmt::Indentation::Space(4));
    let config = csharp::Config::default();

    let path = Path::new(base_folder);

    structs.clone().try_for_each(|(comp, name)| {
        write_tokens_to_file(base_folder, &format!("{}Authoring.cs", name), comp)
    })?;

    let count = structs.clone().count();

    let gen_comps = structs.clone().map(|(_, name)| {
        quote! {
            $['\r'][FieldOffset(0)] public $(&name) $(&name);

        }
    });

    let enum_types = structs.clone().enumerate().map(|(index, (_, name))| {
        quote! {
            $['\r']$name = $index,
        }
    });

    let struct_layout = &csharp::import("System.Runtime.InteropServices", "StructLayout");
    let layout_kind = &csharp::import("System.Runtime.InteropServices", "LayoutKind");

    let generated_comps: csharp::Tokens = quote! {
        namespace unrust.userland
        {
            [$struct_layout($layout_kind.Sequential)]
            public struct CustomData
            {
                public CustomType ty;
                public CustomComponents value;
            }

            public enum CustomType : byte
            {
                $(for n in enum_types  => $n)
            }

            [$struct_layout($layout_kind.Explicit)]
            public struct CustomComponents
            {
                public const int ComponentCount = $count;
                $(for n in gen_comps => $n)
            }
        }
    };

    let file = File::create(path.join("UnrustComponent.cs")).context("failed to open file")?;
    let mut w = fmt::IoWriter::new(file);
    generated_comps
        .format_file(&mut w.as_formatter(&fmt), &config)
        .context("could not write to file")?;

    let add_comps = structs.clone().map(|(_, name)| {
        quote! {


            if (manager.HasComponent<$(&name)>(entity))
            {
                arr[count] = new CustomData
                {
                    ty = CustomType.$(&name),
                    value = new CustomComponents { $(&name) = manager.GetComponentData<$(&name)>(entity) },
                };
                count++;
            }
        }
    });

    let add_comps: csharp::Tokens = quote! {
        $(for n in add_comps  => $n)
    };

    Ok(add_comps)
}

fn generate_components_with_authoring(
    (struct_name, fields): (String, Vec<(String, syn::Type)>),
) -> (csharp::Tokens, String) {
    let component_data = &csharp::import("Unity.Entities", "IComponentData");
    let monobehaviour = &csharp::import("UnityEngine", "MonoBehaviour");
    let struct_layout = &csharp::import("System.Runtime.InteropServices", "StructLayout");
    let layout_kind = &csharp::import("System.Runtime.InteropServices", "LayoutKind");

    let component_fields = fields.iter().map(|(field_name, field_type)| {
        let field_type = map_rust_type(field_type);

        quote! {
            $['\r']public $field_type $field_name;
        }
    });

    let authoring_name = format!("{struct_name}Authoring");

    let authoring_fields = fields.iter().map(|(field_name, _)| {
        quote! {
            $['\r']$field_name = authoring.$field_name,
        }
    });

    let tokens: csharp::Tokens = quote! {
        namespace unrust.userland
        {
            [$struct_layout($layout_kind.Sequential)]
            public struct $(&struct_name) : $component_data
            {
                $(for n in component_fields.clone() => $n)
            }

            public class $(&authoring_name) : $monobehaviour
            {
                $(for n in component_fields => $n)

                class Baker : Baker<$(&authoring_name)>
                {
                    public override void Bake($(&authoring_name) authoring)
                    {
                        var entity = GetEntity(TransformUsageFlags.Dynamic);
                        AddComponent(entity, new $(&struct_name)
                            {
                                $(for n in authoring_fields => $n)
                            });
                    }
                }
            }
        }
    };

    (tokens, struct_name)
}

fn find_structs_with_attr(
    ast: syn::File,
    expected: &str,
) -> Vec<(String, Vec<(String, syn::Type)>)> {
    ast.items
        .iter()
        .filter_map(|item| match item {
            syn::Item::Struct(s) => Some(s),
            _ => None,
        })
        .filter(|item| item.attrs.iter().any(|attr| attr.path().is_ident(expected)))
        .map(|item| {
            let fields = match &item.fields {
                syn::Fields::Named(fields) => fields
                    .named
                    .iter()
                    .map(|f| {
                        let field_name = f.ident.clone().unwrap().to_string();
                        let field_type = f.ty.clone();
                        (field_name, field_type)
                    })
                    .collect::<Vec<(String, syn::Type)>>(),
                _ => vec![],
            };

            (item.ident.to_string(), fields)
        })
        .collect()
}

fn clear_contents(path: &str, extension: &str) -> Result<()> {
    let files = std::fs::read_dir(path)?;
    files
        .filter_map(|p| p.ok())
        .filter_map(|p| {
            let path = p.path();
            let Some(ext) = path.extension() else {
                return None;
            };

            if ext == OsStr::new(extension) {
                Some(p.path())
            } else {
                None
            }
        })
        .try_for_each(std::fs::remove_file)?;

    Ok(())
}

fn map_rust_type(ty: &syn::Type) -> String {
    let syn::Type::Path(path) = ty else {
        panic!("expected rust path type");
    };

    let path = path
        .path
        .get_ident()
        .expect("expected simple path type")
        .to_string();

    match path.as_str() {
        "f32" => "float",
        "f64" => "double",
        "i32" => "int",
        "i64" => "long",
        "u32" => "uint",
        "u64" => "ulong",
        _ => panic!("unsupported base type"),
    }
    .to_string()
}