babylon.glTFFileLoader.ts 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656
  1. module BABYLON {
  2. /**
  3. * Enums
  4. */
  5. export enum EComponentType {
  6. BYTE = 5120,
  7. UNSIGNED_BYTE = 5121,
  8. SHORT = 5122,
  9. UNSIGNED_SHORT = 5123,
  10. FLOAT = 5126
  11. }
  12. export enum EShaderType {
  13. FRAGMENT = 35632,
  14. VERTEX = 35633
  15. }
  16. export enum EParameterType {
  17. BYTE = 5120,
  18. UNSIGNED_BYTE = 5121,
  19. SHORT = 5122,
  20. UNSIGNED_SHORT = 5123,
  21. INT = 5124,
  22. UNSIGNED_INT = 5125,
  23. FLOAT = 5126,
  24. FLOAT_VEC2 = 35664,
  25. FLOAT_VEC3 = 35665,
  26. FLOAT_VEC4 = 35666,
  27. INT_VEC2 = 35667,
  28. INT_VEC3 = 35668,
  29. INT_VEC4 = 35669,
  30. BOOL = 35670,
  31. BOOL_VEC2 = 35671,
  32. BOOL_VEC3 = 35672,
  33. BOOL_VEC4 = 35673,
  34. FLOAT_MAT2 = 35674,
  35. FLOAT_MAT3 = 35675,
  36. FLOAT_MAT4 = 35676,
  37. SAMPLER_2D = 35678
  38. }
  39. export enum ETextureWrapMode {
  40. CLAMP_TO_EDGE = 33071,
  41. MIRRORED_REPEAT = 33648,
  42. REPEAT = 10497
  43. }
  44. export enum ETextureFilterType {
  45. NEAREST = 9728,
  46. LINEAR = 9728,
  47. NEAREST_MIPMAP_NEAREST = 9984,
  48. LINEAR_MIPMAP_NEAREST = 9985,
  49. NEAREST_MIPMAP_LINEAR = 9986,
  50. LINEAR_MIPMAP_LINEAR = 9987
  51. }
  52. export enum ETextureFormat {
  53. ALPHA = 6406,
  54. RGB = 6407,
  55. RGBA = 6408,
  56. LUMINANCE = 6409,
  57. LUMINANCE_ALPHA = 6410
  58. }
  59. export enum ECullingType {
  60. FRONT = 1028,
  61. BACK = 1029,
  62. FRONT_AND_BACK = 1032
  63. }
  64. export enum EBlendingFunction {
  65. ZERO = 0,
  66. ONE = 1,
  67. SRC_COLOR = 768,
  68. ONE_MINUS_SRC_COLOR = 769,
  69. DST_COLOR = 774,
  70. ONE_MINUS_DST_COLOR = 775,
  71. SRC_ALPHA = 770,
  72. ONE_MINUS_SRC_ALPHA = 771,
  73. DST_ALPHA = 772,
  74. ONE_MINUS_DST_ALPHA = 773,
  75. CONSTANT_COLOR = 32769,
  76. ONE_MINUS_CONSTANT_COLOR = 32770,
  77. CONSTANT_ALPHA = 32771,
  78. ONE_MINUS_CONSTANT_ALPHA = 32772,
  79. SRC_ALPHA_SATURATE = 776
  80. }
  81. /**
  82. * Tokenizer. Used for shaders compatibility
  83. * Automatically map world, view, projection, worldViewProjection and attributes
  84. */
  85. enum ETokenType {
  86. IDENTIFIER = 1,
  87. UNKNOWN = 2,
  88. END_OF_INPUT = 3
  89. }
  90. class Tokenizer {
  91. private _toParse: string;
  92. private _pos: number = 0;
  93. private _maxPos: number;
  94. public currentToken: ETokenType;
  95. public currentIdentifier: string;
  96. public currentString: string;
  97. public isLetterOrDigitPattern: RegExp = /^[a-zA-Z0-9]+$/;
  98. constructor(toParse: string) {
  99. this._toParse = toParse;
  100. this._maxPos = toParse.length;
  101. }
  102. public getNextToken(): ETokenType {
  103. if (this.isEnd()) return ETokenType.END_OF_INPUT;
  104. this.currentString = this.read();
  105. this.currentToken = ETokenType.UNKNOWN;
  106. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  107. this.currentToken = ETokenType.IDENTIFIER;
  108. this.currentIdentifier = this.currentString;
  109. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  110. this.currentIdentifier += this.currentString;
  111. this.forward();
  112. }
  113. }
  114. return this.currentToken;
  115. }
  116. public peek(): string {
  117. return this._toParse[this._pos];
  118. }
  119. public read(): string {
  120. return this._toParse[this._pos++];
  121. }
  122. public forward(): void {
  123. this._pos++;
  124. }
  125. public isEnd(): boolean {
  126. return this._pos >= this._maxPos;
  127. }
  128. }
  129. /**
  130. * Values
  131. */
  132. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  133. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  134. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  135. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  136. /**
  137. * Parse
  138. */
  139. var parseBuffers = (parsedBuffers: any, gltfRuntime: IGLTFRuntime) => {
  140. for (var buf in parsedBuffers) {
  141. var parsedBuffer = parsedBuffers[buf];
  142. gltfRuntime.buffers[buf] = parsedBuffer;
  143. gltfRuntime.buffersCount++;
  144. }
  145. };
  146. var parseShaders = (parsedShaders: any, gltfRuntime: IGLTFRuntime) => {
  147. for (var sha in parsedShaders) {
  148. var parsedShader = parsedShaders[sha];
  149. gltfRuntime.shaders[sha] = parsedShader;
  150. gltfRuntime.shaderscount++;
  151. }
  152. };
  153. var parseObject = (parsedObjects: any, runtimeProperty: string, gltfRuntime: IGLTFRuntime) => {
  154. for (var object in parsedObjects) {
  155. var parsedObject = parsedObjects[object];
  156. gltfRuntime[runtimeProperty][object] = parsedObject;
  157. }
  158. };
  159. /**
  160. * Utils
  161. */
  162. var getByteStrideFromType = (accessor: IGLTFAccessor): number => {
  163. // Needs this function since "byteStride" isn't requiered in glTF format
  164. var type = accessor.type;
  165. switch (type) {
  166. case "VEC2": return 2;
  167. case "VEC3": return 3;
  168. case "VEC4": return 4;
  169. case "MAT2": return 4;
  170. case "MAT3": return 9;
  171. case "MAT4": return 16;
  172. default: return 1;
  173. }
  174. };
  175. var setMatrix = (scene: Scene, source: Node, parameter: IGLTFTechniqueParameter, uniformName: string, shaderMaterial: any) => {
  176. var mat: Matrix = null;
  177. if (parameter.semantic === "MODEL") {
  178. mat = source.getWorldMatrix();
  179. }
  180. else if (parameter.semantic === "PROJECTION") {
  181. mat = scene.getProjectionMatrix();
  182. }
  183. else if (parameter.semantic === "VIEW") {
  184. mat = scene.getViewMatrix();
  185. }
  186. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  187. mat = Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  188. }
  189. else if (parameter.semantic === "MODELVIEW") {
  190. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  191. }
  192. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  193. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  194. }
  195. else if (parameter.semantic === "MODELINVERSE") {
  196. mat = source.getWorldMatrix().invert();
  197. }
  198. else if (parameter.semantic === "VIEWINVERSE") {
  199. mat = scene.getViewMatrix().invert();
  200. }
  201. else if (parameter.semantic === "PROJECTIONINVERSE") {
  202. mat = scene.getProjectionMatrix().invert();
  203. }
  204. else if (parameter.semantic === "MODELVIEWINVERSE") {
  205. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  206. }
  207. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  208. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  209. }
  210. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  211. mat = Matrix.Transpose(source.getWorldMatrix().invert());
  212. }
  213. else {
  214. debugger;
  215. }
  216. switch (parameter.type) {
  217. case EParameterType.FLOAT_MAT2: shaderMaterial.setMatrix2x2(uniformName, Matrix.GetAsMatrix2x2(mat)); break;
  218. case EParameterType.FLOAT_MAT3: shaderMaterial.setMatrix3x3(uniformName, Matrix.GetAsMatrix3x3(mat)); break;
  219. case EParameterType.FLOAT_MAT4: shaderMaterial.setMatrix(uniformName, mat); break;
  220. default: break;
  221. }
  222. };
  223. var setUniform = (shaderMaterial: any, uniform: string, value: any, type: number): boolean => {
  224. switch (type) {
  225. case EParameterType.FLOAT: shaderMaterial.setFloat(uniform, value); return true;
  226. case EParameterType.FLOAT_VEC2: shaderMaterial.setVector2(uniform, Vector2.FromArray(value)); return true;
  227. case EParameterType.FLOAT_VEC3: shaderMaterial.setVector3(uniform, Vector3.FromArray(value)); return true;
  228. case EParameterType.FLOAT_VEC4: shaderMaterial.setVector4(uniform, Vector4.FromArray(value)); return true;
  229. default: return false;
  230. }
  231. };
  232. var getWrapMode = (mode: number): number => {
  233. switch (mode) {
  234. case ETextureWrapMode.CLAMP_TO_EDGE: return Texture.CLAMP_ADDRESSMODE;
  235. case ETextureWrapMode.MIRRORED_REPEAT: return Texture.MIRROR_ADDRESSMODE;
  236. case ETextureWrapMode.REPEAT: return Texture.WRAP_ADDRESSMODE;
  237. default: return Texture.WRAP_ADDRESSMODE;
  238. }
  239. };
  240. var getTextureFilterMode = (mode: number): ETextureFilterType => {
  241. switch (mode) {
  242. case ETextureFilterType.LINEAR:
  243. case ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  244. case ETextureFilterType.LINEAR_MIPMAP_LINEAR: return Texture.TRILINEAR_SAMPLINGMODE;
  245. case ETextureFilterType.NEAREST:
  246. case ETextureFilterType.NEAREST_MIPMAP_NEAREST: return Texture.NEAREST_SAMPLINGMODE;
  247. default: return Texture.BILINEAR_SAMPLINGMODE;
  248. }
  249. };
  250. var getBufferFromAccessor = (gltfRuntime: IGLTFRuntime, accessor: IGLTFAccessor): any => {
  251. var bufferView: IGLTFBufferView = gltfRuntime.bufferViews[accessor.bufferView];
  252. var arrayBuffer: ArrayBuffer = gltfRuntime.arrayBuffers[bufferView.buffer];
  253. var byteOffset = accessor.byteOffset + bufferView.byteOffset;
  254. var count = accessor.count * getByteStrideFromType(accessor);
  255. switch (accessor.componentType) {
  256. case EComponentType.BYTE: return new Int8Array(arrayBuffer, byteOffset, count);
  257. case EComponentType.UNSIGNED_BYTE: return new Uint8Array(arrayBuffer, byteOffset, count);
  258. case EComponentType.SHORT: return new Int16Array(arrayBuffer, byteOffset, count);
  259. case EComponentType.UNSIGNED_SHORT: return new Uint16Array(arrayBuffer, byteOffset, count);
  260. default: return new Float32Array(arrayBuffer, byteOffset, count);
  261. }
  262. };
  263. var normalizeUVs = (buffer: any) => {
  264. if (!buffer) {
  265. return;
  266. }
  267. for (var i = 0; i < buffer.length / 2; i++) {
  268. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  269. }
  270. };
  271. var replaceInString = (str: string, searchValue: string, replaceValue: string) => {
  272. while (str.indexOf(searchValue) !== -1) {
  273. str = str.replace(searchValue, replaceValue);
  274. }
  275. return str;
  276. };
  277. var getAttribute = (attributeParameter: IGLTFTechniqueParameter) => {
  278. if (attributeParameter.semantic === "NORMAL") {
  279. return "normal";
  280. } else if (attributeParameter.semantic === "POSITION") {
  281. return "position";
  282. } else if (attributeParameter.semantic === "JOINT") {
  283. return "matricesIndices";
  284. } else if (attributeParameter.semantic === "WEIGHT") {
  285. return "matricesWeights";
  286. } else if (attributeParameter.semantic === "COLOR") {
  287. return "color";
  288. } else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  289. var channel = Number(attributeParameter.semantic.split("_")[1]);
  290. return "uv" + (channel === 0 ? "" : channel + 1);
  291. }
  292. };
  293. var isBase64 = (uri: string): boolean => {
  294. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  295. };
  296. /**
  297. * Returns the animation path (glTF -> Babylon)
  298. */
  299. var getAnimationPath = (path: string): string => {
  300. var index = glTFAnimationPaths.indexOf(path);
  301. if (index !== -1) {
  302. return babylonAnimationPaths[index];
  303. }
  304. return path;
  305. };
  306. /**
  307. * Loads and creates animations
  308. */
  309. var loadAnimations = (gltfRuntime: IGLTFRuntime) => {
  310. for (var anim in gltfRuntime.animations) {
  311. var animation: IGLTFAnimation = gltfRuntime.animations[anim];
  312. for (var i = 0; i < animation.channels.length; i++) {
  313. // Get parameters and load buffers
  314. var channel = animation.channels[i];
  315. var sampler: IGLTFAnimationSampler = animation.samplers[channel.sampler];
  316. if (!sampler) {
  317. continue;
  318. }
  319. var inputData = animation.parameters[sampler.input];
  320. var outputData = animation.parameters[sampler.output];
  321. var bufferInput = getBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  322. var bufferOutput = getBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  323. var targetID = channel.target.id;
  324. var targetNode: any = gltfRuntime.scene.getNodeByID(targetID);
  325. if (targetNode === null) {
  326. Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  327. continue;
  328. }
  329. var isBone = targetNode instanceof Bone;
  330. // Get target path (position, rotation or scaling)
  331. var targetPath = channel.target.path;
  332. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  333. if (targetPathIndex !== -1) {
  334. targetPath = babylonAnimationPaths[targetPathIndex];
  335. }
  336. // Determine animation type
  337. var animationType = Animation.ANIMATIONTYPE_MATRIX;
  338. if (!isBone) {
  339. if (targetPath === "rotationQuaternion") {
  340. animationType = Animation.ANIMATIONTYPE_QUATERNION;
  341. targetNode.rotationQuaternion = new Quaternion();
  342. }
  343. else {
  344. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  345. }
  346. }
  347. // Create animation and key frames
  348. var babylonAnimation = new Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, Animation.ANIMATIONLOOPMODE_CYCLE);
  349. var keys = [];
  350. var arrayOffset = 0;
  351. // For each frame
  352. for (var j = 0; j < bufferInput.length; j++) {
  353. var value: any = null;
  354. if (targetPath === "rotationQuaternion") { // VEC4
  355. //value = Quaternion.RotationAxis(Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]).normalize(), bufferOutput[arrayOffset + 3]);
  356. value = Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  357. arrayOffset += 4;
  358. }
  359. else { // Position and scaling are VEC3
  360. value = Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  361. arrayOffset += 3;
  362. }
  363. if (isBone) {
  364. var bone = <Bone>targetNode;
  365. var translation = Vector3.Zero();
  366. var rotationQuaternion = new Quaternion();
  367. var scaling = Vector3.Zero();
  368. // Warning on decompose
  369. var mat = bone.getBaseMatrix();
  370. mat.decompose(scaling, rotationQuaternion, translation);
  371. if (targetPath === "position") {
  372. translation = value;
  373. }
  374. else if (targetPath === "rotationQuaternion") {
  375. rotationQuaternion = value;
  376. }
  377. else {
  378. scaling = value;
  379. }
  380. value = Matrix.Compose(scaling, rotationQuaternion, translation);
  381. }
  382. keys.push({
  383. frame: bufferInput[j],
  384. value: value
  385. });
  386. }
  387. // Finish
  388. babylonAnimation.setKeys(keys);
  389. targetNode.animations.push(babylonAnimation);
  390. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  391. }
  392. }
  393. };
  394. /**
  395. * Returns the bones transformation matrix
  396. */
  397. var configureBoneTransformation = (node: IGLTFNode): Matrix => {
  398. var mat: Matrix = null;
  399. if (node.translation && node.rotation && node.scale) {
  400. var scale = Vector3.FromArray(node.scale);
  401. var rotation = Quaternion.FromArray(node.rotation);
  402. var position = Vector3.FromArray(node.translation);
  403. mat = Matrix.Compose(scale, rotation, position);
  404. }
  405. else {
  406. mat = Matrix.FromArray(node.matrix);
  407. }
  408. return mat;
  409. };
  410. /**
  411. * Returns the parent bone
  412. */
  413. var getParentBone = (jointName: string, newSkeleton: Skeleton): Bone => {
  414. // Try to find
  415. for (var i = 0; i < newSkeleton.bones.length; i++) {
  416. if (newSkeleton.bones[i].id === jointName) {
  417. return newSkeleton.bones[i];
  418. }
  419. }
  420. }
  421. /**
  422. * Imports a skeleton
  423. */
  424. var importSkeleton = (gltfRuntime: IGLTFRuntime, skins: IGLTFSkins, mesh: Mesh, newSkeleton: Skeleton): Skeleton => {
  425. if (!newSkeleton) {
  426. newSkeleton = new Skeleton(skins.name, "", gltfRuntime.scene);
  427. }
  428. if (!skins.babylonSkeleton) {
  429. return newSkeleton;
  430. }
  431. // Matrices
  432. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  433. var buffer = getBufferFromAccessor(gltfRuntime, accessor);
  434. var bindShapeMatrix = Matrix.FromArray(skins.bindShapeMatrix);
  435. (<any>newSkeleton)._identity = bindShapeMatrix;
  436. // Find the root bone
  437. var nodeToRoot: Bone = null;
  438. for (var nde in gltfRuntime.nodes) {
  439. var node: IGLTFNode = gltfRuntime.nodes[nde];
  440. if (!node) {
  441. continue;
  442. }
  443. if (node.jointName) {
  444. var isInJoints = false;
  445. for (var i = 0; i < skins.jointNames.length; i++) {
  446. if (skins.jointNames[i] === nde) {
  447. isInJoints = true;
  448. break;
  449. }
  450. }
  451. }
  452. if (!isInJoints) {
  453. var mat = configureBoneTransformation(node);
  454. nodeToRoot = new Bone(node.name, newSkeleton, null, mat);
  455. nodeToRoot.id = nde;
  456. // Remove root from bones
  457. newSkeleton.bones = [];
  458. break;
  459. }
  460. }
  461. // Joints
  462. for (var i = 0; i < skins.jointNames.length; i++) {
  463. var node: IGLTFNode = gltfRuntime.nodes[skins.jointNames[i]];
  464. if (!node) {
  465. Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  466. continue;
  467. }
  468. var id = skins.jointNames[i];
  469. // Check if node exists, should never happen
  470. var foundBone = false;
  471. for (var j = 0; j < newSkeleton.bones.length; j++) {
  472. if (newSkeleton.bones[j].id === id) {
  473. foundBone = true;
  474. break;
  475. }
  476. }
  477. if (foundBone) {
  478. continue;
  479. }
  480. // Search for parent bone
  481. var parentBone = null;
  482. for (var j = 0; j < i; j++) {
  483. var joint: IGLTFNode = gltfRuntime.nodes[skins.jointNames[j]];
  484. if (!joint) {
  485. Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  486. continue;
  487. }
  488. var children = joint.children;
  489. foundBone = false;
  490. for (var k = 0; k < children.length; k++) {
  491. if (children[k] === id) {
  492. parentBone = getParentBone(skins.jointNames[j], newSkeleton);
  493. foundBone = true;
  494. break;
  495. }
  496. }
  497. if (foundBone) {
  498. break;
  499. }
  500. }
  501. // Create bone
  502. var mat = configureBoneTransformation(node);
  503. var bone = new Bone(node.name, newSkeleton, parentBone ? parentBone : nodeToRoot, mat);
  504. bone.id = id;
  505. }
  506. newSkeleton.prepare();
  507. if (nodeToRoot) {
  508. newSkeleton.bones.push(nodeToRoot);
  509. }
  510. return newSkeleton;
  511. };
  512. /**
  513. * Imports a mesh and its geometries
  514. */
  515. var importMesh = (gltfRuntime: IGLTFRuntime, node: IGLTFNode, meshes: string[], id: string, newMesh: Mesh): Mesh => {
  516. if (!newMesh) {
  517. newMesh = new Mesh(node.name, gltfRuntime.scene);
  518. newMesh.id = id;
  519. }
  520. if (!node.babylonNode) {
  521. return newMesh;
  522. }
  523. var multiMat = new MultiMaterial("multimat" + id, gltfRuntime.scene);
  524. newMesh.material = multiMat;
  525. var vertexData = new VertexData();
  526. var geometry = new Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  527. var verticesStarts = [];
  528. var verticesCounts = [];
  529. var indexStarts = [];
  530. var indexCounts = [];
  531. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  532. var meshID = meshes[meshIndex];
  533. var mesh: IGLTFMesh = gltfRuntime.meshes[meshID];
  534. if (!mesh) {
  535. continue;
  536. }
  537. // Positions, normals and UVs
  538. for (var i = 0; i < mesh.primitives.length; i++) {
  539. // Temporary vertex data
  540. var tempVertexData = new VertexData();
  541. var primitive = mesh.primitives[i];
  542. if (primitive.mode !== 4) {
  543. //continue;
  544. }
  545. var attributes = primitive.attributes;
  546. var accessor: IGLTFAccessor = null;
  547. var buffer: any = null;
  548. // Set positions, normal and uvs
  549. for (var semantic in attributes) {
  550. // Link accessor and buffer view
  551. accessor = gltfRuntime.accessors[attributes[semantic]];
  552. buffer = getBufferFromAccessor(gltfRuntime, accessor);
  553. if (semantic === "NORMAL") {
  554. tempVertexData.normals = [];
  555. for (var j = 0; j < buffer.length; j++) {
  556. (<number[]>tempVertexData.normals).push(buffer[j]);
  557. }
  558. }
  559. else if (semantic === "POSITION") {
  560. tempVertexData.positions = [];
  561. for (var j = 0; j < buffer.length; j++) {
  562. (<number[]>tempVertexData.positions).push(buffer[j]);
  563. }
  564. verticesCounts.push(tempVertexData.positions.length);
  565. }
  566. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  567. var channel = Number(semantic.split("_")[1]);
  568. var uvKind = VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  569. var uvs = [];
  570. for (var j = 0; j < buffer.length; j++) {
  571. uvs.push(buffer[j]);
  572. }
  573. normalizeUVs(uvs);
  574. tempVertexData.set(uvs, uvKind);
  575. }
  576. else if (semantic === "JOINT") {
  577. tempVertexData.matricesIndices = [];
  578. for (var j = 0; j < buffer.length; j++) {
  579. (<number[]>tempVertexData.matricesIndices).push(buffer[j]);
  580. }
  581. }
  582. else if (semantic === "WEIGHT") {
  583. tempVertexData.matricesWeights = [];
  584. for (var j = 0; j < buffer.length; j++) {
  585. (<number[]>tempVertexData.matricesWeights).push(buffer[j]);
  586. }
  587. }
  588. else if (semantic === "COLOR") {
  589. tempVertexData.colors = [];
  590. for (var j = 0; j < buffer.length; j++) {
  591. (<number[]>tempVertexData.colors).push(buffer[j]);
  592. }
  593. }
  594. }
  595. // Indices
  596. accessor = gltfRuntime.accessors[primitive.indices];
  597. buffer = getBufferFromAccessor(gltfRuntime, accessor);
  598. tempVertexData.indices = [];
  599. for (var j = 0; j < buffer.length; j++) {
  600. (<number[]>tempVertexData.indices).push(buffer[j]);
  601. }
  602. indexCounts.push(buffer.length);
  603. vertexData.merge(tempVertexData);
  604. tempVertexData = undefined;
  605. // Sub material
  606. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  607. multiMat.subMaterials.push(material === null ? gltfRuntime.scene.defaultMaterial : material);
  608. // Update vertices start and index start
  609. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  610. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  611. }
  612. }
  613. // Apply geometry
  614. geometry.setAllVerticesData(vertexData, false);
  615. newMesh.flipFaces(true);
  616. newMesh.computeWorldMatrix(true);
  617. // Apply submeshes
  618. newMesh.subMeshes = [];
  619. var index = 0;
  620. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  621. var meshID = meshes[meshIndex];
  622. var mesh: IGLTFMesh = gltfRuntime.meshes[meshID];
  623. if (!mesh) {
  624. continue;
  625. }
  626. for (var i = 0; i < mesh.primitives.length; i++) {
  627. if (mesh.primitives[i].mode !== 4) {
  628. //continue;
  629. }
  630. var subMesh = new SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  631. index++;
  632. }
  633. }
  634. // Finish
  635. return newMesh;
  636. };
  637. /**
  638. * Configure node transformation from position, rotation and scaling
  639. */
  640. var configureNode = (newNode: any, position: Vector3, rotation: Quaternion, scaling: Vector3) => {
  641. if (newNode.position) {
  642. newNode.position = position;
  643. }
  644. if (newNode.rotationQuaternion || newNode.rotation) {
  645. newNode.rotationQuaternion = rotation;
  646. }
  647. if (newNode.scaling) {
  648. newNode.scaling = scaling;
  649. }
  650. };
  651. /**
  652. * Configures node from transformation matrix
  653. */
  654. var configureNodeFromMatrix = (newNode: any, node: IGLTFNode) => {
  655. if (node.matrix) {
  656. var position = new Vector3(0, 0, 0);
  657. var rotation = new Quaternion();
  658. var scaling = new Vector3(0, 0, 0);
  659. var mat = Matrix.FromArray(node.matrix);
  660. mat.decompose(scaling, rotation, position);
  661. configureNode(newNode, position, rotation, scaling);
  662. if (newNode instanceof TargetCamera) {
  663. (<TargetCamera>newNode).setTarget(Vector3.Zero());
  664. }
  665. }
  666. else {
  667. //configureNode(newNode, Vector3.FromArray(node.translation), Quaternion.RotationAxis(Vector3.FromArray(node.rotation), node.rotation[3]), Vector3.FromArray(node.scale));
  668. configureNode(newNode, Vector3.FromArray(node.translation), Quaternion.FromArray(node.rotation), Vector3.FromArray(node.scale));
  669. }
  670. };
  671. /**
  672. * Imports a node
  673. */
  674. var importNode = (gltfRuntime: IGLTFRuntime, node: IGLTFNode, id: string): Node => {
  675. var lastNode: Node = null;
  676. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  677. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  678. return null;
  679. }
  680. }
  681. // Meshes
  682. if (node.skin) {
  683. if (node.meshes) {
  684. var skin: IGLTFSkins = gltfRuntime.skins[node.skin];
  685. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, <Mesh>node.babylonNode);
  686. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  687. if (newMesh.skeleton === null) {
  688. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton);
  689. if (!skin.babylonSkeleton) {
  690. skin.babylonSkeleton = newMesh.skeleton;
  691. }
  692. }
  693. if (newMesh.skeleton !== null) {
  694. newMesh.useBones = true;
  695. }
  696. lastNode = newMesh;
  697. }
  698. }
  699. else if (node.meshes) {
  700. /**
  701. * Improve meshes property
  702. */
  703. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, <Mesh>node.babylonNode);
  704. lastNode = newMesh;
  705. }
  706. // Lights
  707. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  708. var light = gltfRuntime.lights[node.light];
  709. if (light) {
  710. if (light.type === "ambient") {
  711. var ambienLight: IGLTFAmbienLight = light[light.type];
  712. var hemiLight = new HemisphericLight(node.light, Vector3.Zero(), gltfRuntime.scene);
  713. hemiLight.name = node.name;
  714. if (ambienLight.color) {
  715. hemiLight.diffuse = Color3.FromArray(ambienLight.color);
  716. }
  717. lastNode = hemiLight;
  718. }
  719. else if (light.type === "directional") {
  720. var directionalLight: IGLTFDirectionalLight = light[light.type];
  721. var dirLight = new DirectionalLight(node.light, Vector3.Zero(), gltfRuntime.scene);
  722. dirLight.name = node.name;
  723. if (directionalLight.color) {
  724. dirLight.diffuse = Color3.FromArray(directionalLight.color);
  725. }
  726. lastNode = dirLight;
  727. }
  728. else if (light.type === "point") {
  729. var pointLight: IGLTFPointLight = light[light.type];
  730. var ptLight = new PointLight(node.light, Vector3.Zero(), gltfRuntime.scene);
  731. ptLight.name = node.name;
  732. if (pointLight.color) {
  733. ptLight.diffuse = Color3.FromArray(pointLight.color);
  734. }
  735. lastNode = ptLight;
  736. }
  737. else if (light.type === "spot") {
  738. var spotLight: IGLTFSpotLight = light[light.type];
  739. var spLight = new SpotLight(node.light, Vector3.Zero(), Vector3.Zero(), 0, 0, gltfRuntime.scene);
  740. spLight.name = node.name;
  741. if (spotLight.color) {
  742. spLight.diffuse = Color3.FromArray(spotLight.color);
  743. }
  744. if (spotLight.fallOfAngle) {
  745. spLight.angle = spotLight.fallOfAngle;
  746. }
  747. if (spotLight.fallOffExponent) {
  748. spLight.exponent = spotLight.fallOffExponent;
  749. }
  750. lastNode = spLight;
  751. }
  752. }
  753. }
  754. // Cameras
  755. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  756. var camera: IGLTFCamera = gltfRuntime.cameras[node.camera];
  757. if (camera) {
  758. if (camera.type === "orthographic") {
  759. var orthographicCamera: IGLTFCameraOrthographic = camera[camera.type];
  760. var orthoCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene);
  761. orthoCamera.name = node.name;
  762. orthoCamera.mode = Camera.ORTHOGRAPHIC_CAMERA;
  763. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  764. lastNode = orthoCamera;
  765. }
  766. else if (camera.type === "perspective") {
  767. var perspectiveCamera: IGLTFCameraPerspective = camera[camera.type];
  768. var persCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene);
  769. persCamera.name = node.name;
  770. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  771. if (!perspectiveCamera.aspectRatio) {
  772. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  773. }
  774. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  775. persCamera.maxZ = perspectiveCamera.zfar;
  776. persCamera.minZ = perspectiveCamera.znear;
  777. }
  778. lastNode = persCamera;
  779. }
  780. }
  781. }
  782. // Empty node
  783. if (!node.jointName) {
  784. if (node.babylonNode) {
  785. return node.babylonNode;
  786. }
  787. else if (lastNode === null) {
  788. var dummy = new Mesh(node.name, gltfRuntime.scene);
  789. node.babylonNode = dummy;
  790. lastNode = dummy;
  791. }
  792. }
  793. if (lastNode !== null) {
  794. if (node.matrix) {
  795. configureNodeFromMatrix(lastNode, node);
  796. }
  797. else {
  798. configureNode(lastNode, Vector3.FromArray(node.translation), Quaternion.RotationAxis(Vector3.FromArray(node.rotation).normalize(), node.rotation[3]), Vector3.FromArray(node.scale));
  799. }
  800. lastNode.updateCache(true);
  801. node.babylonNode = lastNode;
  802. }
  803. return lastNode;
  804. };
  805. /**
  806. * Util for ImportMesh function, checks if a given node
  807. * is a descendant of the included mesh(es)
  808. */
  809. var nodeIsDescendantOf = (node: IGLTFRuntime, gltfRuntime: IGLTFRuntime): boolean => {
  810. for (var nde in gltfRuntime.nodes) {
  811. var n: IGLTFNode = gltfRuntime.nodes[nde];
  812. for (var i = 0; i < n.children.length; i++) {
  813. }
  814. }
  815. return false;
  816. }
  817. /**
  818. * Traverses nodes and creates them
  819. */
  820. var traverseNodes = (gltfRuntime: IGLTFRuntime, id: string, parent: Node, meshIncluded?: boolean) => {
  821. var node: IGLTFNode = gltfRuntime.nodes[id];
  822. var newNode: Node = null;
  823. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  824. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  825. meshIncluded = true;
  826. }
  827. else {
  828. meshIncluded = false;
  829. }
  830. }
  831. else {
  832. meshIncluded = true;
  833. }
  834. if (!node.jointName && meshIncluded) {
  835. newNode = importNode(gltfRuntime, node, id);
  836. if (newNode !== null) {
  837. newNode.id = id;
  838. newNode.parent = parent;
  839. }
  840. }
  841. for (var i = 0; i < node.children.length; i++) {
  842. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  843. }
  844. };
  845. /**
  846. * Buffers loaded, create nodes
  847. */
  848. var onBuffersLoaded = (gltfRuntime: IGLTFRuntime) => {
  849. // Nodes
  850. var currentScene: IGLTFScene = <IGLTFScene>gltfRuntime.currentScene;
  851. for (var i = 0; i < currentScene.nodes.length; i++) {
  852. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  853. }
  854. // Set animations
  855. loadAnimations(gltfRuntime);
  856. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  857. var skeleton = gltfRuntime.scene.skeletons[i];
  858. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  859. }
  860. };
  861. /**
  862. * On a buffer is loaded
  863. */
  864. var onLoadBuffer = (gltfRuntime: IGLTFRuntime, buf: string) => {
  865. return (data: any) => {
  866. gltfRuntime.loadedBuffers++;
  867. if (!(data instanceof ArrayBuffer)) {
  868. Tools.Error("Buffer named " + buf + " is not an array buffer");
  869. }
  870. else if ((<ArrayBuffer>data).byteLength != gltfRuntime.buffers[buf].byteLength) {
  871. Tools.Error("Buffer named " + buf + " is length " + data.byteLength + ". Expected: " + gltfRuntime.buffers[buf].byteLength); // Improve error message
  872. }
  873. gltfRuntime.arrayBuffers[buf] = data;
  874. if (gltfRuntime.loadedBuffers === gltfRuntime.buffersCount) {
  875. onBuffersLoaded(gltfRuntime);
  876. }
  877. };
  878. };
  879. /**
  880. * Error when loaded buffer
  881. */
  882. var onLoadBufferError = (gltfRuntime: IGLTFRuntime, buf: string) => {
  883. return () => {
  884. Tools.Error("Error when loading buffer named " + buf + " located at " + gltfRuntime.buffers[buf].uri);
  885. };
  886. };
  887. /**
  888. * Decode array buffer from base64
  889. */
  890. var decodeArrayBuffer = (base64: string): ArrayBuffer => {
  891. var decodedString = atob(base64);
  892. var bufferLength = decodedString.length;
  893. var arraybuffer = new Uint8Array(new ArrayBuffer(bufferLength));
  894. for (var i = 0; i < bufferLength; i++) {
  895. arraybuffer[i] = decodedString.charCodeAt(i);
  896. }
  897. return arraybuffer.buffer;
  898. };
  899. /**
  900. * Loads buffers (geometries)
  901. */
  902. var loadBuffers = (gltfRuntime: IGLTFRuntime) => {
  903. for (var buf in gltfRuntime.buffers) {
  904. var buffer: IGLTFBuffer = gltfRuntime.buffers[buf];
  905. if (buffer) {
  906. if (isBase64(buffer.uri)) {
  907. var arrayBuffer = decodeArrayBuffer(buffer.uri.split(",")[1]);
  908. onLoadBuffer(gltfRuntime, buf)(arrayBuffer);
  909. }
  910. else {
  911. Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, onLoadBuffer(gltfRuntime, buf), null, null, true, onLoadBufferError(gltfRuntime, buf));
  912. }
  913. }
  914. else {
  915. Tools.Error("No buffer named : " + buf);
  916. }
  917. }
  918. };
  919. /**
  920. * onBind shaderrs callback to set uniforms and matrices
  921. */
  922. var onBindShaderMaterial = (mesh: Mesh, gltfRuntime: IGLTFRuntime, unTreatedUniforms: Object, shaderMaterial: ShaderMaterial, technique: IGLTFTechnique, material: IGLTFMaterial) => {
  923. for (var unif in unTreatedUniforms) {
  924. var uniform: IGLTFTechniqueParameter = unTreatedUniforms[unif];
  925. var type = uniform.type;
  926. if (type === EParameterType.FLOAT_MAT2 || type === EParameterType.FLOAT_MAT3 || type === EParameterType.FLOAT_MAT4) {
  927. if (uniform.semantic && !uniform.source && !uniform.node) {
  928. setMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  929. }
  930. else if (uniform.semantic && (uniform.source || uniform.node)) {
  931. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  932. if (source === null) {
  933. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  934. }
  935. if (source === null) {
  936. continue;
  937. }
  938. setMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  939. }
  940. }
  941. else {
  942. var value = material.values[technique.uniforms[unif]];
  943. if (!value) {
  944. continue;
  945. }
  946. if (type === EParameterType.SAMPLER_2D) {
  947. var texture: Texture = gltfRuntime.textures[value].babylonTexture;
  948. if (texture === null) {
  949. continue;
  950. }
  951. shaderMaterial.getEffect().setTexture(unif, texture);
  952. }
  953. else {
  954. setUniform(shaderMaterial.getEffect(), unif, value, type);
  955. }
  956. }
  957. }
  958. };
  959. /**
  960. * Prepare uniforms to send the only one time
  961. * Loads the appropriate textures
  962. */
  963. var prepareShaderMaterialUniforms = (gltfRuntime: IGLTFRuntime, shaderMaterial: ShaderMaterial, technique: IGLTFTechnique, material: IGLTFMaterial, unTreatedUniforms: Object) => {
  964. var materialValues = material.values;
  965. var techniqueUniforms = technique.uniforms;
  966. /**
  967. * Prepare values here (not matrices)
  968. */
  969. for (var unif in unTreatedUniforms) {
  970. var uniform: IGLTFTechniqueParameter = unTreatedUniforms[unif];
  971. var type = uniform.type;
  972. var value = materialValues[techniqueUniforms[unif]] || uniform.value;
  973. if (!value) {
  974. continue;
  975. }
  976. // Texture (sampler2D)
  977. if (type === EParameterType.SAMPLER_2D) {
  978. var texture: IGLTFTexture = gltfRuntime.textures[<string>value];
  979. var sampler: IGLTFSampler = gltfRuntime.samplers[texture.sampler];
  980. if (!texture || !texture.source) {
  981. continue;
  982. }
  983. var source: IGLTFImage = gltfRuntime.images[texture.source];
  984. var newTexture: Texture = null;
  985. var createMipMaps = (sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  986. (sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  987. (sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  988. (sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  989. var samplingMode = Texture.BILINEAR_SAMPLINGMODE;
  990. if (isBase64(source.uri)) {
  991. newTexture = new Texture(source.uri, gltfRuntime.scene, !createMipMaps, true, samplingMode, null, null, source.uri, true);
  992. }
  993. else {
  994. newTexture = new Texture(gltfRuntime.rootUrl + source.uri, gltfRuntime.scene, !createMipMaps, true, samplingMode);
  995. }
  996. newTexture.wrapU = getWrapMode(sampler.wrapS);
  997. newTexture.wrapV = getWrapMode(sampler.wrapT);
  998. newTexture.name = <string>value;
  999. texture.babylonTexture = newTexture;
  1000. if (uniform.value) {
  1001. // Static uniform
  1002. shaderMaterial.setTexture(unif, newTexture);
  1003. delete unTreatedUniforms[unif];
  1004. }
  1005. }
  1006. // Others
  1007. else {
  1008. if (uniform.value && setUniform(shaderMaterial, unif, value, type)) {
  1009. // Static uniform
  1010. delete unTreatedUniforms[unif];
  1011. }
  1012. }
  1013. }
  1014. };
  1015. /**
  1016. * Shader compilation failed
  1017. */
  1018. var onShaderCompileError = (program: IGLTFProgram, shaderMaterial: ShaderMaterial) => {
  1019. return (effect: Effect, error: string) => {
  1020. Tools.Error("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1021. shaderMaterial.dispose(true);
  1022. };
  1023. };
  1024. /**
  1025. * Shader compilation success
  1026. */
  1027. var onShaderCompileSuccess = (gltfRuntime: IGLTFRuntime, shaderMaterial: ShaderMaterial, technique: IGLTFTechnique, material: IGLTFMaterial, unTreatedUniforms: Object) => {
  1028. return (_: Effect) => {
  1029. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1030. shaderMaterial.onBind = (mat: Material, mesh: Mesh) => {
  1031. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material);
  1032. };
  1033. };
  1034. };
  1035. /**
  1036. * Returns the appropriate uniform if already handled by babylon
  1037. */
  1038. var parseShaderUniforms = (tokenizer: Tokenizer, technique: IGLTFTechnique, unTreatedUniforms: Object): string => {
  1039. for (var unif in technique.uniforms) {
  1040. var uniform = technique.uniforms[unif];
  1041. var uniformParameter: IGLTFTechniqueParameter = technique.parameters[uniform];
  1042. if (tokenizer.currentIdentifier === unif) {
  1043. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1044. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1045. if (transformIndex !== -1) {
  1046. delete unTreatedUniforms[unif];
  1047. return babylonTransforms[transformIndex];
  1048. }
  1049. }
  1050. }
  1051. }
  1052. return tokenizer.currentIdentifier;
  1053. };
  1054. /**
  1055. * All shaders loaded. Create materials one by one
  1056. */
  1057. var onShadersLoaded = (gltfRuntime: IGLTFRuntime) => {
  1058. // Create materials
  1059. for (var mat in gltfRuntime.materials) {
  1060. var material: IGLTFMaterial = gltfRuntime.materials[mat];
  1061. var technique: IGLTFTechnique = gltfRuntime.techniques[material.technique];
  1062. var program: IGLTFProgram = gltfRuntime.programs[technique.program];
  1063. var states: IGLTFTechniqueStates = technique.states;
  1064. var vertexShader: string = Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1065. var pixelShader: string = Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1066. var newVertexShader = "";
  1067. var newPixelShader = "";
  1068. var vertexTokenizer = new Tokenizer(vertexShader);
  1069. var pixelTokenizer = new Tokenizer(pixelShader);
  1070. var unTreatedUniforms: Object = {};
  1071. var uniforms = [];
  1072. var attributes = [];
  1073. var samplers = [];
  1074. // Fill uniform, sampler2D and attributes
  1075. for (var unif in technique.uniforms) {
  1076. var uniform = technique.uniforms[unif];
  1077. var uniformParameter: IGLTFTechniqueParameter = technique.parameters[uniform];
  1078. unTreatedUniforms[unif] = uniformParameter;
  1079. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1080. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1081. if (transformIndex !== -1) {
  1082. uniforms.push(babylonTransforms[transformIndex]);
  1083. delete unTreatedUniforms[unif];
  1084. }
  1085. else {
  1086. uniforms.push(unif);
  1087. }
  1088. }
  1089. else if (uniformParameter.type === EParameterType.SAMPLER_2D) {
  1090. samplers.push(unif);
  1091. }
  1092. else {
  1093. uniforms.push(unif);
  1094. }
  1095. }
  1096. for (var attr in technique.attributes) {
  1097. var attribute = technique.attributes[attr];
  1098. var attributeParameter: IGLTFTechniqueParameter = technique.parameters[attribute];
  1099. if (attributeParameter.semantic) {
  1100. attributes.push(getAttribute(attributeParameter));
  1101. }
  1102. }
  1103. // Configure vertex shader
  1104. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1105. var tokenType = vertexTokenizer.currentToken;
  1106. if (tokenType !== ETokenType.IDENTIFIER) {
  1107. newVertexShader += vertexTokenizer.currentString;
  1108. continue;
  1109. }
  1110. var foundAttribute = false;
  1111. for (var attr in technique.attributes) {
  1112. var attribute = technique.attributes[attr];
  1113. var attributeParameter: IGLTFTechniqueParameter = technique.parameters[attribute];
  1114. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1115. newVertexShader += getAttribute(attributeParameter);
  1116. foundAttribute = true;
  1117. break;
  1118. }
  1119. }
  1120. if (foundAttribute) {
  1121. continue;
  1122. }
  1123. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1124. }
  1125. // Configure pixel shader
  1126. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1127. var tokenType = pixelTokenizer.currentToken;
  1128. if (tokenType !== ETokenType.IDENTIFIER) {
  1129. newPixelShader += pixelTokenizer.currentString;
  1130. continue;
  1131. }
  1132. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1133. }
  1134. // Create shader material
  1135. var shaderPath = {
  1136. vertex: program.vertexShader,
  1137. fragment: program.fragmentShader
  1138. };
  1139. var options = {
  1140. attributes: attributes,
  1141. uniforms: uniforms,
  1142. samplers: samplers,
  1143. needAlphaBlending: states.functions && states.functions.blendEquationSeparate
  1144. };
  1145. Effect.ShadersStore[program.vertexShader + "VertexShader"] = newVertexShader;
  1146. Effect.ShadersStore[program.fragmentShader + "PixelShader"] = newPixelShader;
  1147. var shaderMaterial = new ShaderMaterial(material.name, gltfRuntime.scene, shaderPath, options);
  1148. shaderMaterial.id = mat;
  1149. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial);
  1150. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1151. if (states.functions) {
  1152. var functions = states.functions;
  1153. if (functions.cullFace && functions.cullFace[0] !== ECullingType.BACK) {
  1154. shaderMaterial.backFaceCulling = false;
  1155. }
  1156. var blendFunc = functions.blendFuncSeparate;
  1157. if (blendFunc) {
  1158. if (blendFunc[0] === EBlendingFunction.SRC_ALPHA && blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === EBlendingFunction.ONE && blendFunc[3] === EBlendingFunction.ONE) {
  1159. shaderMaterial.alphaMode = Engine.ALPHA_COMBINE;
  1160. }
  1161. else if (blendFunc[0] === EBlendingFunction.ONE && blendFunc[1] === EBlendingFunction.ONE && blendFunc[2] === EBlendingFunction.ZERO && blendFunc[3] === EBlendingFunction.ONE) {
  1162. shaderMaterial.alphaMode = Engine.ALPHA_ONEONE;
  1163. }
  1164. else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA && blendFunc[1] === EBlendingFunction.ONE && blendFunc[2] === EBlendingFunction.ZERO && blendFunc[3] === EBlendingFunction.ONE) {
  1165. shaderMaterial.alphaMode = Engine.ALPHA_ADD;
  1166. }
  1167. else if (blendFunc[0] === EBlendingFunction.ZERO && blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === EBlendingFunction.ONE && blendFunc[3] === EBlendingFunction.ONE) {
  1168. shaderMaterial.alphaMode = Engine.ALPHA_SUBTRACT;
  1169. }
  1170. else if (blendFunc[0] === EBlendingFunction.DST_COLOR && blendFunc[1] === EBlendingFunction.ZERO && blendFunc[2] === EBlendingFunction.ONE && blendFunc[3] === EBlendingFunction.ONE) {
  1171. shaderMaterial.alphaMode = Engine.ALPHA_MULTIPLY;
  1172. }
  1173. else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA && blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === EBlendingFunction.ONE && blendFunc[3] === EBlendingFunction.ONE) {
  1174. shaderMaterial.alphaMode = Engine.ALPHA_MAXIMIZED;
  1175. }
  1176. }
  1177. }
  1178. }
  1179. // Finish
  1180. loadBuffers(gltfRuntime);
  1181. };
  1182. /**
  1183. * Shader loaded
  1184. */
  1185. var onLoadShader = (gltfRuntime: IGLTFRuntime, sha: string) => {
  1186. return (data: any) => {
  1187. gltfRuntime.loadedShaders++;
  1188. Effect.ShadersStore[sha + (gltfRuntime.shaders[sha].type === EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = data;
  1189. if (gltfRuntime.loadedShaders === gltfRuntime.shaderscount) {
  1190. onShadersLoaded(gltfRuntime);
  1191. }
  1192. };
  1193. };
  1194. /**
  1195. * Error callback when loading a shader
  1196. */
  1197. var onLoadShaderError = (gltfRuntime: IGLTFRuntime, sha: string) => {
  1198. return () => {
  1199. Tools.Error("Error when loading shader program named " + sha + " located at " + gltfRuntime.shaders[sha].uri);
  1200. };
  1201. };
  1202. /**
  1203. * Load shaders
  1204. */
  1205. var load = (gltfRuntime: IGLTFRuntime) => {
  1206. // Begin with shaders
  1207. for (var sha in gltfRuntime.shaders) {
  1208. var shader: IGLTFShader = gltfRuntime.shaders[sha];
  1209. if (shader) {
  1210. if (isBase64(shader.uri)) {
  1211. var shaderString = atob(shader.uri.split(",")[1]);
  1212. onLoadShader(gltfRuntime, sha)(shaderString);
  1213. }
  1214. else {
  1215. Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onLoadShader(gltfRuntime, sha), null, null, false, onLoadShaderError(gltfRuntime, sha));
  1216. }
  1217. }
  1218. else {
  1219. Tools.Error("No shader file named " + shader.uri);
  1220. }
  1221. }
  1222. };
  1223. /**
  1224. * glTF File Loader Plugin
  1225. */
  1226. export class GLTFFileLoader implements ISceneLoaderPlugin {
  1227. /**
  1228. * Public members
  1229. */
  1230. public extensions = ".gltf";
  1231. /**
  1232. * Private members
  1233. */
  1234. // None
  1235. /**
  1236. * Import meshes
  1237. */
  1238. public importMesh(meshesNames: any, scene: Scene, data: any, rootUrl: string, meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]): boolean {
  1239. var parsedData = JSON.parse(data);
  1240. var gltfRuntime = this._createGlTFRuntime(parsedData, scene, rootUrl);
  1241. gltfRuntime.importOnlyMeshes = true;
  1242. if (meshesNames === "") {
  1243. gltfRuntime.importMeshesNames = [];
  1244. }
  1245. else if (typeof meshesNames === "string") {
  1246. gltfRuntime.importMeshesNames = [meshesNames];
  1247. }
  1248. else if (meshesNames && !(meshesNames instanceof Array)) {
  1249. gltfRuntime.importMeshesNames = [meshesNames];
  1250. }
  1251. else {
  1252. gltfRuntime.importMeshesNames = [];
  1253. Tools.Warn("Argument meshesNames must be of type string or string[]");
  1254. }
  1255. // Create nodes
  1256. this._createNodes(gltfRuntime);
  1257. // Fill arrays of meshes and skeletons
  1258. for (var nde in gltfRuntime.nodes) {
  1259. var node: IGLTFNode = gltfRuntime.nodes[nde];
  1260. if (node.babylonNode instanceof AbstractMesh) {
  1261. meshes.push(<AbstractMesh>node.babylonNode);
  1262. }
  1263. }
  1264. for (var skl in gltfRuntime.skins) {
  1265. var skin: IGLTFSkins = gltfRuntime.skins[skl];
  1266. if (skin.babylonSkeleton instanceof Skeleton) {
  1267. skeletons.push(skin.babylonSkeleton);
  1268. }
  1269. }
  1270. // Load shaders and buffers to apply
  1271. load(gltfRuntime);
  1272. return true;
  1273. }
  1274. /**
  1275. * Load scene
  1276. */
  1277. public load(scene: Scene, data: string, rootUrl: string): boolean {
  1278. var parsedData = JSON.parse(data);
  1279. var gltfRuntime = this._createGlTFRuntime(parsedData, scene, rootUrl);
  1280. // Create nodes
  1281. this._createNodes(gltfRuntime);
  1282. // Load shaders and buffers to apply
  1283. load(gltfRuntime);
  1284. // Finish
  1285. return true;
  1286. }
  1287. // Creates nodes before loading buffers and shaders
  1288. private _createNodes(gltfRuntime: IGLTFRuntime): void {
  1289. var currentScene: IGLTFScene = <IGLTFScene>gltfRuntime.currentScene;
  1290. for (var i = 0; i < currentScene.nodes.length; i++) {
  1291. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1292. }
  1293. }
  1294. // Creates the gltfRuntime
  1295. private _createGlTFRuntime(parsedData: any, scene: Scene, rootUrl: string): IGLTFRuntime {
  1296. var gltfRuntime: IGLTFRuntime = {
  1297. accessors: {},
  1298. buffers: {},
  1299. bufferViews: {},
  1300. meshes: {},
  1301. lights: {},
  1302. cameras: {},
  1303. nodes: {},
  1304. images: {},
  1305. textures: {},
  1306. shaders: {},
  1307. programs: {},
  1308. samplers: {},
  1309. techniques: {},
  1310. materials: {},
  1311. animations: {},
  1312. skins: {},
  1313. currentScene: {},
  1314. buffersCount: 0,
  1315. shaderscount: 0,
  1316. scene: scene,
  1317. dummyNodes: [],
  1318. loadedBuffers: 0,
  1319. loadedShaders: 0,
  1320. rootUrl: rootUrl,
  1321. importOnlyMeshes: false,
  1322. arrayBuffers: []
  1323. }
  1324. // Parse
  1325. if (parsedData.buffers) {
  1326. parseBuffers(parsedData.buffers, gltfRuntime);
  1327. }
  1328. if (parsedData.bufferViews) {
  1329. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1330. }
  1331. if (parsedData.accessors) {
  1332. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1333. }
  1334. if (parsedData.meshes) {
  1335. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1336. }
  1337. if (parsedData.lights) {
  1338. parseObject(parsedData.lights, "lights", gltfRuntime);
  1339. }
  1340. if (parsedData.cameras) {
  1341. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1342. }
  1343. if (parsedData.nodes) {
  1344. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1345. }
  1346. if (parsedData.images) {
  1347. parseObject(parsedData.images, "images", gltfRuntime);
  1348. }
  1349. if (parsedData.textures) {
  1350. parseObject(parsedData.textures, "textures", gltfRuntime);
  1351. }
  1352. if (parsedData.shaders) {
  1353. parseShaders(parsedData.shaders, gltfRuntime);
  1354. }
  1355. if (parsedData.programs) {
  1356. parseObject(parsedData.programs, "programs", gltfRuntime);
  1357. }
  1358. if (parsedData.samplers) {
  1359. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1360. }
  1361. if (parsedData.techniques) {
  1362. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1363. }
  1364. if (parsedData.materials) {
  1365. parseObject(parsedData.materials, "materials", gltfRuntime);
  1366. }
  1367. if (parsedData.animations) {
  1368. parseObject(parsedData.animations, "animations", gltfRuntime);
  1369. }
  1370. if (parsedData.skins) {
  1371. parseObject(parsedData.skins, "skins", gltfRuntime);
  1372. }
  1373. if (parsedData.scene && parsedData.scenes) {
  1374. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1375. }
  1376. return gltfRuntime;
  1377. }
  1378. };
  1379. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  1380. }