Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integration of ImPlot, ImNodes and ImGuizmo #218

Merged
merged 12 commits into from
Mar 21, 2021
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions src/CodeGenerator/CodeGenerator.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,24 @@
</PropertyGroup>

<ItemGroup>
<Content Include="structs_and_enums.json" CopyToOutputDirectory="PreserveNewest" />
<Content Include="definitions.json" CopyToOutputDirectory="PreserveNewest" />
<Content Include="variants.json" CopyToOutputDirectory="PreserveNewest" />
<Content Include="definitions\cimgui\structs_and_enums.json" CopyToOutputDirectory="PreserveNewest" />
<Content Include="definitions\cimgui\definitions.json" CopyToOutputDirectory="PreserveNewest" />
<Content Include="definitions\cimgui\variants.json" CopyToOutputDirectory="PreserveNewest" />

<Content Include="definitions\cimplot\structs_and_enums.json" CopyToOutputDirectory="PreserveNewest" />
<Content Include="definitions\cimplot\definitions.json" CopyToOutputDirectory="PreserveNewest" />
<Content Include="definitions\cimplot\variants.json" CopyToOutputDirectory="PreserveNewest" />

<Content Include="definitions\cimnodes\structs_and_enums.json" CopyToOutputDirectory="PreserveNewest" />
<Content Include="definitions\cimnodes\definitions.json" CopyToOutputDirectory="PreserveNewest" />
<Content Include="definitions\cimnodes\variants.json" CopyToOutputDirectory="PreserveNewest" />

<Content Include="definitions\cimguizmo\structs_and_enums.json" CopyToOutputDirectory="PreserveNewest" />
<Content Include="definitions\cimguizmo\definitions.json" CopyToOutputDirectory="PreserveNewest" />
<Content Include="definitions\cimguizmo\variants.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
</ItemGroup>

</Project>
7 changes: 5 additions & 2 deletions src/CodeGenerator/ImguiDefinitions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public void LoadFrom(string directory)
JObject variantsJson = null;
if (File.Exists(Path.Combine(directory, "variants.json")))
{
using (StreamReader fs = File.OpenText(Path.Combine(AppContext.BaseDirectory, "variants.json")))
using (StreamReader fs = File.OpenText(Path.Combine(directory, "variants.json")))
using (JsonTextReader jr = new JsonTextReader(fs))
{
variantsJson = JObject.Load(jr);
Expand Down Expand Up @@ -275,6 +275,9 @@ private string SanitizeMemberName(string memberName)
ret = ret.Substring(0, ret.Length - 1);
}

if (Char.IsDigit(ret.First()))
ret = "_" + ret;

return ret;
}
}
Expand Down Expand Up @@ -368,7 +371,7 @@ public TypeReference(string name, string type, int asize, string templateType, E

TypeVariants = typeVariants;

IsEnum = enums.Any(t => t.Name == type || t.FriendlyName == type);
IsEnum = enums.Any(t => t.Name == type || t.FriendlyName == type || TypeInfo.WellKnownEnums.Contains(type));
}

private int ParseSizeString(string sizePart, EnumDefinition[] enums)
Expand Down
98 changes: 70 additions & 28 deletions src/CodeGenerator/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,55 @@ static void Main(string[] args)
{
outputPath = AppContext.BaseDirectory;
}

string libraryName;
if (args.Length > 1)
{
libraryName = args[1];
}
else
{
libraryName = "cimgui";
}

string projectNamespace = libraryName switch
{
"cimgui" => "ImGuiNET",
"cimplot" => "ImGuiNET",
"cimnodes" => "ImGuiNET",
"cimguizmo" => "ImGuiNET",
_ => throw new NotImplementedException()
};

string classPrefix = libraryName switch
{
"cimgui" => "ImGui",
"cimplot" => "ImPlot",
"cimnodes" => "ImNodes",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After looking into this more, cimnodes actually wraps the imnodes project, which is similar but different to another project called ImNodes. Using ImNodes as the class name (instea of imnodes) might be confusing because of that.

"cimguizmo" => "ImGuizmo",
_ => throw new NotImplementedException()
};

string dllName = libraryName switch
{
"cimgui" => "cimgui",
"cimplot" => "cimgui",
"cimnodes" => "cimgui",
"cimguizmo" => "cimgui",
_ => throw new NotImplementedException()
};

