Program.cs 21 KB

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