Program.cs 14 KB

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