-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnityCSharp.cs
More file actions
420 lines (350 loc) · 13.1 KB
/
UnityCSharp.cs
File metadata and controls
420 lines (350 loc) · 13.1 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CG.Output.Helper;
using CG.SDK.Dotnet.Attributes;
using CG.SDK.Dotnet.Engine;
using CG.SDK.Dotnet.Engine.Models;
using CG.SDK.Dotnet.Engine.Unity;
using CG.SDK.Dotnet.Helper;
using CG.SDK.Dotnet.Helper.IO;
using CG.SDK.Dotnet.Plugin.Output;
using LangPrint;
using LangPrint.CSharp;
namespace CG.Output;
// TODO: `RuntimeRemoteClassHandle.value` type should be `RuntimeStructs_RemoteClass*`
internal enum CppOptions
{
PrecompileSyntax,
}
[PluginInfo(
Name = nameof(UnityCSharp),
Version = "5.0.0",
Author = "CorrM",
Description = "CSharp syntax support for Unity",
WebsiteLink = "https://github.com/CheatGear",
SourceCodeLink = "https://github.com/CheatGear/Output.UnityCs"
)]
public sealed class UnityCSharp : OutputPlugin<UnitySdkFile>
{
private readonly CSharpProcessor _cSharpProcessor;
public UnityCSharp()
{
_cSharpProcessor = new CSharpProcessor();
}
protected override Dictionary<string, string> LangTypes { get; } = new()
{
{ "int64_t", "long" },
{ "int32_t", "int" },
{ "int16_t", "short" },
{ "int8_t", "sbyte" },
{ "uint64_t", "ulong" },
{ "uint32_t", "uint" },
{ "uint16_t", "ushort" },
{ "uint8_t", "byte" },
{ "intptr_t", "IntPtr" },
{ "Il2CppString", "string" },
{ "Il2CppObject", "Object" },
};
public override string OutputName => "CSharp";
public override GameEngine SupportedEngines => GameEngine.Unity;
public override OutputPurpose SupportedPurpose => OutputPurpose.Internal | OutputPurpose.External;
public override IReadOnlyDictionary<Enum, OutputOption> Options { get; } = new Dictionary<Enum, OutputOption>
{
{
CppOptions.PrecompileSyntax,
new OutputOption(
"Precompile Syntax",
OutputOptionType.CheckBox,
"Use precompile headers for most build speed",
"true"
)
},
};
private string FixArrayTypeName(string type)
{
if (type.EndsWith("_Array"))
{
return type[..^"_Array".Length] + "[]";
}
return type;
}
private void FixTypes(EngineEnum eEnum)
{
eEnum.Type = ToLangType(eEnum.Type, false);
}
private void FixTypes(EngineField eField)
{
eField.Type = FixArrayTypeName(ToLangType(eField.Type, false));
}
private void FixTypes(EngineProperty eProp)
{
eProp.Type = FixArrayTypeName(ToLangType(eProp.Type, false));
}
private void FixTypes(EngineParameter eParam)
{
eParam.Type = FixArrayTypeName(ToLangType(eParam.Type, false));
}
private void FixTypes(EngineFunction eFunc)
{
foreach (EngineParameter engineParameter in eFunc.Parameters)
{
FixTypes(engineParameter);
}
}
private void FixTypes(EngineStruct eStruct)
{
foreach (EngineField eStructField in eStruct.Fields)
{
FixTypes(eStructField);
}
foreach (EngineProperty eStructProp in eStruct.Properties)
{
FixTypes(eStructProp);
}
foreach (EngineFunction eStructFunc in eStruct.Methods)
{
FixTypes(eStructFunc);
}
}
private void PrepareStruct(EngineStruct eStruct)
{
if (eStruct.Supers.Count > 0)
{
(string key, string value) = eStruct.Supers.First();
if (value is "UObject" or "Il2CppObject")
{
eStruct.Supers.Remove(key);
}
}
int getTypeInfoIdx = eStruct.Methods.FindIndex(m => m.Name == "GetTypeInfo");
if (getTypeInfoIdx != -1)
{
eStruct.Methods.RemoveAt(getTypeInfoIdx);
}
int getKlassIdx = eStruct.Methods.FindIndex(m => m.Name == "GetKlass");
if (getKlassIdx != -1)
{
eStruct.Methods.RemoveAt(getKlassIdx);
}
}
private IEnumerable<CSharpEnum> GetEnums(UnityPackage enginePackage)
{
return enginePackage.Enums.Select(ee => ee.ToCSharp());
}
private IEnumerable<CSharpField> GetFields(UnityPackage enginePackage)
{
return enginePackage.Fields.Select(ef => ef.ToCSharp());
}
private IEnumerable<CSharpFunction> GetFunctions(UnityPackage enginePackage)
{
return enginePackage.Functions.Select(ef => ef.ToCSharp());
}
private IEnumerable<CSharpStruct> GetStructs(UnityPackage enginePackage)
{
return enginePackage.Structs.Where(ec => !ec.IsSubType)
.Select(
eStruct =>
{
PrepareStruct(eStruct);
return eStruct.ToCSharp();
}
);
}
private IEnumerable<CSharpStruct> GetClasses(UnityPackage enginePackage)
{
return enginePackage.Classes.Where(ec => !ec.IsSubType)
.Select(
eStruct =>
{
PrepareStruct(eStruct);
return eStruct.ToCSharp();
}
);
}
/// <summary>
/// Generate enginePackage files
/// </summary>
/// <param name="unityPack">Package to generate files for</param>
/// <returns>File name and its content</returns>
private async ValueTask<Dictionary<string, string>> GeneratePackageFilesAsync(UnityPackage unityPack)
{
await ValueTask.CompletedTask.ConfigureAwait(false);
#if DEBUG
//if (enginePackage.Name != "BasicTypes")
// return new Dictionary<string, string>();
#endif
if (unityPack.IsPredefined)
{
return new Dictionary<string, string>();
}
var ret = new Dictionary<string, string>();
// Make CppPackageModel
List<CSharpStruct> structs = GetStructs(unityPack).ToList();
structs.AddRange(GetClasses(unityPack));
// Make CppPackage
var cppPackage = new CSharpPackage
{
Name = unityPack.Name,
//BeforeNameSpace = $"#ifdef _MSC_VER{Environment.NewLine}\t#pragma pack(push, 0x{SdkFile.GlobalMemberAlignment:X2}){Environment.NewLine}#endif",
//AfterNameSpace = $"#ifdef _MSC_VER{Environment.NewLine}\t#pragma pack(pop){Environment.NewLine}#endif",
HeadingComment = [$"Name: {SdkFile.GameName}", $"Version: {SdkFile.GameVersion}"],
NameSpace = SdkFile.Namespace,
Enums = GetEnums(unityPack).ToList(),
Structs = structs,
Conditions = unityPack.Conditions,
};
// Generate files
Dictionary<string, string> cppFiles = _cSharpProcessor.GenerateFiles(cppPackage);
foreach ((string fName, string fContent) in cppFiles)
{
ret.Add(fName, fContent);
}
return ret;
}
/// <summary>
/// Process local files that needed to be included
/// </summary>
/// <param name="processPurpose">Process props</param>
private ValueTask<Dictionary<string, string>> GenerateIncludesAsync(OutputPurpose processPurpose)
{
var ret = new Dictionary<string, string>();
return ValueTask.FromResult(ret);
/*
// Init
var unitTestCpp = new UnitTest(this);
if (processProps == OutputProps.External)
{
var mmHeader = new MemManagerHeader(this);
var mmCpp = new MemManagerCpp(this);
ValueTask<string> taskMmHeader = mmHeader.ProcessAsync(processProps);
ValueTask<string> taskMmCpp = mmCpp.ProcessAsync(processProps);
ret.Add(mmHeader.FileName, await taskMmHeader.ConfigureAwait(false));
ret.Add(mmCpp.FileName, await taskMmCpp.ConfigureAwait(false));
}
// Process
ValueTask<string> taskUnitTestCpp = unitTestCpp.ProcessAsync(processProps);
// Wait tasks
ret.Add(unitTestCpp.FileName, await taskUnitTestCpp.ConfigureAwait(false));
// PchHeader
if (Options[CppOptions.PrecompileSyntax].Value == "true")
{
var pchHeader = new PchHeader(this);
ret.Add(pchHeader.FileName, await pchHeader.ProcessAsync(processProps).ConfigureAwait(false));
}
return ret;
*/
}
protected override ValueTask OnInitAsync()
{
ArgumentNullException.ThrowIfNull(SdkFile);
var cSharpOpts = new CSharpLangOptions
{
NewLine = NewLineType.CRLF,
PrintSectionName = true,
InlineCommentPadSize = 40,
FieldMemberTypePadSize = 50,
GeneratePackageSyntax = false,
};
_cSharpProcessor.Init(cSharpOpts);
#if DEBUG
Options[CppOptions.PrecompileSyntax].SetValue("true");
#endif
// Fix types in all packages
foreach (UnityPackage pack in SdkFile.Packages)
{
foreach (EngineEnum engineEnum in pack.Enums)
{
FixTypes(engineEnum);
}
foreach (EngineClass engineClass in pack.Classes)
{
FixTypes(engineClass);
}
foreach (EngineStruct engineStruct in pack.Structs)
{
FixTypes(engineStruct);
}
}
return ValueTask.CompletedTask;
}
public override string ToLangType(string cppType, bool onlySubOld)
{
(int startPos, int endPos) = GetClearTypeNamePos(cppType);
string clearedType = cppType[startPos..endPos];
return base.ToLangType(clearedType, onlySubOld);
}
public override async ValueTask SaveAsync(string saveDirPath, OutputPurpose processPurpose)
{
var builder = new MyStringBuilder();
builder.AppendLine($"#pragma once{Environment.NewLine}");
builder.AppendLine("// --------------------------------------- \\\\");
builder.AppendLine("// Sdk Generated By ( CheatGear ) \\\\");
builder.AppendLine("// --------------------------------------- \\\\");
builder.AppendLine($"// Name: {SdkFile.GameName.Trim()}, Version: {SdkFile.GameVersion}{Environment.NewLine}");
builder.AppendLine("#include <set>");
builder.AppendLine("#include <string>");
builder.AppendLine("#include <vector>");
builder.AppendLine("#include <locale>");
builder.AppendLine("#include <unordered_set>");
builder.AppendLine("#include <unordered_map>");
builder.AppendLine("#include <iostream>");
builder.AppendLine("#include <sstream>");
builder.AppendLine("#include <cstdint>");
builder.AppendLine("#include <Windows.h>");
// Packages generator [ Should be first task ]
int packCount = 0;
foreach (UnityPackage pack in SdkFile.Packages)
{
foreach ((string fName, string fContent) in await GeneratePackageFilesAsync(pack).ConfigureAwait(false))
{
await FileManager.WriteAsync(saveDirPath, fName, fContent).ConfigureAwait(false);
}
if (Status?.ProgressbarStatus is not null)
{
await Status.ProgressbarStatus.Invoke("", packCount, SdkFile.Packages.Count - packCount)
.ConfigureAwait(false);
}
packCount++;
}
// Includes
foreach ((string fName, string fContent) in await GenerateIncludesAsync(processPurpose).ConfigureAwait(false))
{
await FileManager.WriteAsync(saveDirPath, fName, fContent).ConfigureAwait(false);
if (!fName.EndsWith(".cpp") && fName.ToLower() != "pch.h")
{
builder.AppendLine($"#include \"{fName.Replace("\\", "/")}\"");
}
}
builder.Append(Environment.NewLine);
// Package sorter
if (Status?.TextStatus is not null)
{
await Status.TextStatus.Invoke("Sort packages depend on dependencies").ConfigureAwait(false);
}
PackageSorterResult<IEnginePackage> sortResult =
PackageSorter.Sort(SdkFile.Packages.Cast<IEnginePackage>().ToList());
if (sortResult.CycleList.Count > 0)
{
builder.AppendLine("// # Dependency cycle headers");
builder.AppendLine($"// # (Sorted: {sortResult.SortedList.Count}, Cycle: {sortResult.CycleList.Count})\n");
foreach ((IEnginePackage package, IEnginePackage dependPackage) in sortResult.CycleList)
{
builder.AppendLine($"// {package.Name} <-> {dependPackage.Name}");
builder.AppendLine($"#include \"SDK/{package.Name}_Package.h\"");
}
builder.AppendLine();
builder.AppendLine();
}
foreach (IEnginePackage package in sortResult.SortedList.Where(p => p.IsPredefined))
{
builder.AppendLine($"#include \"SDK/{package.Name}_Package.h\"");
}
foreach (IEnginePackage package in sortResult.SortedList.Where(p => !p.IsPredefined))
{
builder.AppendLine($"#include \"SDK/{package.Name}_Package.h\"");
}
await FileManager.WriteAsync(saveDirPath, "SDK.h", builder.ToString()).ConfigureAwait(false);
}
}