Program.cs 17 KB

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