string definitionsPath = Path.Combine(AppContext.BaseDirectory, "definitions", libraryName);
var defs = new ImguiDefinitions();
defs.LoadFrom(AppContext.BaseDirectory);
defs.LoadFrom(definitionsPath);

Console.WriteLine($"Outputting generated code files to {outputPath}.");

foreach (EnumDefinition ed in defs.Enums)
{
using (CSharpCodeWriter writer = new CSharpCodeWriter(Path.Combine(outputPath, ed.FriendlyName + ".gen.cs")))
{
writer.PushBlock("namespace ImGuiNET");
writer.PushBlock($"namespace {projectNamespace}");
if (ed.FriendlyName.Contains("Flags"))
{
writer.WriteLine("[System.Flags]");
Expand Down Expand Up @@ -62,7 +100,7 @@ static void Main(string[] args)
writer.Using("System.Runtime.CompilerServices");
writer.Using("System.Text");
writer.WriteLine(string.Empty);
writer.PushBlock("namespace ImGuiNET");
writer.PushBlock($"namespace {projectNamespace}");

writer.PushBlock($"public unsafe partial struct {td.Name}");
foreach (TypeReference field in td.Fields)
Expand Down Expand Up @@ -209,7 +247,7 @@ static void Main(string[] args)
{
defaults.Add(orderedDefaults[j].Key, orderedDefaults[j].Value);
}
EmitOverload(writer, overload, defaults, "NativePtr");
EmitOverload(writer, overload, defaults, "NativePtr", classPrefix);
}
}
}
Expand All @@ -219,14 +257,14 @@ static void Main(string[] args)
}
}

using (CSharpCodeWriter writer = new CSharpCodeWriter(Path.Combine(outputPath, "ImGuiNative.gen.cs")))
using (CSharpCodeWriter writer = new CSharpCodeWriter(Path.Combine(outputPath, $"{classPrefix}Native.gen.cs")))
{
writer.Using("System");
writer.Using("System.Numerics");
writer.Using("System.Runtime.InteropServices");
writer.WriteLine(string.Empty);
writer.PushBlock("namespace ImGuiNET");
writer.PushBlock("public static unsafe partial class ImGuiNative");
writer.PushBlock($"namespace {projectNamespace}");
writer.PushBlock($"public static unsafe partial class {classPrefix}Native");
foreach (FunctionDefinition fd in defs.Functions)
{
foreach (OverloadDefinition overload in fd.Overloads)
Expand Down Expand Up @@ -273,12 +311,12 @@ static void Main(string[] args)

if (isUdtVariant)
{
writer.WriteLine($"[DllImport(\"cimgui\", CallingConvention = CallingConvention.Cdecl, EntryPoint = \"{exportedName}\")]");
writer.WriteLine($"[DllImport(\"{dllName}\", CallingConvention = CallingConvention.Cdecl, EntryPoint = \"{exportedName}\")]");

}
else
{
writer.WriteLine("[DllImport(\"cimgui\", CallingConvention = CallingConvention.Cdecl)]");
writer.WriteLine($"[DllImport(\"{dllName}\", CallingConvention = CallingConvention.Cdecl)]");
}
writer.WriteLine($"public static extern {ret} {methodName}({parameters});");
}
Expand All @@ -287,15 +325,15 @@ static void Main(string[] args)
writer.PopBlock();
}

