Program.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using NJsonSchema.References;
  8. namespace SharpGLTF
  9. {
  10. using CodeGen;
  11. using SchemaReflection;
  12. class Program
  13. {
  14. #region MAIN
  15. static void Main(string[] args)
  16. {
  17. SchemaDownload.Syncronize(Constants.RemoteSchemaRepo, Constants.LocalRepoDirectory);
  18. _ProcessMainSchema();
  19. _ProcessKhronosPBRExtension();
  20. _ProcessKhronosUnlitExtension();
  21. _ProcessKhronosModelLightsPunctualExtension();
  22. _ProcessKhronosNodeLightsPunctualExtension();
  23. _ProcessKhronosTextureTransformExtension();
  24. // these extansions are not fully supported and temporarily removed:
  25. // _ProcessDracoExtension();
  26. // _ProcessMicrosoftLODExtension();
  27. }
  28. #endregion
  29. #region Main Schema code generation
  30. private static void _ProcessMainSchema()
  31. {
  32. // load and process schema
  33. var ctx1 = LoadSchemaContext(Constants.MainSchemaFile);
  34. // Ignore "glTF Property" because it is completely hand coded.
  35. ctx1.IgnoredByCodeEmitter("glTF Property");
  36. // We will mimeType "anyof" as a plain string.
  37. ctx1.Remove("image/jpeg-image/png");
  38. // replace Image.mimeType type from an Enum to String, so we can serialize it with more formats if required
  39. ctx1.FindClass("Image")
  40. .GetField("mimeType")
  41. .FieldType = ctx1.UseString();
  42. // replace Node.Matrix, Node.Rotation, Node.Scale and Node.Translation with System.Numerics.Vectors types
  43. var node = ctx1.FindClass("Node");
  44. node.GetField("matrix").SetDataType(typeof(System.Numerics.Matrix4x4), true).RemoveDefaultValue().SetItemsRange(0);
  45. node.GetField("rotation").SetDataType(typeof(System.Numerics.Quaternion), true).RemoveDefaultValue().SetItemsRange(0);
  46. node.GetField("scale").SetDataType(typeof(System.Numerics.Vector3), true).RemoveDefaultValue().SetItemsRange(0);
  47. node.GetField("translation").SetDataType(typeof(System.Numerics.Vector3), true).RemoveDefaultValue().SetItemsRange(0);
  48. // replace Material.emissiveFactor with System.Numerics.Vectors types
  49. ctx1.FindClass("Material")
  50. .GetField("emissiveFactor")
  51. .SetDataType(typeof(System.Numerics.Vector3), true)
  52. .SetDefaultValue("Vector3.Zero")
  53. .SetItemsRange(0);
  54. // replace Material.baseColorFactor with System.Numerics.Vectors types
  55. ctx1.FindClass("Material PBR Metallic Roughness")
  56. .GetField("baseColorFactor")
  57. .SetDataType(typeof(System.Numerics.Vector4), true)
  58. .SetDefaultValue("Vector4.One")
  59. .SetItemsRange(0);
  60. var tex1 = ctx1.FindEnum("LINEAR-NEAREST");
  61. tex1.SetValue("DEFAULT",0);
  62. var tex2 = ctx1.FindEnum("LINEAR-LINEAR_MIPMAP_LINEAR-LINEAR_MIPMAP_NEAREST-NEAREST-NEAREST_MIPMAP_LINEAR-NEAREST_MIPMAP_NEAREST");
  63. tex2.SetValue("DEFAULT", 0);
  64. ProcessSchema("gltf.g", ctx1);
  65. }
  66. #endregion
  67. #region Extensions code generation
  68. private static void _ProcessKhronosPBRExtension()
  69. {
  70. var ctx = LoadSchemaContext(Constants.KhronosPbrSpecGlossSchemaFile);
  71. ctx.IgnoredByCodeEmitter("glTF Property");
  72. ctx.IgnoredByCodeEmitter("glTF Child of Root Property");
  73. ctx.IgnoredByCodeEmitter("Texture Info");
  74. ctx.FindClass("KHR_materials_pbrSpecularGlossiness glTF extension")
  75. .GetField("diffuseFactor")
  76. .SetDataType(typeof(System.Numerics.Vector4), true)
  77. .SetDefaultValue("Vector4.One")
  78. .SetItemsRange(0);
  79. ctx.FindClass("KHR_materials_pbrSpecularGlossiness glTF extension")
  80. .GetField("specularFactor")
  81. .SetDataType(typeof(System.Numerics.Vector3), true)
  82. .SetDefaultValue("Vector3.One")
  83. .SetItemsRange(0);
  84. ProcessSchema("ext.pbrSpecularGlossiness.g", ctx);
  85. }
  86. private static void _ProcessKhronosUnlitExtension()
  87. {
  88. var ctx = LoadSchemaContext(Constants.KhronosUnlitSchemaFile);
  89. ctx.IgnoredByCodeEmitter("glTF Property");
  90. ctx.IgnoredByCodeEmitter("glTF Child of Root Property");
  91. ProcessSchema("ext.Unlit.g", ctx);
  92. }
  93. private static void _ProcessKhronosModelLightsPunctualExtension()
  94. {
  95. var ctx = LoadSchemaContext(Constants.KhronosModelLightsPunctualSchemaFile);
  96. ctx.IgnoredByCodeEmitter("glTF Property");
  97. ctx.IgnoredByCodeEmitter("glTF Child of Root Property");
  98. ctx.FindClass("light")
  99. .GetField("color")
  100. .SetDataType(typeof(System.Numerics.Vector3), true)
  101. .SetDefaultValue("Vector3.One")
  102. .SetItemsRange(0);
  103. ProcessSchema("ext.ModelLightsPunctual.g", ctx);
  104. }
  105. private static void _ProcessKhronosNodeLightsPunctualExtension()
  106. {
  107. var ctx = LoadSchemaContext(Constants.KhronosNodeLightsPunctualSchemaFile);
  108. ctx.IgnoredByCodeEmitter("glTF Property");
  109. ctx.IgnoredByCodeEmitter("glTF Child of Root Property");
  110. ProcessSchema("ext.NodeLightsPunctual.g", ctx);
  111. }
  112. private static void _ProcessKhronosTextureTransformExtension()
  113. {
  114. var ctx = LoadSchemaContext(Constants.KhronosTextureTransformSchemaFile);
  115. ctx.IgnoredByCodeEmitter("glTF Property");
  116. ctx.IgnoredByCodeEmitter("glTF Child of Root Property");
  117. var tex = ctx.FindClass("KHR_texture_transform textureInfo extension");
  118. tex.GetField("offset")
  119. .SetDataType(typeof(System.Numerics.Vector2), true)
  120. .SetDefaultValue("Vector2.One")
  121. .SetItemsRange(0);
  122. tex.GetField("scale")
  123. .SetDataType(typeof(System.Numerics.Vector2), true)
  124. .SetDefaultValue("Vector2.One")
  125. .SetItemsRange(0);
  126. ProcessSchema("ext.TextureTransform.g", ctx);
  127. }
  128. #endregion
  129. #region code generation
  130. private static string _FindTargetDirectory(string dstDir)
  131. {
  132. var dir = Constants.LocalRepoDirectory;
  133. while(dir.Length > 3)
  134. {
  135. var xdir = System.IO.Path.Combine(dir, dstDir);
  136. if (System.IO.Directory.Exists(xdir)) return xdir;
  137. dir = System.IO.Path.GetDirectoryName(dir); // move up
  138. }
  139. return null;
  140. }
  141. private static void ProcessSchema(string dstFile, SchemaType.Context ctx)
  142. {
  143. var newEmitter = new CSharpEmitter();
  144. newEmitter.DeclareContext(ctx);
  145. newEmitter.SetCollectionContainer("List<TItem>");
  146. const string rootName = "ModelRoot";
  147. newEmitter.SetRuntimeName("glTF", rootName);
  148. newEmitter.SetRuntimeName("glTF Property", "ExtraProperties");
  149. newEmitter.SetRuntimeName("glTF Child of Root Property", "LogicalChildOfRoot");
  150. newEmitter.SetRuntimeName("Sampler", "TextureSampler");
  151. newEmitter.SetRuntimeName("UNSIGNED_BYTE-UNSIGNED_INT-UNSIGNED_SHORT", "IndexEncodingType");
  152. newEmitter.SetRuntimeName("BYTE-FLOAT-SHORT-UNSIGNED_BYTE-UNSIGNED_INT-UNSIGNED_SHORT", "EncodingType");
  153. newEmitter.SetRuntimeName("MAT2-MAT3-MAT4-SCALAR-VEC2-VEC3-VEC4", "DimensionType");
  154. newEmitter.SetRuntimeName("rotation-scale-translation-weights", "PropertyPath");
  155. newEmitter.SetRuntimeName("ARRAY_BUFFER-ELEMENT_ARRAY_BUFFER", "BufferMode");
  156. newEmitter.SetRuntimeName("orthographic-perspective", "CameraType");
  157. newEmitter.SetRuntimeName("BLEND-MASK-OPAQUE", "AlphaMode");
  158. newEmitter.SetRuntimeName("LINE_LOOP-LINE_STRIP-LINES-POINTS-TRIANGLE_FAN-TRIANGLE_STRIP-TRIANGLES", "PrimitiveType");
  159. newEmitter.SetRuntimeName("CUBICSPLINE-LINEAR-STEP", "AnimationInterpolationMode");
  160. newEmitter.SetRuntimeName("LINEAR-NEAREST", "TextureInterpolationFilter");
  161. newEmitter.SetRuntimeName("CLAMP_TO_EDGE-MIRRORED_REPEAT-REPEAT", "TextureWrapMode");
  162. newEmitter.SetRuntimeName("LINEAR-LINEAR_MIPMAP_LINEAR-LINEAR_MIPMAP_NEAREST-NEAREST-NEAREST_MIPMAP_LINEAR-NEAREST_MIPMAP_NEAREST", "TextureMipMapFilter");
  163. newEmitter.SetRuntimeName("KHR_materials_pbrSpecularGlossiness glTF extension", "MaterialPBRSpecularGlossiness");
  164. newEmitter.SetRuntimeName("KHR_materials_unlit glTF extension", "MaterialUnlit");
  165. newEmitter.SetRuntimeName("light", "PunctualLight");
  166. newEmitter.SetRuntimeName("light/spot", "PunctualLightSpot");
  167. newEmitter.SetRuntimeName("KHR_texture_transform textureInfo extension", "TextureTransform");
  168. var classes = ctx.Classes.ToArray();
  169. var fields = classes.SelectMany(item => item.Fields).ToArray();
  170. var meshClass = ctx.FindClass("Mesh");
  171. if (meshClass != null)
  172. {
  173. newEmitter.SetCollectionContainer(meshClass.UseField("primitives"), "ChildrenCollection<TItem,Mesh>");
  174. }
  175. var animationClass = ctx.FindClass("Animation");
  176. if (animationClass != null)
  177. {
  178. newEmitter.SetCollectionContainer(animationClass.UseField("channels"), "ChildrenCollection<TItem,Animation>");
  179. newEmitter.SetCollectionContainer(animationClass.UseField("samplers"), "ChildrenCollection<TItem,Animation>");
  180. }
  181. foreach (var f in fields)
  182. {
  183. if (f.FieldType is ArrayType atype)
  184. {
  185. if (atype.ItemType is ClassType ctype)
  186. {
  187. if (ctype.BaseClass != null && ctype.BaseClass.PersistentName == "glTF Child of Root Property")
  188. {
  189. newEmitter.SetCollectionContainer(f, $"ChildrenCollection<TItem,{rootName}>");
  190. }
  191. }
  192. }
  193. }
  194. var textOut = newEmitter.EmitContext(ctx);
  195. var dstDir = _FindTargetDirectory(Constants.TargetProjectDirectory);
  196. var dstPath = System.IO.Path.Combine(dstDir, $"{dstFile}.cs");
  197. System.IO.File.WriteAllText(dstPath, textOut);
  198. }
  199. #endregion
  200. #region schema loader
  201. private static SchemaType.Context LoadSchemaContext(string srcSchema)
  202. {
  203. var schema = LoadSchema(srcSchema);
  204. var settings = new NJsonSchema.CodeGeneration.CSharp.CSharpGeneratorSettings
  205. {
  206. Namespace = "glTf.POCO",
  207. ClassStyle = NJsonSchema.CodeGeneration.CSharp.CSharpClassStyle.Poco
  208. };
  209. var ctypes = new NJsonSchema.CodeGeneration.CSharp.CSharpTypeResolver(settings);
  210. ctypes.Resolve(schema, false, null);
  211. return SchemaTypesReader.Generate(ctypes);
  212. }
  213. static NJsonSchema.JsonSchema4 LoadSchema(string filePath)
  214. {
  215. // https://blogs.msdn.microsoft.com/benjaminperkins/2017/03/08/how-to-call-an-async-method-from-a-console-app-main-method/
  216. if (!System.IO.File.Exists(filePath)) throw new System.IO.FileNotFoundException(nameof(filePath), filePath);
  217. return NJsonSchema.JsonSchema4
  218. .FromFileAsync(filePath, s => _Resolver(s,filePath) )
  219. .ConfigureAwait(false)
  220. .GetAwaiter()
  221. .GetResult();
  222. }
  223. static NJsonSchema.JsonReferenceResolver _Resolver(NJsonSchema.JsonSchema4 schema, string basePath)
  224. {
  225. var solver = new NJsonSchema.JsonSchemaResolver(schema, new NJsonSchema.Generation.JsonSchemaGeneratorSettings());
  226. return new MyReferenceResolver(solver);
  227. }
  228. class MyReferenceResolver : NJsonSchema.JsonReferenceResolver
  229. {
  230. public MyReferenceResolver(NJsonSchema.JsonSchemaResolver resolver) : base(resolver) { }
  231. public override Task<IJsonReference> ResolveFileReferenceAsync(string filePath)
  232. {
  233. if (System.IO.File.Exists(filePath)) return base.ResolveFileReferenceAsync(filePath);
  234. filePath = System.IO.Path.GetFileName(filePath);
  235. filePath = System.IO.Path.Combine(Constants.MainSchemaDir, filePath);
  236. if (System.IO.File.Exists(filePath)) return base.ResolveFileReferenceAsync(filePath);
  237. throw new System.IO.FileNotFoundException(filePath);
  238. }
  239. }
  240. #endregion
  241. }
  242. }