Files
BlenderSharp/CodeGenerator/Program.cs
Samuele Lorefice 439cea385f Regenerated files
2025-01-22 18:11:19 +01:00

276 lines
11 KiB
C#

using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using Kaitai;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CSharp;
using BlendFile = Kaitai.BlenderBlend;
// ReSharper disable BitwiseOperatorOnEnumWithoutFlags
namespace CodeGenerator {
public class Program {
public static BlendFile blendfile;
private static StringBuilder sb = new();
private const string OutPath = @"Blendfile\DNA";
private const string Namespace = "BlendFile.DNA";
private static readonly string[] AdaptedTypes = new[] { "uchar" };
private static HashSet<string> customTypes;
public static void Log(string message) {
sb.AppendLine(message);
Console.WriteLine(message);
}
public static void Main(string[] args) {
Log("Reading blend file");
ReadBlendFile();
Log("Generating C# code...");
Log("Pass 1: Generating types");
CodeNamespace ns = GenerateTypes();
Log("Pass 2: Writing out code");
OutputCodeFiles(ns);
Log("Finished generating C# code!");
File.AppendAllText("Log.txt", sb.ToString());
}
private static void ReadBlendFile() {
Log("Reading empty.blend file");
blendfile = BlendFile.FromFile("empty.blend");
Log($"Header: Blender v{blendfile.Hdr.Version} {blendfile.Hdr.Endian}\n" +
$"DataBlocks: {blendfile.Blocks.Count}\n" +
$"DNA1: {blendfile.SdnaStructs.Count} structures\n");
}
private static CodeNamespace GenerateTypes() {
CodeNamespace ns = new CodeNamespace(Namespace);
customTypes = new();
foreach (var type in blendfile.SdnaStructs) {
Log($"Generating struct {type.Type}");
bool referenceSelf = false;
bool referencePointer = false;
//Add the type to the custom types list
customTypes.Add(type.Type);
//Create a new type declaration
var ctd = new CodeTypeDeclaration(type.Type);
foreach (var field in type.Fields) {
if (field.Name.Contains("*")) {
referencePointer = true;
}
if (field.Type.Contains(type.Type)) {
referenceSelf = true;
}
}
if (referenceSelf || referencePointer) {
Log("Struct contains references");
ctd.IsClass = true;
}
else {
ctd.IsStruct = true;
}
//Add the class to the namespace
ns.Types.Add(ctd);
//Add the fields to the class
Log($"Fields: {type.Fields.Count}");
foreach (var field in type.Fields) {
CodeMemberField cmf;
string name = field.Name;
if (name.Contains("()")) continue;
if (name.Contains("[")) {
Log($"Generating array field {field.Name}");
cmf = CreateArrayMemberField(field);
}
else {
Log($"Generating field {field.Name}");
cmf = CreateMemberField(field);
}
ctd.Members.Add(cmf);
}
Log("Generating constructor");
ctd.Members.Add(GenerateConstructor(type, ctd));
Log("Finished generating struct");
}
return ns;
}
private static CodeMemberField CreateMemberField(BlenderBlend.DnaField field) {
Type t = Type.GetType(field.Type.ParseFType());
CodeMemberField cmf;
//Check if the type is a built-in type or a custom type
if (t != null) cmf = new(t, field.Name.ParseFName()); //Built-in type
else {
cmf = new(new CodeTypeReference(field.Type), field.Name.ParseFName()); //Custom type
customTypes.Add(field.Type);
}
cmf.Attributes = MemberAttributes.Public;
return cmf;
}
private static CodeMemberField CreateArrayMemberField(BlenderBlend.DnaField field) {
Type t = Type.GetType(field.Type.ParseFType());
CodeMemberField cmf;
// Parse all array dimensions
var dimensions = new List<int>();
var name = field.Name.ParseFName();
int startIndex = 0;
// Get all array dimensions
while ((startIndex = name.IndexOf('[', startIndex)) != -1) {
int endIndex = name.IndexOf(']', startIndex);
string sizeStr = name.Substring(startIndex + 1, endIndex - startIndex - 1);
if (int.TryParse(sizeStr, out int size)) {
dimensions.Add(size);
}
startIndex = endIndex + 1;
}
// Get clean field name (without array brackets)
name = field.Name.ParseFName().Substring(0, field.Name.IndexOf('['));
//Check if the type is a built-in type or a custom type
if (t != null) cmf = new(t, name); //Built-in type
else {
cmf = new(field.Type, name); //Custom type
customTypes.Add(field.Type);
}
//Set the field attributes
cmf.Attributes = MemberAttributes.Public;
//Define the array type
cmf.Type.ArrayElementType = new(field.Type.ParseFType() ?? field.Type);
cmf.Type.ArrayRank = dimensions.Count;
//Define the array initialization expression
cmf.InitExpression = GenerateArrayInitExpression(cmf.Type, dimensions);
return cmf;
}
public static CodeExpression GenerateArrayInitExpression(CodeTypeReference type, IEnumerable<int> dimensions) {
var dimValues = dimensions as int[] ?? dimensions.ToArray();
string dims = string.Concat(dimValues.Take(dimValues.Count() - 1).Select(d => $"{d},"));
dims+= dimValues.Last();
return new CodeSnippetExpression($"new {type.BaseType}[{dims}]");
}
private static CodeTypeConstructor GenerateStaticConstructor(CodeTypeDeclaration ctd) {
CodeTypeConstructor ctc = new CodeTypeConstructor();
ctc.Attributes = MemberAttributes.Static;
ctc.Statements.AddRange(ctd.Members
.OfType<CodeMemberField>()
.Where(f => f.Type.ArrayRank > 0)
.Select(f =>
{
var dims = new List<int>();
for (int i = 0; i < f.Type.ArrayRank; i++) {
dims.Add(0);
}
return new CodeAssignStatement(
new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), f.Name),
GenerateArrayInitExpression(f.Type, dims)
);
}).ToArray<CodeStatement>());
return ctc;
}
private static CodeConstructor GenerateConstructor(BlenderBlend.DnaStruct type, CodeTypeDeclaration ctd) {
//Create a normal constructor
CodeConstructor cc = new CodeConstructor {
Name = type.Type,
Attributes = MemberAttributes.Public,
ReturnType = new(type.Type)
};
//Add the parameters to the constructor
cc.Parameters.AddRange(ctd.Members
.OfType<CodeMemberField>()
.Select(f =>
{
var cpde = new CodeParameterDeclarationExpression(f.Type, f.Name);
cpde.Direction = FieldDirection.In;
return cpde;
}).ToArray());
//Assign the parameters to the respective fields
cc.Statements.AddRange(ctd.Members
.OfType<CodeMemberField>()
.Select(f => new CodeAssignStatement(
new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), f.Name),
new CodeArgumentReferenceExpression(f.Name))
).ToArray<CodeStatement>());
return cc;
}
private static void SetupCCU(out CodeGeneratorOptions genOpts, out CSharpCodeProvider provider,
out CodeCompileUnit ccu) {
genOpts = new() {
BlankLinesBetweenMembers = false,
BracingStyle = "Block",
ElseOnClosing = true,
IndentString = " ",
VerbatimOrder = true
};
provider = new();
//var date = DateTime.Now.ToString(CultureInfo.InvariantCulture);
CodeNamespace globalNs = new CodeNamespace();
//CodeComment comment = new CodeComment("Automatically generated by BlenderSharp at " + date, false);
//globalNs.Comments.Add(new(comment));
globalNs.Imports.Add(new("System"));
ccu = new();
ccu.Namespaces.Add(globalNs);
}
private static void OutputCodeFiles(CodeNamespace ns) {
if (!Path.Exists(OutPath)) Directory.CreateDirectory(OutPath);
SetupCCU(out var codeGeneratorOptions, out var provider, out var ccu);
CodeNamespace tempNs = new CodeNamespace(Namespace);
ccu.Namespaces.Add(tempNs);
foreach (var type in ns.Types.OfType<CodeTypeDeclaration>()) {
tempNs.Types.Add(type);
Log($"Writing out {(type.IsStruct ? "struct" : "class")} {type.Name}");
using var sw = new StreamWriter($"{OutPath}\\{type.Name}.cs");
provider.GenerateCodeFromCompileUnit(ccu, sw, codeGeneratorOptions);
tempNs.Types.Remove(type);
}
customTypes.ExceptWith(ns.Types.OfType<CodeTypeDeclaration>().Select(t => t.Name));
foreach (var type in customTypes) {
Log($"Creating empty struct for missing {type}");
var ctd = new CodeTypeDeclaration(type) {
IsStruct = true,
Attributes = MemberAttributes.Public
};
tempNs.Types.Add(ctd);
}
using var finalsw = new StreamWriter($"{OutPath}\\_ExtraTypes.cs");
provider.GenerateCodeFromCompileUnit(ccu, finalsw, codeGeneratorOptions);
}
}
}