using (CSharpCodeWriter writer = new CSharpCodeWriter(Path.Combine(outputPath, "ImGui.gen.cs")))
using (CSharpCodeWriter writer = new CSharpCodeWriter(Path.Combine(outputPath, $"{classPrefix}.gen.cs")))
{
writer.Using("System");
writer.Using("System.Numerics");
writer.Using("System.Runtime.InteropServices");
writer.Using("System.Text");
writer.WriteLine(string.Empty);
writer.PushBlock("namespace ImGuiNET");
writer.PushBlock("public static unsafe partial class ImGui");
writer.PushBlock($"namespace {projectNamespace}");
writer.PushBlock($"public static unsafe partial class {classPrefix}");
foreach (FunctionDefinition fd in defs.Functions)
{
if (TypeInfo.SkippedFunctions.Contains(fd.Name)) { continue; }
Expand Down Expand Up @@ -336,7 +374,7 @@ static void Main(string[] args)
{
defaults.Add(orderedDefaults[j].Key, orderedDefaults[j].Value);
}
EmitOverload(writer, overload, defaults, null);
EmitOverload(writer, overload, defaults, null, classPrefix);
}
}
}
Expand Down Expand Up @@ -381,7 +419,8 @@ private static void EmitOverload(
CSharpCodeWriter writer,
OverloadDefinition overload,
Dictionary<string, string> defaultValues,
string selfName)
string selfName,
string classPrefix)
{
if (overload.Parameters.Where(tr => tr.Name.EndsWith("_begin") || tr.Name.EndsWith("_end"))
.Any(tr => !defaultValues.ContainsKey(tr.Name)))
Expand Down Expand Up @@ -481,6 +520,15 @@ private static void EmitOverload(
postCallLines.Add($"}}");
}
}
else if (defaultValues.TryGetValue(tr.Name, out string defaultVal))
{
if (!CorrectDefaultValue(defaultVal, tr, out string correctedDefault))
{
correctedDefault = defaultVal;
}
marshalledParameters[i] = new MarshalledParameter(nativeTypeName, false, correctedIdentifier, true);
preCallLines.Add($"{nativeTypeName} {correctedIdentifier} = {correctedDefault};");
}
else if (tr.Type == "char* []")
{
string nativeArgName = "native_" + tr.Name;
Expand Down Expand Up @@ -518,15 +566,6 @@ private static void EmitOverload(
preCallLines.Add($" offset += {correctedIdentifier}_byteCounts[i] + 1;");
preCallLines.Add("}");
}
else if (defaultValues.TryGetValue(tr.Name, out string defaultVal))
{
if (!CorrectDefaultValue(defaultVal, tr, out string correctedDefault))
{
correctedDefault = defaultVal;
}
marshalledParameters[i] = new MarshalledParameter(nativeTypeName, false, correctedIdentifier, true);
preCallLines.Add($"{nativeTypeName} {correctedIdentifier} = {correctedDefault};");
}
else if (tr.Type == "bool")
{
string nativeArgName = "native_" + tr.Name;
Expand Down Expand Up @@ -557,7 +596,7 @@ private static void EmitOverload(
marshalledParameters[i] = new MarshalledParameter(wrappedParamType, false, nativeArgName, false);
preCallLines.Add($"{tr.Type} {nativeArgName} = {correctedIdentifier}.NativePtr;");
}
else if ((tr.Type.EndsWith("*") || tr.Type.Contains("[") || tr.Type.EndsWith("&")) && tr.Type != "void*" && tr.Type != "ImGuiContext*")
else if ((tr.Type.EndsWith("*") || tr.Type.Contains("[") || tr.Type.EndsWith("&")) && tr.Type != "void*" && tr.Type != "ImGuiContext*" && tr.Type != "ImPlotContext*"&& tr.Type != "EditorContext*")
{
string nonPtrType;
if (tr.Type.Contains("["))
Expand Down Expand Up @@ -634,7 +673,7 @@ private static void EmitOverload(
targetName = targetName.Substring(0, targetName.IndexOf("_nonUDT"));
}

writer.WriteLine($"{ret}ImGuiNative.{targetName}({nativeInvocationStr});");
writer.WriteLine($"{ret}{classPrefix}Native.{targetName}({nativeInvocationStr});");

foreach (string line in postCallLines)
{
Expand Down Expand Up @@ -736,7 +775,7 @@ private static bool GetWrappedType(string nativeType, out string wrappedType)

private static bool CorrectDefaultValue(string defaultVal, TypeReference tr, out string correctedDefault)
{
if (tr.Type == "ImGuiContext*")
if (tr.Type == "ImGuiContext*" || tr.Type == "ImPlotContext*" || tr.Type == "EditorContext*")
{
correctedDefault = "IntPtr.Zero";
return true;
Expand All @@ -754,7 +793,10 @@ private static bool CorrectDefaultValue(string defaultVal, TypeReference tr, out

if (tr.IsEnum)
{
correctedDefault = $"({tr.Type}){defaultVal}";
if (defaultVal.StartsWith("-"))
correctedDefault = $"({tr.Type})({defaultVal})";
TillAlex marked this conversation as resolved.
Show resolved Hide resolved
else
correctedDefault = $"({tr.Type}){defaultVal}";
return true;
}

Expand Down
36 changes: 33 additions & 3 deletions src/CodeGenerator/TypeInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@ public class TypeInfo
{ "ImFileHandle", "IntPtr" },
{ "ImU8", "byte" },
{ "ImS8", "sbyte" },
{ "ImU16", "ushort" },
{ "ImS16", "short" },
{ "ImU32", "uint" },
{ "ImS32", "int" },
{ "ImU64", "ulong" },
{ "ImS64", "long" },
{ "unsigned short", "ushort" },
{ "unsigned int", "uint" },
{ "ImVec2", "Vector2" },
Expand All @@ -29,10 +34,11 @@ public class TypeInfo
{ "ImDrawIdx", "ushort" },
{ "ImDrawListSharedData", "IntPtr" },
{ "ImDrawListSharedData*", "IntPtr" },
{ "ImU32", "uint" },
{ "ImDrawCallback", "IntPtr" },
{ "size_t", "uint" },
{ "ImGuiContext*", "IntPtr" },
{ "ImPlotContext*", "IntPtr" },
{ "EditorContext*", "IntPtr" },
{ "float[2]", "Vector2*" },
{ "float[3]", "Vector3*" },
{ "float[4]", "Vector4*" },
Expand All @@ -44,7 +50,12 @@ public class TypeInfo
{ "char* []", "byte**" },
{ "unsigned char[256]", "byte*"},
};


public static readonly List<string> WellKnownEnums = new List<string>()
{
"ImGuiMouseButton"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, I guess this is needed because one of the new projects uses ImGuiMouseButton, but the definitions.json file that is used for it doesn't include it (since it's part of cimgui). This might work as a quick fix, but it points to a deeper issue. It seems like the new libraries should reference the cimgui definitions while generating code.

};

public static readonly Dictionary<string, string> WellKnownFieldReplacements = new Dictionary<string, string>()
{
{ "bool", "bool" }, // Force bool to remain as bool in type-safe wrappers.
Expand All @@ -62,16 +73,35 @@ public class TypeInfo
{
{ "((void *)0)", "null" },
{ "((void*)0)", "null" },
{ "NULL", "null"},
{ "nullptr", "null"},
{ "ImVec2(0,0)", "new Vector2()" },
{ "ImVec2(-1,0)", "new Vector2(-1, 0)" },
{ "ImVec2(1,0)", "new Vector2(1, 0)" },
{ "ImVec2(1,1)", "new Vector2(1, 1)" },
{ "ImVec2(0,1)", "new Vector2(0, 1)" },
{ "ImVec4(0,0,0,0)", "new Vector4()" },
{ "ImVec4(1,1,1,1)", "new Vector4(1, 1, 1, 1)" },
{ "ImVec4(0,0,0,-1)", "new Vector4(0, 0, 0, -1)" },
{ "ImPlotPoint(0,0)", "new ImPlotPoint { x = 0, y = 0 }" },
{ "ImPlotPoint(1,1)", "new ImPlotPoint { x = 1, y = 1 }" },
{ "ImDrawCornerFlags_All", "ImDrawCornerFlags.All" },
{ "ImPlotFlags_None", "ImPlotFlags.None"},
{ "ImPlotAxisFlags_None", "ImPlotAxisFlags.None"},
{ "ImPlotAxisFlags_NoGridLines", "ImPlotAxisFlags.NoGridLines"},
{ "ImGuiCond_Once", "ImGuiCond.Once"},
{ "ImPlotOrientation_Vertical", "ImPlotOrientation.Vertical"},
{ "PinShape_CircleFilled", "PinShape._CircleFilled"},
{ "FLT_MAX", "float.MaxValue" },
{ "(((ImU32)(255)<<24)|((ImU32)(255)<<16)|((ImU32)(255)<<8)|((ImU32)(255)<<0))", "0xFFFFFFFF" }
{ "(((ImU32)(255)<<24)|((ImU32)(255)<<16)|((ImU32)(255)<<8)|((ImU32)(255)<<0))", "0xFFFFFFFF" },
{ "sizeof(ImU8)", "sizeof(byte)"},
{ "sizeof(ImS8)", "sizeof(sbyte)"},
{ "sizeof(ImU16)", "sizeof(ushort)"},
{ "sizeof(ImS16)", "sizeof(short)"},
{ "sizeof(ImU32)", "sizeof(uint)"},
{ "sizeof(ImS32)", "sizeof(int)"},
{ "sizeof(ImU64)", "sizeof(ulong)"},
{ "sizeof(ImS64)", "sizeof(long)"}
};

public static readonly Dictionary<string, string> IdentifierReplacements = new Dictionary<string, string>()
Expand Down
Loading