babylon.glTF2Serializer.js 181 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179
  1. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. ;
  5. /**
  6. * Class for generating glTF data from a Babylon scene.
  7. */
  8. var GLTF2Export = /** @class */ (function () {
  9. function GLTF2Export() {
  10. }
  11. /**
  12. * Exports the geometry of the scene to .gltf file format synchronously
  13. * @param scene Babylon scene with scene hierarchy information
  14. * @param filePrefix File prefix to use when generating the glTF file
  15. * @param options Exporter options
  16. * @returns Returns an object with a .gltf file and associates texture names
  17. * as keys and their data and paths as values
  18. */
  19. GLTF2Export.GLTF = function (scene, filePrefix, options) {
  20. var glTFPrefix = filePrefix.replace(/\.[^/.]+$/, "");
  21. var gltfGenerator = new BABYLON.GLTF2._Exporter(scene, options);
  22. return gltfGenerator._generateGLTF(glTFPrefix);
  23. };
  24. /**
  25. * Exports the geometry of the scene to .gltf file format asynchronously
  26. * @param scene Babylon scene with scene hierarchy information
  27. * @param filePrefix File prefix to use when generating the glTF file
  28. * @param options Exporter options
  29. * @returns Returns an object with a .gltf file and associates texture names
  30. * as keys and their data and paths as values
  31. */
  32. GLTF2Export.GLTFAsync = function (scene, filePrefix, options) {
  33. return Promise.resolve(scene.whenReadyAsync()).then(function () {
  34. return GLTF2Export.GLTF(scene, filePrefix, options);
  35. });
  36. };
  37. /**
  38. * Exports the geometry of the scene to .glb file format synchronously
  39. * @param scene Babylon scene with scene hierarchy information
  40. * @param filePrefix File prefix to use when generating glb file
  41. * @param options Exporter options
  42. * @returns Returns an object with a .glb filename as key and data as value
  43. */
  44. GLTF2Export.GLB = function (scene, filePrefix, options) {
  45. var glTFPrefix = filePrefix.replace(/\.[^/.]+$/, "");
  46. var gltfGenerator = new BABYLON.GLTF2._Exporter(scene, options);
  47. return gltfGenerator._generateGLB(glTFPrefix);
  48. };
  49. /**
  50. * Exports the geometry of the scene to .glb file format asychronously
  51. * @param scene Babylon scene with scene hierarchy information
  52. * @param filePrefix File prefix to use when generating glb file
  53. * @param options Exporter options
  54. * @returns Returns an object with a .glb filename as key and data as value
  55. */
  56. GLTF2Export.GLBAsync = function (scene, filePrefix, options) {
  57. return Promise.resolve(scene.whenReadyAsync()).then(function () {
  58. return GLTF2Export.GLB(scene, filePrefix, options);
  59. });
  60. };
  61. return GLTF2Export;
  62. }());
  63. BABYLON.GLTF2Export = GLTF2Export;
  64. })(BABYLON || (BABYLON = {}));
  65. //# sourceMappingURL=babylon.glTFSerializer.js.map
  66. /// <reference path="../../../../dist/preview release/gltf2Interface/babylon.glTF2Interface.d.ts"/>
  67. /**
  68. * Module for the Babylon glTF 2.0 exporter. Should ONLY be used internally
  69. * @hidden
  70. */
  71. var BABYLON;
  72. (function (BABYLON) {
  73. var GLTF2;
  74. (function (GLTF2) {
  75. /**
  76. * Utility interface for storing vertex attribute data
  77. * @hidden
  78. */
  79. /**
  80. * Converts Babylon Scene into glTF 2.0.
  81. * @hidden
  82. */
  83. var _Exporter = /** @class */ (function () {
  84. /**
  85. * Creates a glTF Exporter instance, which can accept optional exporter options
  86. * @param babylonScene Babylon scene object
  87. * @param options Options to modify the behavior of the exporter
  88. */
  89. function _Exporter(babylonScene, options) {
  90. this.asset = { generator: "BabylonJS", version: "2.0" };
  91. this.babylonScene = babylonScene;
  92. this.bufferViews = [];
  93. this.accessors = [];
  94. this.meshes = [];
  95. this.scenes = [];
  96. this.nodes = [];
  97. this.images = [];
  98. this.materials = [];
  99. this.textures = [];
  100. this.samplers = [];
  101. this.animations = [];
  102. this.imageData = {};
  103. this.convertToRightHandedSystem = this.babylonScene.useRightHandedSystem ? false : true;
  104. var _options = options || {};
  105. this.shouldExportTransformNode = _options.shouldExportTransformNode ? _options.shouldExportTransformNode : function (babylonTransformNode) { return true; };
  106. this.animationSampleRate = _options.animationSampleRate ? _options.animationSampleRate : 1 / 60;
  107. }
  108. _Exporter.prototype.reorderIndicesBasedOnPrimitiveMode = function (submesh, primitiveMode, babylonIndices, byteOffset, binaryWriter) {
  109. switch (primitiveMode) {
  110. case BABYLON.Material.TriangleFillMode: {
  111. if (!byteOffset) {
  112. byteOffset = 0;
  113. }
  114. for (var i = submesh.indexStart, length_1 = submesh.indexStart + submesh.indexCount; i < length_1; i = i + 3) {
  115. var index = byteOffset + i * 4;
  116. // swap the second and third indices
  117. var secondIndex = binaryWriter.getUInt32(index + 4);
  118. var thirdIndex = binaryWriter.getUInt32(index + 8);
  119. binaryWriter.setUInt32(thirdIndex, index + 4);
  120. binaryWriter.setUInt32(secondIndex, index + 8);
  121. }
  122. break;
  123. }
  124. case BABYLON.Material.TriangleFanDrawMode: {
  125. for (var i = submesh.indexStart + submesh.indexCount - 1, start = submesh.indexStart; i >= start; --i) {
  126. binaryWriter.setUInt32(babylonIndices[i], byteOffset);
  127. byteOffset += 4;
  128. }
  129. break;
  130. }
  131. case BABYLON.Material.TriangleStripDrawMode: {
  132. if (submesh.indexCount >= 3) {
  133. binaryWriter.setUInt32(babylonIndices[submesh.indexStart + 2], byteOffset + 4);
  134. binaryWriter.setUInt32(babylonIndices[submesh.indexStart + 1], byteOffset + 8);
  135. }
  136. break;
  137. }
  138. }
  139. };
  140. /**
  141. * Reorders the vertex attribute data based on the primitive mode. This is necessary when indices are not available and the winding order is
  142. * clock-wise during export to glTF
  143. * @param submesh BabylonJS submesh
  144. * @param primitiveMode Primitive mode of the mesh
  145. * @param sideOrientation the winding order of the submesh
  146. * @param vertexBufferKind The type of vertex attribute
  147. * @param meshAttributeArray The vertex attribute data
  148. * @param byteOffset The offset to the binary data
  149. * @param binaryWriter The binary data for the glTF file
  150. */
  151. _Exporter.prototype.reorderVertexAttributeDataBasedOnPrimitiveMode = function (submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter) {
  152. if (this.convertToRightHandedSystem && sideOrientation === BABYLON.Material.ClockWiseSideOrientation) {
  153. switch (primitiveMode) {
  154. case BABYLON.Material.TriangleFillMode: {
  155. this.reorderTriangleFillMode(submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter);
  156. break;
  157. }
  158. case BABYLON.Material.TriangleStripDrawMode: {
  159. this.reorderTriangleStripDrawMode(submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter);
  160. break;
  161. }
  162. case BABYLON.Material.TriangleFanDrawMode: {
  163. this.reorderTriangleFanMode(submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter);
  164. break;
  165. }
  166. }
  167. }
  168. };
  169. /**
  170. * Reorders the vertex attributes in the correct triangle mode order . This is necessary when indices are not available and the winding order is
  171. * clock-wise during export to glTF
  172. * @param submesh BabylonJS submesh
  173. * @param primitiveMode Primitive mode of the mesh
  174. * @param sideOrientation the winding order of the submesh
  175. * @param vertexBufferKind The type of vertex attribute
  176. * @param meshAttributeArray The vertex attribute data
  177. * @param byteOffset The offset to the binary data
  178. * @param binaryWriter The binary data for the glTF file
  179. */
  180. _Exporter.prototype.reorderTriangleFillMode = function (submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter) {
  181. var vertexBuffer = this.getVertexBufferFromMesh(vertexBufferKind, submesh.getMesh());
  182. if (vertexBuffer) {
  183. var stride = vertexBuffer.byteStride / BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  184. if (submesh.verticesCount % 3 !== 0) {
  185. BABYLON.Tools.Error('The submesh vertices for the triangle fill mode is not divisible by 3!');
  186. }
  187. else {
  188. var vertexData = [];
  189. var index = 0;
  190. switch (vertexBufferKind) {
  191. case BABYLON.VertexBuffer.PositionKind:
  192. case BABYLON.VertexBuffer.NormalKind: {
  193. for (var x = submesh.verticesStart; x < submesh.verticesStart + submesh.verticesCount; x = x + 3) {
  194. index = x * stride;
  195. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index));
  196. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index + 2 * stride));
  197. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index + stride));
  198. }
  199. break;
  200. }
  201. case BABYLON.VertexBuffer.TangentKind: {
  202. for (var x = submesh.verticesStart; x < submesh.verticesStart + submesh.verticesCount; x = x + 3) {
  203. index = x * stride;
  204. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index));
  205. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index + 2 * stride));
  206. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index + stride));
  207. }
  208. break;
  209. }
  210. case BABYLON.VertexBuffer.ColorKind: {
  211. var size = vertexBuffer.getSize();
  212. for (var x = submesh.verticesStart; x < submesh.verticesStart + submesh.verticesCount; x = x + size) {
  213. index = x * stride;
  214. if (size === 4) {
  215. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index));
  216. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index + 2 * stride));
  217. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index + stride));
  218. }
  219. else {
  220. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index));
  221. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index + 2 * stride));
  222. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index + stride));
  223. }
  224. }
  225. break;
  226. }
  227. case BABYLON.VertexBuffer.UVKind:
  228. case BABYLON.VertexBuffer.UV2Kind: {
  229. for (var x = submesh.verticesStart; x < submesh.verticesStart + submesh.verticesCount; x = x + 3) {
  230. index = x * stride;
  231. vertexData.push(BABYLON.Vector2.FromArray(meshAttributeArray, index));
  232. vertexData.push(BABYLON.Vector2.FromArray(meshAttributeArray, index + 2 * stride));
  233. vertexData.push(BABYLON.Vector2.FromArray(meshAttributeArray, index + stride));
  234. }
  235. break;
  236. }
  237. default: {
  238. BABYLON.Tools.Error("Unsupported Vertex Buffer type: " + vertexBufferKind);
  239. }
  240. }
  241. this.writeVertexAttributeData(vertexData, byteOffset, vertexBufferKind, meshAttributeArray, binaryWriter);
  242. }
  243. }
  244. else {
  245. BABYLON.Tools.Warn("reorderTriangleFillMode: Vertex Buffer Kind " + vertexBufferKind + " not present!");
  246. }
  247. };
  248. /**
  249. * Reorders the vertex attributes in the correct triangle strip order. This is necessary when indices are not available and the winding order is
  250. * clock-wise during export to glTF
  251. * @param submesh BabylonJS submesh
  252. * @param primitiveMode Primitive mode of the mesh
  253. * @param sideOrientation the winding order of the submesh
  254. * @param vertexBufferKind The type of vertex attribute
  255. * @param meshAttributeArray The vertex attribute data
  256. * @param byteOffset The offset to the binary data
  257. * @param binaryWriter The binary data for the glTF file
  258. */
  259. _Exporter.prototype.reorderTriangleStripDrawMode = function (submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter) {
  260. var vertexBuffer = this.getVertexBufferFromMesh(vertexBufferKind, submesh.getMesh());
  261. if (vertexBuffer) {
  262. var stride = vertexBuffer.byteStride / BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  263. var vertexData = [];
  264. var index = 0;
  265. switch (vertexBufferKind) {
  266. case BABYLON.VertexBuffer.PositionKind:
  267. case BABYLON.VertexBuffer.NormalKind: {
  268. index = submesh.verticesStart;
  269. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index + 2 * stride));
  270. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index + stride));
  271. break;
  272. }
  273. case BABYLON.VertexBuffer.TangentKind: {
  274. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  275. index = x * stride;
  276. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index));
  277. }
  278. break;
  279. }
  280. case BABYLON.VertexBuffer.ColorKind: {
  281. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  282. index = x * stride;
  283. vertexBuffer.getSize() === 4 ? vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index)) : vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index));
  284. }
  285. break;
  286. }
  287. case BABYLON.VertexBuffer.UVKind:
  288. case BABYLON.VertexBuffer.UV2Kind: {
  289. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  290. index = x * stride;
  291. vertexData.push(BABYLON.Vector2.FromArray(meshAttributeArray, index));
  292. }
  293. break;
  294. }
  295. default: {
  296. BABYLON.Tools.Error("Unsupported Vertex Buffer type: " + vertexBufferKind);
  297. }
  298. }
  299. this.writeVertexAttributeData(vertexData, byteOffset + 12, vertexBufferKind, meshAttributeArray, binaryWriter);
  300. }
  301. else {
  302. BABYLON.Tools.Warn("reorderTriangleStripDrawMode: Vertex buffer kind " + vertexBufferKind + " not present!");
  303. }
  304. };
  305. /**
  306. * Reorders the vertex attributes in the correct triangle fan order. This is necessary when indices are not available and the winding order is
  307. * clock-wise during export to glTF
  308. * @param submesh BabylonJS submesh
  309. * @param primitiveMode Primitive mode of the mesh
  310. * @param sideOrientation the winding order of the submesh
  311. * @param vertexBufferKind The type of vertex attribute
  312. * @param meshAttributeArray The vertex attribute data
  313. * @param byteOffset The offset to the binary data
  314. * @param binaryWriter The binary data for the glTF file
  315. */
  316. _Exporter.prototype.reorderTriangleFanMode = function (submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter) {
  317. var vertexBuffer = this.getVertexBufferFromMesh(vertexBufferKind, submesh.getMesh());
  318. if (vertexBuffer) {
  319. var stride = vertexBuffer.byteStride / BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  320. var vertexData = [];
  321. var index = 0;
  322. switch (vertexBufferKind) {
  323. case BABYLON.VertexBuffer.PositionKind:
  324. case BABYLON.VertexBuffer.NormalKind: {
  325. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  326. index = x * stride;
  327. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index));
  328. }
  329. break;
  330. }
  331. case BABYLON.VertexBuffer.TangentKind: {
  332. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  333. index = x * stride;
  334. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index));
  335. }
  336. break;
  337. }
  338. case BABYLON.VertexBuffer.ColorKind: {
  339. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  340. index = x * stride;
  341. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index));
  342. vertexBuffer.getSize() === 4 ? vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index)) : vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index));
  343. }
  344. break;
  345. }
  346. case BABYLON.VertexBuffer.UVKind:
  347. case BABYLON.VertexBuffer.UV2Kind: {
  348. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  349. index = x * stride;
  350. vertexData.push(BABYLON.Vector2.FromArray(meshAttributeArray, index));
  351. }
  352. break;
  353. }
  354. default: {
  355. BABYLON.Tools.Error("Unsupported Vertex Buffer type: " + vertexBufferKind);
  356. }
  357. }
  358. this.writeVertexAttributeData(vertexData, byteOffset, vertexBufferKind, meshAttributeArray, binaryWriter);
  359. }
  360. else {
  361. BABYLON.Tools.Warn("reorderTriangleFanMode: Vertex buffer kind " + vertexBufferKind + " not present!");
  362. }
  363. };
  364. /**
  365. * Writes the vertex attribute data to binary
  366. * @param vertices The vertices to write to the binary writer
  367. * @param byteOffset The offset into the binary writer to overwrite binary data
  368. * @param vertexAttributeKind The vertex attribute type
  369. * @param meshAttributeArray The vertex attribute data
  370. * @param binaryWriter The writer containing the binary data
  371. */
  372. _Exporter.prototype.writeVertexAttributeData = function (vertices, byteOffset, vertexAttributeKind, meshAttributeArray, binaryWriter) {
  373. for (var _i = 0, vertices_1 = vertices; _i < vertices_1.length; _i++) {
  374. var vertex = vertices_1[_i];
  375. if (this.convertToRightHandedSystem && !(vertexAttributeKind === BABYLON.VertexBuffer.ColorKind) && !(vertex instanceof BABYLON.Vector2)) {
  376. if (vertex instanceof BABYLON.Vector3) {
  377. (vertexAttributeKind === BABYLON.VertexBuffer.PositionKind) ? GLTF2._GLTFUtilities.GetRightHandedPositionVector3FromRef(vertex) : GLTF2._GLTFUtilities.GetRightHandedNormalVector3FromRef(vertex);
  378. }
  379. else {
  380. GLTF2._GLTFUtilities.GetRightHandedVector4FromRef(vertex);
  381. }
  382. }
  383. for (var _a = 0, _b = vertex.asArray(); _a < _b.length; _a++) {
  384. var component = _b[_a];
  385. binaryWriter.setFloat32(component, byteOffset);
  386. byteOffset += 4;
  387. }
  388. }
  389. };
  390. /**
  391. * Writes mesh attribute data to a data buffer
  392. * Returns the bytelength of the data
  393. * @param vertexBufferKind Indicates what kind of vertex data is being passed in
  394. * @param meshAttributeArray Array containing the attribute data
  395. * @param binaryWriter The buffer to write the binary data to
  396. * @param indices Used to specify the order of the vertex data
  397. */
  398. _Exporter.prototype.writeAttributeData = function (vertexBufferKind, meshAttributeArray, byteStride, binaryWriter) {
  399. var stride = byteStride / 4;
  400. var vertexAttributes = [];
  401. var index;
  402. switch (vertexBufferKind) {
  403. case BABYLON.VertexBuffer.PositionKind: {
  404. for (var k = 0, length_2 = meshAttributeArray.length / stride; k < length_2; ++k) {
  405. index = k * stride;
  406. var vertexData = BABYLON.Vector3.FromArray(meshAttributeArray, index);
  407. if (this.convertToRightHandedSystem) {
  408. GLTF2._GLTFUtilities.GetRightHandedPositionVector3FromRef(vertexData);
  409. }
  410. vertexAttributes.push(vertexData.asArray());
  411. }
  412. break;
  413. }
  414. case BABYLON.VertexBuffer.NormalKind: {
  415. for (var k = 0, length_3 = meshAttributeArray.length / stride; k < length_3; ++k) {
  416. index = k * stride;
  417. var vertexData = BABYLON.Vector3.FromArray(meshAttributeArray, index);
  418. if (this.convertToRightHandedSystem) {
  419. GLTF2._GLTFUtilities.GetRightHandedNormalVector3FromRef(vertexData);
  420. }
  421. vertexAttributes.push(vertexData.asArray());
  422. }
  423. break;
  424. }
  425. case BABYLON.VertexBuffer.TangentKind: {
  426. for (var k = 0, length_4 = meshAttributeArray.length / stride; k < length_4; ++k) {
  427. index = k * stride;
  428. var vertexData = BABYLON.Vector4.FromArray(meshAttributeArray, index);
  429. if (this.convertToRightHandedSystem) {
  430. GLTF2._GLTFUtilities.GetRightHandedVector4FromRef(vertexData);
  431. }
  432. vertexAttributes.push(vertexData.asArray());
  433. }
  434. break;
  435. }
  436. case BABYLON.VertexBuffer.ColorKind: {
  437. for (var k = 0, length_5 = meshAttributeArray.length / stride; k < length_5; ++k) {
  438. index = k * stride;
  439. var vertexData = stride === 3 ? BABYLON.Vector3.FromArray(meshAttributeArray, index) : BABYLON.Vector4.FromArray(meshAttributeArray, index);
  440. vertexAttributes.push(vertexData.asArray());
  441. }
  442. break;
  443. }
  444. case BABYLON.VertexBuffer.UVKind:
  445. case BABYLON.VertexBuffer.UV2Kind: {
  446. for (var k = 0, length_6 = meshAttributeArray.length / stride; k < length_6; ++k) {
  447. index = k * stride;
  448. vertexAttributes.push(this.convertToRightHandedSystem ? [meshAttributeArray[index], meshAttributeArray[index + 1]] : [meshAttributeArray[index], meshAttributeArray[index + 1]]);
  449. }
  450. break;
  451. }
  452. default: {
  453. BABYLON.Tools.Warn("Unsupported Vertex Buffer Type: " + vertexBufferKind);
  454. vertexAttributes = [];
  455. }
  456. }
  457. for (var _i = 0, vertexAttributes_1 = vertexAttributes; _i < vertexAttributes_1.length; _i++) {
  458. var vertexAttribute = vertexAttributes_1[_i];
  459. for (var _a = 0, vertexAttribute_1 = vertexAttribute; _a < vertexAttribute_1.length; _a++) {
  460. var component = vertexAttribute_1[_a];
  461. binaryWriter.setFloat32(component);
  462. }
  463. }
  464. };
  465. /**
  466. * Generates glTF json data
  467. * @param shouldUseGlb Indicates whether the json should be written for a glb file
  468. * @param glTFPrefix Text to use when prefixing a glTF file
  469. * @param prettyPrint Indicates whether the json file should be pretty printed (true) or not (false)
  470. * @returns json data as string
  471. */
  472. _Exporter.prototype.generateJSON = function (shouldUseGlb, glTFPrefix, prettyPrint) {
  473. var _this = this;
  474. var buffer = { byteLength: this.totalByteLength };
  475. var imageName;
  476. var imageData;
  477. var bufferView;
  478. var byteOffset = this.totalByteLength;
  479. var glTF = {
  480. asset: this.asset
  481. };
  482. if (buffer.byteLength) {
  483. glTF.buffers = [buffer];
  484. }
  485. if (this.nodes && this.nodes.length) {
  486. glTF.nodes = this.nodes;
  487. }
  488. if (this.meshes && this.meshes.length) {
  489. glTF.meshes = this.meshes;
  490. }
  491. if (this.scenes && this.scenes.length) {
  492. glTF.scenes = this.scenes;
  493. glTF.scene = 0;
  494. }
  495. if (this.bufferViews && this.bufferViews.length) {
  496. glTF.bufferViews = this.bufferViews;
  497. }
  498. if (this.accessors && this.accessors.length) {
  499. glTF.accessors = this.accessors;
  500. }
  501. if (this.animations && this.animations.length) {
  502. glTF.animations = this.animations;
  503. }
  504. if (this.materials && this.materials.length) {
  505. glTF.materials = this.materials;
  506. }
  507. if (this.textures && this.textures.length) {
  508. glTF.textures = this.textures;
  509. }
  510. if (this.samplers && this.samplers.length) {
  511. glTF.samplers = this.samplers;
  512. }
  513. if (this.images && this.images.length) {
  514. if (!shouldUseGlb) {
  515. glTF.images = this.images;
  516. }
  517. else {
  518. glTF.images = [];
  519. this.images.forEach(function (image) {
  520. if (image.uri) {
  521. imageData = _this.imageData[image.uri];
  522. imageName = image.uri.split('.')[0] + " image";
  523. bufferView = GLTF2._GLTFUtilities.CreateBufferView(0, byteOffset, imageData.data.length, undefined, imageName);
  524. byteOffset += imageData.data.buffer.byteLength;
  525. _this.bufferViews.push(bufferView);
  526. image.bufferView = _this.bufferViews.length - 1;
  527. image.name = imageName;
  528. image.mimeType = imageData.mimeType;
  529. image.uri = undefined;
  530. if (!glTF.images) {
  531. glTF.images = [];
  532. }
  533. glTF.images.push(image);
  534. }
  535. });
  536. // Replace uri with bufferview and mime type for glb
  537. buffer.byteLength = byteOffset;
  538. }
  539. }
  540. if (!shouldUseGlb) {
  541. buffer.uri = glTFPrefix + ".bin";
  542. }
  543. var jsonText = prettyPrint ? JSON.stringify(glTF, null, 2) : JSON.stringify(glTF);
  544. return jsonText;
  545. };
  546. /**
  547. * Generates data for .gltf and .bin files based on the glTF prefix string
  548. * @param glTFPrefix Text to use when prefixing a glTF file
  549. * @returns GLTFData with glTF file data
  550. */
  551. _Exporter.prototype._generateGLTF = function (glTFPrefix) {
  552. var binaryBuffer = this.generateBinary();
  553. var jsonText = this.generateJSON(false, glTFPrefix, true);
  554. var bin = new Blob([binaryBuffer], { type: 'application/octet-stream' });
  555. var glTFFileName = glTFPrefix + '.gltf';
  556. var glTFBinFile = glTFPrefix + '.bin';
  557. var container = new BABYLON.GLTFData();
  558. container.glTFFiles[glTFFileName] = jsonText;
  559. container.glTFFiles[glTFBinFile] = bin;
  560. if (this.imageData) {
  561. for (var image in this.imageData) {
  562. container.glTFFiles[image] = new Blob([this.imageData[image].data], { type: this.imageData[image].mimeType });
  563. }
  564. }
  565. return container;
  566. };
  567. /**
  568. * Creates a binary buffer for glTF
  569. * @returns array buffer for binary data
  570. */
  571. _Exporter.prototype.generateBinary = function () {
  572. var binaryWriter = new _BinaryWriter(4);
  573. this.createScene(this.babylonScene, binaryWriter);
  574. return binaryWriter.getArrayBuffer();
  575. };
  576. /**
  577. * Pads the number to a multiple of 4
  578. * @param num number to pad
  579. * @returns padded number
  580. */
  581. _Exporter.prototype._getPadding = function (num) {
  582. var remainder = num % 4;
  583. var padding = remainder === 0 ? remainder : 4 - remainder;
  584. return padding;
  585. };
  586. /**
  587. * Generates a glb file from the json and binary data
  588. * Returns an object with the glb file name as the key and data as the value
  589. * @param glTFPrefix
  590. * @returns object with glb filename as key and data as value
  591. */
  592. _Exporter.prototype._generateGLB = function (glTFPrefix) {
  593. var binaryBuffer = this.generateBinary();
  594. var jsonText = this.generateJSON(true);
  595. var glbFileName = glTFPrefix + '.glb';
  596. var headerLength = 12;
  597. var chunkLengthPrefix = 8;
  598. var jsonLength = jsonText.length;
  599. var imageByteLength = 0;
  600. for (var key in this.imageData) {
  601. imageByteLength += this.imageData[key].data.byteLength;
  602. }
  603. var jsonPadding = this._getPadding(jsonLength);
  604. var binPadding = this._getPadding(binaryBuffer.byteLength);
  605. var imagePadding = this._getPadding(imageByteLength);
  606. var byteLength = headerLength + (2 * chunkLengthPrefix) + jsonLength + jsonPadding + binaryBuffer.byteLength + binPadding + imageByteLength + imagePadding;
  607. //header
  608. var headerBuffer = new ArrayBuffer(headerLength);
  609. var headerBufferView = new DataView(headerBuffer);
  610. headerBufferView.setUint32(0, 0x46546C67, true); //glTF
  611. headerBufferView.setUint32(4, 2, true); // version
  612. headerBufferView.setUint32(8, byteLength, true); // total bytes in file
  613. //json chunk
  614. var jsonChunkBuffer = new ArrayBuffer(chunkLengthPrefix + jsonLength + jsonPadding);
  615. var jsonChunkBufferView = new DataView(jsonChunkBuffer);
  616. jsonChunkBufferView.setUint32(0, jsonLength + jsonPadding, true);
  617. jsonChunkBufferView.setUint32(4, 0x4E4F534A, true);
  618. //json chunk bytes
  619. var jsonData = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix);
  620. for (var i = 0; i < jsonLength; ++i) {
  621. jsonData[i] = jsonText.charCodeAt(i);
  622. }
  623. //json padding
  624. var jsonPaddingView = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix + jsonLength);
  625. for (var i = 0; i < jsonPadding; ++i) {
  626. jsonPaddingView[i] = 0x20;
  627. }
  628. //binary chunk
  629. var binaryChunkBuffer = new ArrayBuffer(chunkLengthPrefix);
  630. var binaryChunkBufferView = new DataView(binaryChunkBuffer);
  631. binaryChunkBufferView.setUint32(0, binaryBuffer.byteLength + imageByteLength + imagePadding, true);
  632. binaryChunkBufferView.setUint32(4, 0x004E4942, true);
  633. // binary padding
  634. var binPaddingBuffer = new ArrayBuffer(binPadding);
  635. var binPaddingView = new Uint8Array(binPaddingBuffer);
  636. for (var i = 0; i < binPadding; ++i) {
  637. binPaddingView[i] = 0;
  638. }
  639. var imagePaddingBuffer = new ArrayBuffer(imagePadding);
  640. var imagePaddingView = new Uint8Array(imagePaddingBuffer);
  641. for (var i = 0; i < imagePadding; ++i) {
  642. imagePaddingView[i] = 0;
  643. }
  644. var glbData = [headerBuffer, jsonChunkBuffer, binaryChunkBuffer, binaryBuffer];
  645. // binary data
  646. for (var key in this.imageData) {
  647. glbData.push(this.imageData[key].data.buffer);
  648. }
  649. glbData.push(binPaddingBuffer);
  650. glbData.push(imagePaddingBuffer);
  651. var glbFile = new Blob(glbData, { type: 'application/octet-stream' });
  652. var container = new BABYLON.GLTFData();
  653. container.glTFFiles[glbFileName] = glbFile;
  654. return container;
  655. };
  656. /**
  657. * Sets the TRS for each node
  658. * @param node glTF Node for storing the transformation data
  659. * @param babylonTransformNode Babylon mesh used as the source for the transformation data
  660. */
  661. _Exporter.prototype.setNodeTransformation = function (node, babylonTransformNode) {
  662. if (!babylonTransformNode.position.equalsToFloats(0, 0, 0)) {
  663. node.translation = this.convertToRightHandedSystem ? GLTF2._GLTFUtilities.GetRightHandedPositionVector3(babylonTransformNode.position).asArray() : babylonTransformNode.position.asArray();
  664. }
  665. if (!babylonTransformNode.scaling.equalsToFloats(1, 1, 1)) {
  666. node.scale = babylonTransformNode.scaling.asArray();
  667. }
  668. var rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(babylonTransformNode.rotation.y, babylonTransformNode.rotation.x, babylonTransformNode.rotation.z);
  669. if (babylonTransformNode.rotationQuaternion) {
  670. rotationQuaternion.multiplyInPlace(babylonTransformNode.rotationQuaternion);
  671. }
  672. if (!(rotationQuaternion.x === 0 && rotationQuaternion.y === 0 && rotationQuaternion.z === 0 && rotationQuaternion.w === 1)) {
  673. if (this.convertToRightHandedSystem) {
  674. GLTF2._GLTFUtilities.GetRightHandedQuaternionFromRef(rotationQuaternion);
  675. }
  676. node.rotation = rotationQuaternion.normalize().asArray();
  677. }
  678. };
  679. _Exporter.prototype.getVertexBufferFromMesh = function (attributeKind, bufferMesh) {
  680. if (bufferMesh.isVerticesDataPresent(attributeKind)) {
  681. var vertexBuffer = bufferMesh.getVertexBuffer(attributeKind);
  682. if (vertexBuffer) {
  683. return vertexBuffer;
  684. }
  685. }
  686. return null;
  687. };
  688. /**
  689. * Creates a bufferview based on the vertices type for the Babylon mesh
  690. * @param kind Indicates the type of vertices data
  691. * @param babylonTransformNode The Babylon mesh to get the vertices data from
  692. * @param binaryWriter The buffer to write the bufferview data to
  693. */
  694. _Exporter.prototype.createBufferViewKind = function (kind, babylonTransformNode, binaryWriter, byteStride) {
  695. var bufferMesh = babylonTransformNode instanceof BABYLON.Mesh ?
  696. babylonTransformNode : babylonTransformNode instanceof BABYLON.InstancedMesh ?
  697. babylonTransformNode.sourceMesh : null;
  698. if (bufferMesh) {
  699. var vertexData = bufferMesh.getVerticesData(kind);
  700. if (vertexData) {
  701. var byteLength = vertexData.length * 4;
  702. var bufferView = GLTF2._GLTFUtilities.CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, byteStride, kind + " - " + bufferMesh.name);
  703. this.bufferViews.push(bufferView);
  704. this.writeAttributeData(kind, vertexData, byteStride, binaryWriter);
  705. }
  706. }
  707. };
  708. /**
  709. * The primitive mode of the Babylon mesh
  710. * @param babylonMesh The BabylonJS mesh
  711. */
  712. _Exporter.prototype.getMeshPrimitiveMode = function (babylonMesh) {
  713. return babylonMesh.material ? babylonMesh.material.fillMode : BABYLON.Material.TriangleFanDrawMode;
  714. };
  715. /**
  716. * Sets the primitive mode of the glTF mesh primitive
  717. * @param meshPrimitive glTF mesh primitive
  718. * @param primitiveMode The primitive mode
  719. */
  720. _Exporter.prototype.setPrimitiveMode = function (meshPrimitive, primitiveMode) {
  721. switch (primitiveMode) {
  722. case BABYLON.Material.TriangleFillMode: {
  723. // glTF defaults to using Triangle Mode
  724. break;
  725. }
  726. case BABYLON.Material.TriangleStripDrawMode: {
  727. meshPrimitive.mode = 5 /* TRIANGLE_STRIP */;
  728. break;
  729. }
  730. case BABYLON.Material.TriangleFanDrawMode: {
  731. meshPrimitive.mode = 6 /* TRIANGLE_FAN */;
  732. break;
  733. }
  734. case BABYLON.Material.PointListDrawMode: {
  735. meshPrimitive.mode = 0 /* POINTS */;
  736. }
  737. case BABYLON.Material.PointFillMode: {
  738. meshPrimitive.mode = 0 /* POINTS */;
  739. break;
  740. }
  741. case BABYLON.Material.LineLoopDrawMode: {
  742. meshPrimitive.mode = 2 /* LINE_LOOP */;
  743. break;
  744. }
  745. case BABYLON.Material.LineListDrawMode: {
  746. meshPrimitive.mode = 1 /* LINES */;
  747. break;
  748. }
  749. case BABYLON.Material.LineStripDrawMode: {
  750. meshPrimitive.mode = 3 /* LINE_STRIP */;
  751. break;
  752. }
  753. }
  754. };
  755. /**
  756. * Sets the vertex attribute accessor based of the glTF mesh primitive
  757. * @param meshPrimitive glTF mesh primitive
  758. * @param attributeKind vertex attribute
  759. * @returns boolean specifying if uv coordinates are present
  760. */
  761. _Exporter.prototype.setAttributeKind = function (meshPrimitive, attributeKind) {
  762. switch (attributeKind) {
  763. case BABYLON.VertexBuffer.PositionKind: {
  764. meshPrimitive.attributes.POSITION = this.accessors.length - 1;
  765. break;
  766. }
  767. case BABYLON.VertexBuffer.NormalKind: {
  768. meshPrimitive.attributes.NORMAL = this.accessors.length - 1;
  769. break;
  770. }
  771. case BABYLON.VertexBuffer.ColorKind: {
  772. meshPrimitive.attributes.COLOR_0 = this.accessors.length - 1;
  773. break;
  774. }
  775. case BABYLON.VertexBuffer.TangentKind: {
  776. meshPrimitive.attributes.TANGENT = this.accessors.length - 1;
  777. break;
  778. }
  779. case BABYLON.VertexBuffer.UVKind: {
  780. meshPrimitive.attributes.TEXCOORD_0 = this.accessors.length - 1;
  781. break;
  782. }
  783. case BABYLON.VertexBuffer.UV2Kind: {
  784. meshPrimitive.attributes.TEXCOORD_1 = this.accessors.length - 1;
  785. break;
  786. }
  787. default: {
  788. BABYLON.Tools.Warn("Unsupported Vertex Buffer Type: " + attributeKind);
  789. }
  790. }
  791. };
  792. /**
  793. * Sets data for the primitive attributes of each submesh
  794. * @param mesh glTF Mesh object to store the primitive attribute information
  795. * @param babylonTransformNode Babylon mesh to get the primitive attribute data from
  796. * @param binaryWriter Buffer to write the attribute data to
  797. */
  798. _Exporter.prototype.setPrimitiveAttributes = function (mesh, babylonTransformNode, binaryWriter) {
  799. var bufferMesh = null;
  800. var bufferView;
  801. var uvCoordsPresent;
  802. var minMax;
  803. if (babylonTransformNode instanceof BABYLON.Mesh) {
  804. bufferMesh = babylonTransformNode;
  805. }
  806. else if (babylonTransformNode instanceof BABYLON.InstancedMesh) {
  807. bufferMesh = babylonTransformNode.sourceMesh;
  808. }
  809. var attributeData = [
  810. { kind: BABYLON.VertexBuffer.PositionKind, accessorType: "VEC3" /* VEC3 */, byteStride: 12 },
  811. { kind: BABYLON.VertexBuffer.NormalKind, accessorType: "VEC3" /* VEC3 */, byteStride: 12 },
  812. { kind: BABYLON.VertexBuffer.ColorKind, accessorType: "VEC4" /* VEC4 */, byteStride: 16 },
  813. { kind: BABYLON.VertexBuffer.TangentKind, accessorType: "VEC4" /* VEC4 */, byteStride: 16 },
  814. { kind: BABYLON.VertexBuffer.UVKind, accessorType: "VEC2" /* VEC2 */, byteStride: 8 },
  815. { kind: BABYLON.VertexBuffer.UV2Kind, accessorType: "VEC2" /* VEC2 */, byteStride: 8 },
  816. ];
  817. if (bufferMesh) {
  818. var indexBufferViewIndex = null;
  819. var primitiveMode = this.getMeshPrimitiveMode(bufferMesh);
  820. var vertexAttributeBufferViews = {};
  821. // For each BabylonMesh, create bufferviews for each 'kind'
  822. for (var _i = 0, attributeData_1 = attributeData; _i < attributeData_1.length; _i++) {
  823. var attribute = attributeData_1[_i];
  824. var attributeKind = attribute.kind;
  825. if (bufferMesh.isVerticesDataPresent(attributeKind)) {
  826. var vertexBuffer = this.getVertexBufferFromMesh(attributeKind, bufferMesh);
  827. attribute.byteStride = vertexBuffer ? vertexBuffer.getSize() * 4 : BABYLON.VertexBuffer.DeduceStride(attributeKind) * 4;
  828. if (attribute.byteStride === 12) {
  829. attribute.accessorType = "VEC3" /* VEC3 */;
  830. }
  831. this.createBufferViewKind(attributeKind, babylonTransformNode, binaryWriter, attribute.byteStride);
  832. attribute.bufferViewIndex = this.bufferViews.length - 1;
  833. vertexAttributeBufferViews[attributeKind] = attribute.bufferViewIndex;
  834. }
  835. }
  836. if (bufferMesh.getTotalIndices()) {
  837. var indices = bufferMesh.getIndices();
  838. if (indices) {
  839. var byteLength = indices.length * 4;
  840. bufferView = GLTF2._GLTFUtilities.CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, undefined, "Indices - " + bufferMesh.name);
  841. this.bufferViews.push(bufferView);
  842. indexBufferViewIndex = this.bufferViews.length - 1;
  843. for (var k = 0, length_7 = indices.length; k < length_7; ++k) {
  844. binaryWriter.setUInt32(indices[k]);
  845. }
  846. }
  847. }
  848. if (bufferMesh.subMeshes) {
  849. uvCoordsPresent = false;
  850. // go through all mesh primitives (submeshes)
  851. for (var _a = 0, _b = bufferMesh.subMeshes; _a < _b.length; _a++) {
  852. var submesh = _b[_a];
  853. var meshPrimitive = { attributes: {} };
  854. for (var _c = 0, attributeData_2 = attributeData; _c < attributeData_2.length; _c++) {
  855. var attribute = attributeData_2[_c];
  856. var attributeKind = attribute.kind;
  857. var vertexData = bufferMesh.getVerticesData(attributeKind);
  858. if (vertexData) {
  859. var vertexBuffer = this.getVertexBufferFromMesh(attributeKind, bufferMesh);
  860. if (vertexBuffer) {
  861. var stride = vertexBuffer.getSize();
  862. var bufferViewIndex = attribute.bufferViewIndex;
  863. if (bufferViewIndex != undefined) { // check to see if bufferviewindex has a numeric value assigned.
  864. minMax = { min: null, max: null };
  865. if (attributeKind == BABYLON.VertexBuffer.PositionKind) {
  866. minMax = GLTF2._GLTFUtilities.CalculateMinMaxPositions(vertexData, 0, vertexData.length / stride, this.convertToRightHandedSystem);
  867. }
  868. var accessor = GLTF2._GLTFUtilities.CreateAccessor(bufferViewIndex, attributeKind + " - " + babylonTransformNode.name, attribute.accessorType, 5126 /* FLOAT */, vertexData.length / stride, 0, minMax.min, minMax.max);
  869. this.accessors.push(accessor);
  870. this.setAttributeKind(meshPrimitive, attributeKind);
  871. if (meshPrimitive.attributes.TEXCOORD_0 != null || meshPrimitive.attributes.TEXCOORD_1 != null) {
  872. uvCoordsPresent = true;
  873. }
  874. }
  875. }
  876. }
  877. }
  878. if (indexBufferViewIndex) {
  879. // Create accessor
  880. var accessor = GLTF2._GLTFUtilities.CreateAccessor(indexBufferViewIndex, "indices - " + babylonTransformNode.name, "SCALAR" /* SCALAR */, 5125 /* UNSIGNED_INT */, submesh.indexCount, submesh.indexStart * 4, null, null);
  881. this.accessors.push(accessor);
  882. meshPrimitive.indices = this.accessors.length - 1;
  883. }
  884. if (bufferMesh.material) {
  885. var materialIndex = null;
  886. if (bufferMesh.material instanceof BABYLON.StandardMaterial || bufferMesh.material instanceof BABYLON.PBRMetallicRoughnessMaterial || bufferMesh.material instanceof BABYLON.PBRMaterial) {
  887. materialIndex = babylonTransformNode.getScene().materials.indexOf(bufferMesh.material);
  888. }
  889. else if (bufferMesh.material instanceof BABYLON.MultiMaterial) {
  890. var babylonMultiMaterial = bufferMesh.material;
  891. var material = babylonMultiMaterial.subMaterials[submesh.materialIndex];
  892. if (material) {
  893. materialIndex = babylonTransformNode.getScene().materials.indexOf(material);
  894. }
  895. }
  896. else {
  897. BABYLON.Tools.Warn("Material type " + bufferMesh.material.getClassName() + " for material " + bufferMesh.material.name + " is not yet implemented in glTF serializer.");
  898. }
  899. if (materialIndex != null && Object.keys(meshPrimitive.attributes).length > 0) {
  900. var sideOrientation = this.babylonScene.materials[materialIndex].sideOrientation;
  901. this.setPrimitiveMode(meshPrimitive, primitiveMode);
  902. if (this.convertToRightHandedSystem && sideOrientation === BABYLON.Material.ClockWiseSideOrientation) {
  903. //Overwrite the indices to be counter-clockwise
  904. var byteOffset = indexBufferViewIndex != null ? this.bufferViews[indexBufferViewIndex].byteOffset : null;
  905. if (byteOffset == null) {
  906. byteOffset = 0;
  907. }
  908. var babylonIndices = null;
  909. if (indexBufferViewIndex != null) {
  910. babylonIndices = bufferMesh.getIndices();
  911. }
  912. if (babylonIndices) {
  913. this.reorderIndicesBasedOnPrimitiveMode(submesh, primitiveMode, babylonIndices, byteOffset, binaryWriter);
  914. }
  915. else {
  916. for (var _d = 0, attributeData_3 = attributeData; _d < attributeData_3.length; _d++) {
  917. var attribute = attributeData_3[_d];
  918. var vertexData = bufferMesh.getVerticesData(attribute.kind);
  919. if (vertexData) {
  920. var byteOffset_1 = this.bufferViews[vertexAttributeBufferViews[attribute.kind]].byteOffset;
  921. if (!byteOffset_1) {
  922. byteOffset_1 = 0;
  923. }
  924. this.reorderVertexAttributeDataBasedOnPrimitiveMode(submesh, primitiveMode, sideOrientation, attribute.kind, vertexData, byteOffset_1, binaryWriter);
  925. }
  926. }
  927. }
  928. }
  929. if (uvCoordsPresent) {
  930. if (!GLTF2._GLTFMaterial._HasTexturesPresent(this.materials[materialIndex])) {
  931. delete meshPrimitive.attributes.TEXCOORD_0;
  932. delete meshPrimitive.attributes.TEXCOORD_1;
  933. }
  934. meshPrimitive.material = materialIndex;
  935. }
  936. else {
  937. if (GLTF2._GLTFMaterial._HasTexturesPresent(this.materials[materialIndex])) {
  938. var newMat = GLTF2._GLTFMaterial._StripTexturesFromMaterial(this.materials[materialIndex]);
  939. this.materials.push(newMat);
  940. meshPrimitive.material = this.materials.length - 1;
  941. }
  942. else {
  943. meshPrimitive.material = materialIndex;
  944. }
  945. }
  946. }
  947. }
  948. else {
  949. var sideOrientation = this.babylonScene.defaultMaterial.sideOrientation;
  950. var byteOffset = indexBufferViewIndex != null ? this.bufferViews[indexBufferViewIndex].byteOffset : null;
  951. if (byteOffset == null) {
  952. byteOffset = 0;
  953. }
  954. var babylonIndices = null;
  955. if (indexBufferViewIndex != null) {
  956. babylonIndices = bufferMesh.getIndices();
  957. }
  958. if (babylonIndices) {
  959. if (sideOrientation === BABYLON.Material.ClockWiseSideOrientation) {
  960. this.reorderIndicesBasedOnPrimitiveMode(submesh, primitiveMode, babylonIndices, byteOffset, binaryWriter);
  961. }
  962. }
  963. else {
  964. for (var _e = 0, attributeData_4 = attributeData; _e < attributeData_4.length; _e++) {
  965. var attribute = attributeData_4[_e];
  966. var vertexData = bufferMesh.getVerticesData(attribute.kind);
  967. if (vertexData) {
  968. var byteOffset_2 = this.bufferViews[vertexAttributeBufferViews[attribute.kind]].byteOffset;
  969. if (!byteOffset_2) {
  970. byteOffset_2 = 0;
  971. }
  972. this.reorderVertexAttributeDataBasedOnPrimitiveMode(submesh, primitiveMode, sideOrientation, attribute.kind, vertexData, byteOffset_2, binaryWriter);
  973. }
  974. }
  975. }
  976. }
  977. mesh.primitives.push(meshPrimitive);
  978. }
  979. }
  980. }
  981. };
  982. /**
  983. * Creates a glTF scene based on the array of meshes
  984. * Returns the the total byte offset
  985. * @param babylonScene Babylon scene to get the mesh data from
  986. * @param binaryWriter Buffer to write binary data to
  987. */
  988. _Exporter.prototype.createScene = function (babylonScene, binaryWriter) {
  989. if (this.setNodeTransformation.length) {
  990. var scene = { nodes: [] };
  991. var glTFNodeIndex = void 0;
  992. var glTFNode = void 0;
  993. var directDescendents = void 0;
  994. var nodes = babylonScene.transformNodes.concat(babylonScene.meshes);
  995. GLTF2._GLTFMaterial._ConvertMaterialsToGLTF(babylonScene.materials, "image/png" /* PNG */, this.images, this.textures, this.samplers, this.materials, this.imageData, true);
  996. this.nodeMap = this.createNodeMapAndAnimations(babylonScene, nodes, this.shouldExportTransformNode, binaryWriter);
  997. this.totalByteLength = binaryWriter.getByteOffset();
  998. // Build Hierarchy with the node map.
  999. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  1000. var babylonTransformNode = nodes_1[_i];
  1001. glTFNodeIndex = this.nodeMap[babylonTransformNode.uniqueId];
  1002. if (glTFNodeIndex != null) {
  1003. glTFNode = this.nodes[glTFNodeIndex];
  1004. if (!babylonTransformNode.parent) {
  1005. if (!this.shouldExportTransformNode(babylonTransformNode)) {
  1006. BABYLON.Tools.Log("Omitting " + babylonTransformNode.name + " from scene.");
  1007. }
  1008. else {
  1009. if (this.convertToRightHandedSystem) {
  1010. if (glTFNode.translation) {
  1011. glTFNode.translation[2] *= -1;
  1012. glTFNode.translation[0] *= -1;
  1013. }
  1014. glTFNode.rotation = glTFNode.rotation ? BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(BABYLON.Quaternion.FromArray(glTFNode.rotation)).asArray() : (BABYLON.Quaternion.FromArray([0, 1, 0, 0])).asArray();
  1015. }
  1016. scene.nodes.push(glTFNodeIndex);
  1017. }
  1018. }
  1019. directDescendents = babylonTransformNode.getDescendants(true);
  1020. if (!glTFNode.children && directDescendents && directDescendents.length) {
  1021. glTFNode.children = [];
  1022. for (var _a = 0, directDescendents_1 = directDescendents; _a < directDescendents_1.length; _a++) {
  1023. var descendent = directDescendents_1[_a];
  1024. if (this.nodeMap[descendent.uniqueId] != null) {
  1025. glTFNode.children.push(this.nodeMap[descendent.uniqueId]);
  1026. }
  1027. }
  1028. }
  1029. }
  1030. }
  1031. ;
  1032. if (scene.nodes.length) {
  1033. this.scenes.push(scene);
  1034. }
  1035. }
  1036. };
  1037. /**
  1038. * Creates a mapping of Node unique id to node index and handles animations
  1039. * @param babylonScene Babylon Scene
  1040. * @param binaryWriter Buffer to write binary data to
  1041. * @returns Node mapping of unique id to index
  1042. */
  1043. _Exporter.prototype.createNodeMapAndAnimations = function (babylonScene, nodes, shouldExportTransformNode, binaryWriter) {
  1044. var _this = this;
  1045. var nodeMap = {};
  1046. var nodeIndex;
  1047. var runtimeGLTFAnimation = {
  1048. name: 'runtime animations',
  1049. channels: [],
  1050. samplers: []
  1051. };
  1052. var idleGLTFAnimations = [];
  1053. var node;
  1054. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  1055. var babylonTransformNode = nodes_2[_i];
  1056. if (shouldExportTransformNode(babylonTransformNode)) {
  1057. node = this.createNode(babylonTransformNode, binaryWriter);
  1058. this.nodes.push(node);
  1059. nodeIndex = this.nodes.length - 1;
  1060. nodeMap[babylonTransformNode.uniqueId] = nodeIndex;
  1061. if (!babylonScene.animationGroups.length && babylonTransformNode.animations.length) {
  1062. GLTF2._GLTFAnimation._CreateNodeAnimationFromTransformNodeAnimations(babylonTransformNode, runtimeGLTFAnimation, idleGLTFAnimations, nodeMap, this.nodes, binaryWriter, this.bufferViews, this.accessors, this.convertToRightHandedSystem, this.animationSampleRate);
  1063. }
  1064. }
  1065. else {
  1066. "Excluding mesh " + babylonTransformNode.name;
  1067. }
  1068. }
  1069. ;
  1070. if (runtimeGLTFAnimation.channels.length && runtimeGLTFAnimation.samplers.length) {
  1071. this.animations.push(runtimeGLTFAnimation);
  1072. }
  1073. idleGLTFAnimations.forEach(function (idleGLTFAnimation) {
  1074. if (idleGLTFAnimation.channels.length && idleGLTFAnimation.samplers.length) {
  1075. _this.animations.push(idleGLTFAnimation);
  1076. }
  1077. });
  1078. if (babylonScene.animationGroups.length) {
  1079. GLTF2._GLTFAnimation._CreateNodeAnimationFromAnimationGroups(babylonScene, this.animations, nodeMap, this.nodes, binaryWriter, this.bufferViews, this.accessors, this.convertToRightHandedSystem, this.animationSampleRate);
  1080. }
  1081. return nodeMap;
  1082. };
  1083. /**
  1084. * Creates a glTF node from a Babylon mesh
  1085. * @param babylonMesh Source Babylon mesh
  1086. * @param binaryWriter Buffer for storing geometry data
  1087. * @returns glTF node
  1088. */
  1089. _Exporter.prototype.createNode = function (babylonTransformNode, binaryWriter) {
  1090. // create node to hold translation/rotation/scale and the mesh
  1091. var node = {};
  1092. // create mesh
  1093. var mesh = { primitives: [] };
  1094. if (babylonTransformNode.name) {
  1095. node.name = babylonTransformNode.name;
  1096. }
  1097. // Set transformation
  1098. this.setNodeTransformation(node, babylonTransformNode);
  1099. this.setPrimitiveAttributes(mesh, babylonTransformNode, binaryWriter);
  1100. if (mesh.primitives.length) {
  1101. this.meshes.push(mesh);
  1102. node.mesh = this.meshes.length - 1;
  1103. }
  1104. return node;
  1105. };
  1106. return _Exporter;
  1107. }());
  1108. GLTF2._Exporter = _Exporter;
  1109. /**
  1110. * @hidden
  1111. *
  1112. * Stores glTF binary data. If the array buffer byte length is exceeded, it doubles in size dynamically
  1113. */
  1114. var _BinaryWriter = /** @class */ (function () {
  1115. /**
  1116. * Initialize binary writer with an initial byte length
  1117. * @param byteLength Initial byte length of the array buffer
  1118. */
  1119. function _BinaryWriter(byteLength) {
  1120. this._arrayBuffer = new ArrayBuffer(byteLength);
  1121. this._dataView = new DataView(this._arrayBuffer);
  1122. this._byteOffset = 0;
  1123. }
  1124. /**
  1125. * Resize the array buffer to the specified byte length
  1126. * @param byteLength
  1127. */
  1128. _BinaryWriter.prototype.resizeBuffer = function (byteLength) {
  1129. var newBuffer = new ArrayBuffer(byteLength);
  1130. var oldUint8Array = new Uint8Array(this._arrayBuffer);
  1131. var newUint8Array = new Uint8Array(newBuffer);
  1132. for (var i = 0, length_8 = newUint8Array.byteLength; i < length_8; ++i) {
  1133. newUint8Array[i] = oldUint8Array[i];
  1134. }
  1135. this._arrayBuffer = newBuffer;
  1136. this._dataView = new DataView(this._arrayBuffer);
  1137. };
  1138. /**
  1139. * Get an array buffer with the length of the byte offset
  1140. * @returns ArrayBuffer resized to the byte offset
  1141. */
  1142. _BinaryWriter.prototype.getArrayBuffer = function () {
  1143. this.resizeBuffer(this.getByteOffset());
  1144. return this._arrayBuffer;
  1145. };
  1146. /**
  1147. * Get the byte offset of the array buffer
  1148. * @returns byte offset
  1149. */
  1150. _BinaryWriter.prototype.getByteOffset = function () {
  1151. return this._byteOffset;
  1152. };
  1153. /**
  1154. * Stores an UInt8 in the array buffer
  1155. * @param entry
  1156. * @param byteOffset If defined, specifies where to set the value as an offset.
  1157. */
  1158. _BinaryWriter.prototype.setUInt8 = function (entry, byteOffset) {
  1159. if (byteOffset != null) {
  1160. if (byteOffset < this._byteOffset) {
  1161. this._dataView.setUint8(byteOffset, entry);
  1162. }
  1163. else {
  1164. BABYLON.Tools.Error('BinaryWriter: byteoffset is greater than the current binary buffer length!');
  1165. }
  1166. }
  1167. else {
  1168. if (this._byteOffset + 1 > this._arrayBuffer.byteLength) {
  1169. this.resizeBuffer(this._arrayBuffer.byteLength * 2);
  1170. }
  1171. this._dataView.setUint8(this._byteOffset++, entry);
  1172. }
  1173. };
  1174. /**
  1175. * Gets an UInt32 in the array buffer
  1176. * @param entry
  1177. * @param byteOffset If defined, specifies where to set the value as an offset.
  1178. */
  1179. _BinaryWriter.prototype.getUInt32 = function (byteOffset) {
  1180. if (byteOffset < this._byteOffset) {
  1181. return this._dataView.getUint32(byteOffset, true);
  1182. }
  1183. else {
  1184. BABYLON.Tools.Error('BinaryWriter: byteoffset is greater than the current binary buffer length!');
  1185. throw new Error('BinaryWriter: byteoffset is greater than the current binary buffer length!');
  1186. }
  1187. };
  1188. _BinaryWriter.prototype.getVector3Float32FromRef = function (vector3, byteOffset) {
  1189. if (byteOffset + 8 > this._byteOffset) {
  1190. BABYLON.Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!");
  1191. }
  1192. else {
  1193. vector3.x = this._dataView.getFloat32(byteOffset, true);
  1194. vector3.y = this._dataView.getFloat32(byteOffset + 4, true);
  1195. vector3.z = this._dataView.getFloat32(byteOffset + 8, true);
  1196. }
  1197. };
  1198. _BinaryWriter.prototype.setVector3Float32FromRef = function (vector3, byteOffset) {
  1199. if (byteOffset + 8 > this._byteOffset) {
  1200. BABYLON.Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!");
  1201. }
  1202. else {
  1203. this._dataView.setFloat32(byteOffset, vector3.x, true);
  1204. this._dataView.setFloat32(byteOffset + 4, vector3.y, true);
  1205. this._dataView.setFloat32(byteOffset + 8, vector3.z, true);
  1206. }
  1207. };
  1208. _BinaryWriter.prototype.getVector4Float32FromRef = function (vector4, byteOffset) {
  1209. if (byteOffset + 12 > this._byteOffset) {
  1210. BABYLON.Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!");
  1211. }
  1212. else {
  1213. vector4.x = this._dataView.getFloat32(byteOffset, true);
  1214. vector4.y = this._dataView.getFloat32(byteOffset + 4, true);
  1215. vector4.z = this._dataView.getFloat32(byteOffset + 8, true);
  1216. vector4.w = this._dataView.getFloat32(byteOffset + 12, true);
  1217. }
  1218. };
  1219. _BinaryWriter.prototype.setVector4Float32FromRef = function (vector4, byteOffset) {
  1220. if (byteOffset + 12 > this._byteOffset) {
  1221. BABYLON.Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!");
  1222. }
  1223. else {
  1224. this._dataView.setFloat32(byteOffset, vector4.x, true);
  1225. this._dataView.setFloat32(byteOffset + 4, vector4.y, true);
  1226. this._dataView.setFloat32(byteOffset + 8, vector4.z, true);
  1227. this._dataView.setFloat32(byteOffset + 12, vector4.w, true);
  1228. }
  1229. };
  1230. /**
  1231. * Stores a Float32 in the array buffer
  1232. * @param entry
  1233. */
  1234. _BinaryWriter.prototype.setFloat32 = function (entry, byteOffset) {
  1235. if (isNaN(entry)) {
  1236. BABYLON.Tools.Error('Invalid data being written!');
  1237. }
  1238. if (byteOffset != null) {
  1239. if (byteOffset < this._byteOffset) {
  1240. this._dataView.setFloat32(byteOffset, entry, true);
  1241. }
  1242. else {
  1243. BABYLON.Tools.Error('BinaryWriter: byteoffset is greater than the current binary length!');
  1244. }
  1245. }
  1246. if (this._byteOffset + 4 > this._arrayBuffer.byteLength) {
  1247. this.resizeBuffer(this._arrayBuffer.byteLength * 2);
  1248. }
  1249. this._dataView.setFloat32(this._byteOffset, entry, true);
  1250. this._byteOffset += 4;
  1251. };
  1252. /**
  1253. * Stores an UInt32 in the array buffer
  1254. * @param entry
  1255. * @param byteOffset If defined, specifies where to set the value as an offset.
  1256. */
  1257. _BinaryWriter.prototype.setUInt32 = function (entry, byteOffset) {
  1258. if (byteOffset != null) {
  1259. if (byteOffset < this._byteOffset) {
  1260. this._dataView.setUint32(byteOffset, entry, true);
  1261. }
  1262. else {
  1263. BABYLON.Tools.Error('BinaryWriter: byteoffset is greater than the current binary buffer length!');
  1264. }
  1265. }
  1266. else {
  1267. if (this._byteOffset + 4 > this._arrayBuffer.byteLength) {
  1268. this.resizeBuffer(this._arrayBuffer.byteLength * 2);
  1269. }
  1270. this._dataView.setUint32(this._byteOffset, entry, true);
  1271. this._byteOffset += 4;
  1272. }
  1273. };
  1274. return _BinaryWriter;
  1275. }());
  1276. GLTF2._BinaryWriter = _BinaryWriter;
  1277. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1278. })(BABYLON || (BABYLON = {}));
  1279. //# sourceMappingURL=babylon.glTFExporter.js.map
  1280. /// <reference path="../../../../dist/preview release/gltf2Interface/babylon.glTF2Interface.d.ts"/>
  1281. var BABYLON;
  1282. (function (BABYLON) {
  1283. /**
  1284. * Class for holding and downloading glTF file data
  1285. */
  1286. var GLTFData = /** @class */ (function () {
  1287. /**
  1288. * Initializes the glTF file object
  1289. */
  1290. function GLTFData() {
  1291. this.glTFFiles = {};
  1292. }
  1293. /**
  1294. * Downloads the glTF data as files based on their names and data
  1295. */
  1296. GLTFData.prototype.downloadFiles = function () {
  1297. /**
  1298. * Checks for a matching suffix at the end of a string (for ES5 and lower)
  1299. * @param str Source string
  1300. * @param suffix Suffix to search for in the source string
  1301. * @returns Boolean indicating whether the suffix was found (true) or not (false)
  1302. */
  1303. function endsWith(str, suffix) {
  1304. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  1305. }
  1306. for (var key in this.glTFFiles) {
  1307. var link = document.createElement('a');
  1308. document.body.appendChild(link);
  1309. link.setAttribute("type", "hidden");
  1310. link.download = key;
  1311. var blob = this.glTFFiles[key];
  1312. var mimeType = void 0;
  1313. if (endsWith(key, ".glb")) {
  1314. mimeType = { type: "model/gltf-binary" };
  1315. }
  1316. else if (endsWith(key, ".bin")) {
  1317. mimeType = { type: "application/octet-stream" };
  1318. }
  1319. else if (endsWith(key, ".gltf")) {
  1320. mimeType = { type: "model/gltf+json" };
  1321. }
  1322. else if (endsWith(key, ".jpeg" || ".jpg")) {
  1323. mimeType = { type: "image/jpeg" /* JPEG */ };
  1324. }
  1325. else if (endsWith(key, ".png")) {
  1326. mimeType = { type: "image/png" /* PNG */ };
  1327. }
  1328. link.href = window.URL.createObjectURL(new Blob([blob], mimeType));
  1329. link.click();
  1330. }
  1331. };
  1332. return GLTFData;
  1333. }());
  1334. BABYLON.GLTFData = GLTFData;
  1335. })(BABYLON || (BABYLON = {}));
  1336. //# sourceMappingURL=babylon.glTFData.js.map
  1337. /// <reference path="../../../../dist/preview release/gltf2Interface/babylon.glTF2Interface.d.ts"/>
  1338. var BABYLON;
  1339. (function (BABYLON) {
  1340. var GLTF2;
  1341. (function (GLTF2) {
  1342. /**
  1343. * Utility methods for working with glTF material conversion properties. This class should only be used internally
  1344. * @hidden
  1345. */
  1346. var _GLTFMaterial = /** @class */ (function () {
  1347. function _GLTFMaterial() {
  1348. }
  1349. /**
  1350. * Specifies if two colors are approximately equal in value
  1351. * @param color1 first color to compare to
  1352. * @param color2 second color to compare to
  1353. * @param epsilon threshold value
  1354. */
  1355. _GLTFMaterial.FuzzyEquals = function (color1, color2, epsilon) {
  1356. return BABYLON.Scalar.WithinEpsilon(color1.r, color2.r, epsilon) &&
  1357. BABYLON.Scalar.WithinEpsilon(color1.g, color2.g, epsilon) &&
  1358. BABYLON.Scalar.WithinEpsilon(color1.b, color2.b, epsilon);
  1359. };
  1360. /**
  1361. * Gets the materials from a Babylon scene and converts them to glTF materials
  1362. * @param scene babylonjs scene
  1363. * @param mimeType texture mime type
  1364. * @param images array of images
  1365. * @param textures array of textures
  1366. * @param materials array of materials
  1367. * @param imageData mapping of texture names to base64 textures
  1368. * @param hasTextureCoords specifies if texture coordinates are present on the material
  1369. */
  1370. _GLTFMaterial._ConvertMaterialsToGLTF = function (babylonMaterials, mimeType, images, textures, samplers, materials, imageData, hasTextureCoords) {
  1371. for (var _i = 0, babylonMaterials_1 = babylonMaterials; _i < babylonMaterials_1.length; _i++) {
  1372. var babylonMaterial = babylonMaterials_1[_i];
  1373. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  1374. _GLTFMaterial._ConvertStandardMaterial(babylonMaterial, mimeType, images, textures, samplers, materials, imageData, hasTextureCoords);
  1375. }
  1376. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  1377. _GLTFMaterial._ConvertPBRMetallicRoughnessMaterial(babylonMaterial, mimeType, images, textures, samplers, materials, imageData, hasTextureCoords);
  1378. }
  1379. else if (babylonMaterial instanceof BABYLON.PBRMaterial) {
  1380. _GLTFMaterial._ConvertPBRMaterial(babylonMaterial, mimeType, images, textures, samplers, materials, imageData, hasTextureCoords);
  1381. }
  1382. else {
  1383. BABYLON.Tools.Error("Unsupported material type: " + babylonMaterial.name);
  1384. }
  1385. }
  1386. };
  1387. /**
  1388. * Makes a copy of the glTF material without the texture parameters
  1389. * @param originalMaterial original glTF material
  1390. * @returns glTF material without texture parameters
  1391. */
  1392. _GLTFMaterial._StripTexturesFromMaterial = function (originalMaterial) {
  1393. var newMaterial = {};
  1394. if (originalMaterial) {
  1395. newMaterial.name = originalMaterial.name;
  1396. newMaterial.doubleSided = originalMaterial.doubleSided;
  1397. newMaterial.alphaMode = originalMaterial.alphaMode;
  1398. newMaterial.alphaCutoff = originalMaterial.alphaCutoff;
  1399. newMaterial.emissiveFactor = originalMaterial.emissiveFactor;
  1400. var originalPBRMetallicRoughness = originalMaterial.pbrMetallicRoughness;
  1401. if (originalPBRMetallicRoughness) {
  1402. newMaterial.pbrMetallicRoughness = {};
  1403. newMaterial.pbrMetallicRoughness.baseColorFactor = originalPBRMetallicRoughness.baseColorFactor;
  1404. newMaterial.pbrMetallicRoughness.metallicFactor = originalPBRMetallicRoughness.metallicFactor;
  1405. newMaterial.pbrMetallicRoughness.roughnessFactor = originalPBRMetallicRoughness.roughnessFactor;
  1406. }
  1407. }
  1408. return newMaterial;
  1409. };
  1410. /**
  1411. * Specifies if the material has any texture parameters present
  1412. * @param material glTF Material
  1413. * @returns boolean specifying if texture parameters are present
  1414. */
  1415. _GLTFMaterial._HasTexturesPresent = function (material) {
  1416. if (material.emissiveTexture || material.normalTexture || material.occlusionTexture) {
  1417. return true;
  1418. }
  1419. var pbrMat = material.pbrMetallicRoughness;
  1420. if (pbrMat) {
  1421. if (pbrMat.baseColorTexture || pbrMat.metallicRoughnessTexture) {
  1422. return true;
  1423. }
  1424. }
  1425. return false;
  1426. };
  1427. /**
  1428. * Converts a Babylon StandardMaterial to a glTF Metallic Roughness Material
  1429. * @param babylonStandardMaterial
  1430. * @returns glTF Metallic Roughness Material representation
  1431. */
  1432. _GLTFMaterial._ConvertToGLTFPBRMetallicRoughness = function (babylonStandardMaterial) {
  1433. var P0 = new BABYLON.Vector2(0, 1);
  1434. var P1 = new BABYLON.Vector2(0, 0.1);
  1435. var P2 = new BABYLON.Vector2(0, 0.1);
  1436. var P3 = new BABYLON.Vector2(1300, 0.1);
  1437. /**
  1438. * Given the control points, solve for x based on a given t for a cubic bezier curve
  1439. * @param t a value between 0 and 1
  1440. * @param p0 first control point
  1441. * @param p1 second control point
  1442. * @param p2 third control point
  1443. * @param p3 fourth control point
  1444. * @returns number result of cubic bezier curve at the specified t
  1445. */
  1446. function _cubicBezierCurve(t, p0, p1, p2, p3) {
  1447. return ((1 - t) * (1 - t) * (1 - t) * p0 +
  1448. 3 * (1 - t) * (1 - t) * t * p1 +
  1449. 3 * (1 - t) * t * t * p2 +
  1450. t * t * t * p3);
  1451. }
  1452. /**
  1453. * Evaluates a specified specular power value to determine the appropriate roughness value,
  1454. * based on a pre-defined cubic bezier curve with specular on the abscissa axis (x-axis)
  1455. * and roughness on the ordinant axis (y-axis)
  1456. * @param specularPower specular power of standard material
  1457. * @returns Number representing the roughness value
  1458. */
  1459. function _solveForRoughness(specularPower) {
  1460. var t = Math.pow(specularPower / P3.x, 0.333333);
  1461. return _cubicBezierCurve(t, P0.y, P1.y, P2.y, P3.y);
  1462. }
  1463. var diffuse = babylonStandardMaterial.diffuseColor.toLinearSpace().scale(0.5);
  1464. var opacity = babylonStandardMaterial.alpha;
  1465. var specularPower = BABYLON.Scalar.Clamp(babylonStandardMaterial.specularPower, 0, this._maxSpecularPower);
  1466. var roughness = _solveForRoughness(specularPower);
  1467. var glTFPbrMetallicRoughness = {
  1468. baseColorFactor: [
  1469. diffuse.r,
  1470. diffuse.g,
  1471. diffuse.b,
  1472. opacity
  1473. ],
  1474. metallicFactor: 0,
  1475. roughnessFactor: roughness,
  1476. };
  1477. return glTFPbrMetallicRoughness;
  1478. };
  1479. /**
  1480. * Computes the metallic factor
  1481. * @param diffuse diffused value
  1482. * @param specular specular value
  1483. * @param oneMinusSpecularStrength one minus the specular strength
  1484. * @returns metallic value
  1485. */
  1486. _GLTFMaterial._SolveMetallic = function (diffuse, specular, oneMinusSpecularStrength) {
  1487. if (specular < _GLTFMaterial._dielectricSpecular.r) {
  1488. _GLTFMaterial._dielectricSpecular;
  1489. return 0;
  1490. }
  1491. var a = _GLTFMaterial._dielectricSpecular.r;
  1492. var b = diffuse * oneMinusSpecularStrength / (1.0 - _GLTFMaterial._dielectricSpecular.r) + specular - 2.0 * _GLTFMaterial._dielectricSpecular.r;
  1493. var c = _GLTFMaterial._dielectricSpecular.r - specular;
  1494. var D = b * b - 4.0 * a * c;
  1495. return BABYLON.Scalar.Clamp((-b + Math.sqrt(D)) / (2.0 * a), 0, 1);
  1496. };
  1497. /**
  1498. * Gets the glTF alpha mode from the Babylon Material
  1499. * @param babylonMaterial Babylon Material
  1500. * @returns The Babylon alpha mode value
  1501. */
  1502. _GLTFMaterial._GetAlphaMode = function (babylonMaterial) {
  1503. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  1504. var babylonStandardMaterial = babylonMaterial;
  1505. if ((babylonStandardMaterial.alpha != 1.0) ||
  1506. (babylonStandardMaterial.diffuseTexture != null && babylonStandardMaterial.diffuseTexture.hasAlpha) ||
  1507. (babylonStandardMaterial.opacityTexture != null)) {
  1508. return "BLEND" /* BLEND */;
  1509. }
  1510. else {
  1511. return "OPAQUE" /* OPAQUE */;
  1512. }
  1513. }
  1514. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  1515. var babylonPBRMetallicRoughness = babylonMaterial;
  1516. switch (babylonPBRMetallicRoughness.transparencyMode) {
  1517. case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
  1518. return "OPAQUE" /* OPAQUE */;
  1519. }
  1520. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
  1521. return "BLEND" /* BLEND */;
  1522. }
  1523. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
  1524. return "MASK" /* MASK */;
  1525. }
  1526. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
  1527. BABYLON.Tools.Warn(babylonMaterial.name + ": GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
  1528. return "BLEND" /* BLEND */;
  1529. }
  1530. default: {
  1531. BABYLON.Tools.Error("Unsupported alpha mode " + babylonPBRMetallicRoughness.transparencyMode);
  1532. return null;
  1533. }
  1534. }
  1535. }
  1536. else if (babylonMaterial instanceof BABYLON.PBRMaterial) {
  1537. var babylonPBRMaterial = babylonMaterial;
  1538. switch (babylonPBRMaterial.transparencyMode) {
  1539. case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
  1540. return "OPAQUE" /* OPAQUE */;
  1541. }
  1542. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
  1543. return "BLEND" /* BLEND */;
  1544. }
  1545. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
  1546. return "MASK" /* MASK */;
  1547. }
  1548. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
  1549. BABYLON.Tools.Warn(babylonMaterial.name + ": GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
  1550. return "BLEND" /* BLEND */;
  1551. }
  1552. default: {
  1553. BABYLON.Tools.Error("Unsupported alpha mode " + babylonPBRMaterial.transparencyMode);
  1554. return null;
  1555. }
  1556. }
  1557. }
  1558. else {
  1559. BABYLON.Tools.Error("Unsupported Babylon material type");
  1560. return null;
  1561. }
  1562. };
  1563. /**
  1564. * Converts a Babylon Standard Material to a glTF Material
  1565. * @param babylonStandardMaterial BJS Standard Material
  1566. * @param mimeType mime type to use for the textures
  1567. * @param images array of glTF image interfaces
  1568. * @param textures array of glTF texture interfaces
  1569. * @param materials array of glTF material interfaces
  1570. * @param imageData map of image file name to data
  1571. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  1572. */
  1573. _GLTFMaterial._ConvertStandardMaterial = function (babylonStandardMaterial, mimeType, images, textures, samplers, materials, imageData, hasTextureCoords) {
  1574. var glTFPbrMetallicRoughness = _GLTFMaterial._ConvertToGLTFPBRMetallicRoughness(babylonStandardMaterial);
  1575. var glTFMaterial = { name: babylonStandardMaterial.name };
  1576. if (babylonStandardMaterial.backFaceCulling != null && !babylonStandardMaterial.backFaceCulling) {
  1577. if (!babylonStandardMaterial.twoSidedLighting) {
  1578. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  1579. }
  1580. glTFMaterial.doubleSided = true;
  1581. }
  1582. if (hasTextureCoords) {
  1583. if (babylonStandardMaterial.diffuseTexture) {
  1584. var glTFTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.diffuseTexture, mimeType, images, textures, samplers, imageData);
  1585. if (glTFTexture != null) {
  1586. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1587. }
  1588. }
  1589. if (babylonStandardMaterial.bumpTexture) {
  1590. var glTFTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.bumpTexture, mimeType, images, textures, samplers, imageData);
  1591. if (glTFTexture) {
  1592. glTFMaterial.normalTexture = glTFTexture;
  1593. if (babylonStandardMaterial.bumpTexture.level !== 1) {
  1594. glTFMaterial.normalTexture.scale = babylonStandardMaterial.bumpTexture.level;
  1595. }
  1596. }
  1597. }
  1598. if (babylonStandardMaterial.emissiveTexture) {
  1599. var glTFEmissiveTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.emissiveTexture, mimeType, images, textures, samplers, imageData);
  1600. if (glTFEmissiveTexture) {
  1601. glTFMaterial.emissiveTexture = glTFEmissiveTexture;
  1602. }
  1603. glTFMaterial.emissiveFactor = [1.0, 1.0, 1.0];
  1604. }
  1605. if (babylonStandardMaterial.ambientTexture) {
  1606. var glTFTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.ambientTexture, mimeType, images, textures, samplers, imageData);
  1607. if (glTFTexture) {
  1608. var occlusionTexture = {
  1609. index: glTFTexture.index
  1610. };
  1611. glTFMaterial.occlusionTexture = occlusionTexture;
  1612. occlusionTexture.strength = 1.0;
  1613. }
  1614. }
  1615. }
  1616. if (babylonStandardMaterial.alpha < 1.0 || babylonStandardMaterial.opacityTexture) {
  1617. if (babylonStandardMaterial.alphaMode === BABYLON.Engine.ALPHA_COMBINE) {
  1618. glTFMaterial.alphaMode = "BLEND" /* BLEND */;
  1619. }
  1620. else {
  1621. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": glTF 2.0 does not support alpha mode: " + babylonStandardMaterial.alphaMode.toString());
  1622. }
  1623. }
  1624. if (babylonStandardMaterial.emissiveColor && !this.FuzzyEquals(babylonStandardMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  1625. glTFMaterial.emissiveFactor = babylonStandardMaterial.emissiveColor.asArray();
  1626. }
  1627. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1628. materials.push(glTFMaterial);
  1629. };
  1630. /**
  1631. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material
  1632. * @param babylonPBRMetalRoughMaterial BJS PBR Metallic Roughness Material
  1633. * @param mimeType mime type to use for the textures
  1634. * @param images array of glTF image interfaces
  1635. * @param textures array of glTF texture interfaces
  1636. * @param materials array of glTF material interfaces
  1637. * @param imageData map of image file name to data
  1638. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  1639. */
  1640. _GLTFMaterial._ConvertPBRMetallicRoughnessMaterial = function (babylonPBRMetalRoughMaterial, mimeType, images, textures, samplers, materials, imageData, hasTextureCoords) {
  1641. var glTFPbrMetallicRoughness = {};
  1642. if (babylonPBRMetalRoughMaterial.baseColor) {
  1643. glTFPbrMetallicRoughness.baseColorFactor = [
  1644. babylonPBRMetalRoughMaterial.baseColor.r,
  1645. babylonPBRMetalRoughMaterial.baseColor.g,
  1646. babylonPBRMetalRoughMaterial.baseColor.b,
  1647. babylonPBRMetalRoughMaterial.alpha
  1648. ];
  1649. }
  1650. if (babylonPBRMetalRoughMaterial.metallic != null && babylonPBRMetalRoughMaterial.metallic !== 1) {
  1651. glTFPbrMetallicRoughness.metallicFactor = babylonPBRMetalRoughMaterial.metallic;
  1652. }
  1653. if (babylonPBRMetalRoughMaterial.roughness != null && babylonPBRMetalRoughMaterial.roughness !== 1) {
  1654. glTFPbrMetallicRoughness.roughnessFactor = babylonPBRMetalRoughMaterial.roughness;
  1655. }
  1656. var glTFMaterial = {
  1657. name: babylonPBRMetalRoughMaterial.name
  1658. };
  1659. if (babylonPBRMetalRoughMaterial.doubleSided) {
  1660. glTFMaterial.doubleSided = babylonPBRMetalRoughMaterial.doubleSided;
  1661. }
  1662. if (hasTextureCoords) {
  1663. if (babylonPBRMetalRoughMaterial.baseTexture != null) {
  1664. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.baseTexture, mimeType, images, textures, samplers, imageData);
  1665. if (glTFTexture != null) {
  1666. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1667. }
  1668. }
  1669. if (babylonPBRMetalRoughMaterial.normalTexture) {
  1670. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.normalTexture, mimeType, images, textures, samplers, imageData);
  1671. if (glTFTexture) {
  1672. glTFMaterial.normalTexture = glTFTexture;
  1673. if (babylonPBRMetalRoughMaterial.normalTexture.level !== 1) {
  1674. glTFMaterial.normalTexture.scale = babylonPBRMetalRoughMaterial.normalTexture.level;
  1675. }
  1676. }
  1677. }
  1678. if (babylonPBRMetalRoughMaterial.occlusionTexture) {
  1679. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.occlusionTexture, mimeType, images, textures, samplers, imageData);
  1680. if (glTFTexture) {
  1681. glTFMaterial.occlusionTexture = glTFTexture;
  1682. if (babylonPBRMetalRoughMaterial.occlusionStrength != null) {
  1683. glTFMaterial.occlusionTexture.strength = babylonPBRMetalRoughMaterial.occlusionStrength;
  1684. }
  1685. }
  1686. }
  1687. if (babylonPBRMetalRoughMaterial.emissiveTexture) {
  1688. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.emissiveTexture, mimeType, images, textures, samplers, imageData);
  1689. if (glTFTexture != null) {
  1690. glTFMaterial.emissiveTexture = glTFTexture;
  1691. }
  1692. }
  1693. }
  1694. if (this.FuzzyEquals(babylonPBRMetalRoughMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  1695. glTFMaterial.emissiveFactor = babylonPBRMetalRoughMaterial.emissiveColor.asArray();
  1696. }
  1697. if (babylonPBRMetalRoughMaterial.transparencyMode != null) {
  1698. var alphaMode = _GLTFMaterial._GetAlphaMode(babylonPBRMetalRoughMaterial);
  1699. if (alphaMode) {
  1700. if (alphaMode !== "OPAQUE" /* OPAQUE */) { //glTF defaults to opaque
  1701. glTFMaterial.alphaMode = alphaMode;
  1702. if (alphaMode === "MASK" /* MASK */) {
  1703. glTFMaterial.alphaCutoff = babylonPBRMetalRoughMaterial.alphaCutOff;
  1704. }
  1705. }
  1706. }
  1707. }
  1708. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1709. materials.push(glTFMaterial);
  1710. };
  1711. /**
  1712. * Converts an image typed array buffer to a base64 image
  1713. * @param buffer typed array buffer
  1714. * @param width width of the image
  1715. * @param height height of the image
  1716. * @param mimeType mimetype of the image
  1717. * @returns base64 image string
  1718. */
  1719. _GLTFMaterial._CreateBase64FromCanvas = function (buffer, width, height, mimeType) {
  1720. var imageCanvas = document.createElement('canvas');
  1721. imageCanvas.width = width;
  1722. imageCanvas.height = height;
  1723. imageCanvas.id = "WriteCanvas";
  1724. var ctx = imageCanvas.getContext('2d');
  1725. var imgData = ctx.createImageData(width, height);
  1726. imgData.data.set(buffer);
  1727. ctx.putImageData(imgData, 0, 0);
  1728. return imageCanvas.toDataURL(mimeType);
  1729. };
  1730. /**
  1731. * Generates a white texture based on the specified width and height
  1732. * @param width width of the texture in pixels
  1733. * @param height height of the texture in pixels
  1734. * @param scene babylonjs scene
  1735. * @returns white texture
  1736. */
  1737. _GLTFMaterial._CreateWhiteTexture = function (width, height, scene) {
  1738. var data = new Uint8Array(width * height * 4);
  1739. for (var i = 0; i < data.length; i = i + 4) {
  1740. data[i] = data[i + 1] = data[i + 2] = data[i + 3] = 0xFF;
  1741. }
  1742. var rawTexture = BABYLON.RawTexture.CreateRGBATexture(data, width, height, scene);
  1743. return rawTexture;
  1744. };
  1745. /**
  1746. * Resizes the two source textures to the same dimensions. If a texture is null, a default white texture is generated. If both textures are null, returns null
  1747. * @param texture1 first texture to resize
  1748. * @param texture2 second texture to resize
  1749. * @param scene babylonjs scene
  1750. * @returns resized textures or null
  1751. */
  1752. _GLTFMaterial._ResizeTexturesToSameDimensions = function (texture1, texture2, scene) {
  1753. var texture1Size = texture1 ? texture1.getSize() : { width: 0, height: 0 };
  1754. var texture2Size = texture2 ? texture2.getSize() : { width: 0, height: 0 };
  1755. var resizedTexture1;
  1756. var resizedTexture2;
  1757. if (texture1Size.width < texture2Size.width) {
  1758. if (texture1) {
  1759. resizedTexture1 = BABYLON.TextureTools.CreateResizedCopy(texture1, texture2Size.width, texture2Size.height, true);
  1760. }
  1761. else {
  1762. resizedTexture1 = this._CreateWhiteTexture(texture2Size.width, texture2Size.height, scene);
  1763. }
  1764. resizedTexture2 = texture2;
  1765. }
  1766. else if (texture1Size.width > texture2Size.width) {
  1767. if (texture2) {
  1768. resizedTexture2 = BABYLON.TextureTools.CreateResizedCopy(texture2, texture1Size.width, texture1Size.height, true);
  1769. }
  1770. else {
  1771. resizedTexture2 = this._CreateWhiteTexture(texture1Size.width, texture1Size.height, scene);
  1772. }
  1773. resizedTexture1 = texture1;
  1774. }
  1775. else {
  1776. resizedTexture1 = texture1;
  1777. resizedTexture2 = texture2;
  1778. }
  1779. return {
  1780. "texture1": resizedTexture1,
  1781. "texture2": resizedTexture2
  1782. };
  1783. };
  1784. /**
  1785. * Convert Specular Glossiness Textures to Metallic Roughness
  1786. * See link below for info on the material conversions from PBR Metallic/Roughness and Specular/Glossiness
  1787. * @link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness/examples/convert-between-workflows-bjs/js/babylon.pbrUtilities.js
  1788. * @param diffuseTexture texture used to store diffuse information
  1789. * @param specularGlossinessTexture texture used to store specular and glossiness information
  1790. * @param factors specular glossiness material factors
  1791. * @param mimeType the mime type to use for the texture
  1792. * @returns pbr metallic roughness interface or null
  1793. */
  1794. _GLTFMaterial._ConvertSpecularGlossinessTexturesToMetallicRoughness = function (diffuseTexture, specularGlossinessTexture, factors, mimeType) {
  1795. if (!(diffuseTexture || specularGlossinessTexture)) {
  1796. return null;
  1797. }
  1798. var scene = diffuseTexture ? diffuseTexture.getScene() : specularGlossinessTexture.getScene();
  1799. if (!scene) {
  1800. BABYLON.Tools.Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Scene from textures is missing!");
  1801. return null;
  1802. }
  1803. var resizedTextures = this._ResizeTexturesToSameDimensions(diffuseTexture, specularGlossinessTexture, scene);
  1804. var diffuseSize = resizedTextures.texture1.getSize();
  1805. var diffuseBuffer;
  1806. var specularGlossinessBuffer;
  1807. var width = diffuseSize.width;
  1808. var height = diffuseSize.height;
  1809. var pixels = (resizedTextures.texture1.readPixels());
  1810. if (pixels instanceof Uint8Array) {
  1811. diffuseBuffer = (resizedTextures.texture1.readPixels());
  1812. }
  1813. else {
  1814. BABYLON.Tools.Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Pixel array buffer type not supported for texture: " + resizedTextures.texture1.name);
  1815. return null;
  1816. }
  1817. pixels = resizedTextures.texture2.readPixels();
  1818. if (pixels instanceof Uint8Array) {
  1819. specularGlossinessBuffer = (resizedTextures.texture2.readPixels());
  1820. }
  1821. else {
  1822. BABYLON.Tools.Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Pixel array buffer type not supported for texture: " + resizedTextures.texture2.name);
  1823. return null;
  1824. }
  1825. var byteLength = specularGlossinessBuffer.byteLength;
  1826. var metallicRoughnessBuffer = new Uint8Array(byteLength);
  1827. var baseColorBuffer = new Uint8Array(byteLength);
  1828. var strideSize = 4;
  1829. var maxBaseColor = BABYLON.Color3.Black();
  1830. var maxMetallic = 0;
  1831. var maxRoughness = 0;
  1832. for (var h = 0; h < height; ++h) {
  1833. for (var w = 0; w < width; ++w) {
  1834. var offset = (width * h + w) * strideSize;
  1835. var diffuseColor = BABYLON.Color3.FromInts(diffuseBuffer[offset], diffuseBuffer[offset + 1], diffuseBuffer[offset + 2]).toLinearSpace().multiply(factors.diffuseColor);
  1836. var specularColor = BABYLON.Color3.FromInts(specularGlossinessBuffer[offset], specularGlossinessBuffer[offset + 1], specularGlossinessBuffer[offset + 2]).toLinearSpace().multiply(factors.specularColor);
  1837. var glossiness = (specularGlossinessBuffer[offset + 3] / 255) * factors.glossiness;
  1838. var specularGlossiness = {
  1839. diffuseColor: diffuseColor,
  1840. specularColor: specularColor,
  1841. glossiness: glossiness
  1842. };
  1843. var metallicRoughness = this._ConvertSpecularGlossinessToMetallicRoughness(specularGlossiness);
  1844. maxBaseColor.r = Math.max(maxBaseColor.r, metallicRoughness.baseColor.r);
  1845. maxBaseColor.g = Math.max(maxBaseColor.g, metallicRoughness.baseColor.g);
  1846. maxBaseColor.b = Math.max(maxBaseColor.b, metallicRoughness.baseColor.b);
  1847. maxMetallic = Math.max(maxMetallic, metallicRoughness.metallic);
  1848. maxRoughness = Math.max(maxRoughness, metallicRoughness.roughness);
  1849. baseColorBuffer[offset] = metallicRoughness.baseColor.r * 255;
  1850. baseColorBuffer[offset + 1] = metallicRoughness.baseColor.g * 255;
  1851. baseColorBuffer[offset + 2] = metallicRoughness.baseColor.b * 255;
  1852. baseColorBuffer[offset + 3] = resizedTextures.texture1.hasAlpha ? diffuseBuffer[offset + 3] : 255;
  1853. metallicRoughnessBuffer[offset] = 0;
  1854. metallicRoughnessBuffer[offset + 1] = metallicRoughness.roughness * 255;
  1855. metallicRoughnessBuffer[offset + 2] = metallicRoughness.metallic * 255;
  1856. metallicRoughnessBuffer[offset + 3] = 255;
  1857. }
  1858. }
  1859. // Retrieves the metallic roughness factors from the maximum texture values.
  1860. var metallicRoughnessFactors = {
  1861. baseColor: maxBaseColor,
  1862. metallic: maxMetallic,
  1863. roughness: maxRoughness
  1864. };
  1865. var writeOutMetallicRoughnessTexture = false;
  1866. var writeOutBaseColorTexture = false;
  1867. for (var h = 0; h < height; ++h) {
  1868. for (var w = 0; w < width; ++w) {
  1869. var destinationOffset = (width * h + w) * strideSize;
  1870. baseColorBuffer[destinationOffset] /= metallicRoughnessFactors.baseColor.r > this._epsilon ? metallicRoughnessFactors.baseColor.r : 1;
  1871. baseColorBuffer[destinationOffset + 1] /= metallicRoughnessFactors.baseColor.g > this._epsilon ? metallicRoughnessFactors.baseColor.g : 1;
  1872. baseColorBuffer[destinationOffset + 2] /= metallicRoughnessFactors.baseColor.b > this._epsilon ? metallicRoughnessFactors.baseColor.b : 1;
  1873. var linearBaseColorPixel = BABYLON.Color3.FromInts(baseColorBuffer[destinationOffset], baseColorBuffer[destinationOffset + 1], baseColorBuffer[destinationOffset + 2]);
  1874. var sRGBBaseColorPixel = linearBaseColorPixel.toGammaSpace();
  1875. baseColorBuffer[destinationOffset] = sRGBBaseColorPixel.r * 255;
  1876. baseColorBuffer[destinationOffset + 1] = sRGBBaseColorPixel.g * 255;
  1877. baseColorBuffer[destinationOffset + 2] = sRGBBaseColorPixel.b * 255;
  1878. if (!this.FuzzyEquals(sRGBBaseColorPixel, BABYLON.Color3.White(), this._epsilon)) {
  1879. writeOutBaseColorTexture = true;
  1880. }
  1881. metallicRoughnessBuffer[destinationOffset + 1] /= metallicRoughnessFactors.roughness > this._epsilon ? metallicRoughnessFactors.roughness : 1;
  1882. metallicRoughnessBuffer[destinationOffset + 2] /= metallicRoughnessFactors.metallic > this._epsilon ? metallicRoughnessFactors.metallic : 1;
  1883. var metallicRoughnessPixel = BABYLON.Color3.FromInts(255, metallicRoughnessBuffer[destinationOffset + 1], metallicRoughnessBuffer[destinationOffset + 2]);
  1884. if (!this.FuzzyEquals(metallicRoughnessPixel, BABYLON.Color3.White(), this._epsilon)) {
  1885. writeOutMetallicRoughnessTexture = true;
  1886. }
  1887. }
  1888. }
  1889. if (writeOutMetallicRoughnessTexture) {
  1890. var metallicRoughnessBase64 = this._CreateBase64FromCanvas(metallicRoughnessBuffer, width, height, mimeType);
  1891. metallicRoughnessFactors.metallicRoughnessTextureBase64 = metallicRoughnessBase64;
  1892. }
  1893. if (writeOutBaseColorTexture) {
  1894. var baseColorBase64 = this._CreateBase64FromCanvas(baseColorBuffer, width, height, mimeType);
  1895. metallicRoughnessFactors.baseColorTextureBase64 = baseColorBase64;
  1896. }
  1897. return metallicRoughnessFactors;
  1898. };
  1899. /**
  1900. * Converts specular glossiness material properties to metallic roughness
  1901. * @param specularGlossiness interface with specular glossiness material properties
  1902. * @returns interface with metallic roughness material properties
  1903. */
  1904. _GLTFMaterial._ConvertSpecularGlossinessToMetallicRoughness = function (specularGlossiness) {
  1905. var diffusePerceivedBrightness = _GLTFMaterial._GetPerceivedBrightness(specularGlossiness.diffuseColor);
  1906. var specularPerceivedBrightness = _GLTFMaterial._GetPerceivedBrightness(specularGlossiness.specularColor);
  1907. var oneMinusSpecularStrength = 1 - _GLTFMaterial._GetMaxComponent(specularGlossiness.specularColor);
  1908. var metallic = _GLTFMaterial._SolveMetallic(diffusePerceivedBrightness, specularPerceivedBrightness, oneMinusSpecularStrength);
  1909. var baseColorFromDiffuse = specularGlossiness.diffuseColor.scale(oneMinusSpecularStrength / (1.0 - this._dielectricSpecular.r) / Math.max(1 - metallic, this._epsilon));
  1910. var baseColorFromSpecular = specularGlossiness.specularColor.subtract(this._dielectricSpecular.scale(1 - metallic)).scale(1 / Math.max(metallic, this._epsilon));
  1911. var baseColor = BABYLON.Color3.Lerp(baseColorFromDiffuse, baseColorFromSpecular, metallic * metallic);
  1912. baseColor = baseColor.clampToRef(0, 1, baseColor);
  1913. var metallicRoughness = {
  1914. baseColor: baseColor,
  1915. metallic: metallic,
  1916. roughness: 1 - specularGlossiness.glossiness
  1917. };
  1918. return metallicRoughness;
  1919. };
  1920. /**
  1921. * Calculates the surface reflectance, independent of lighting conditions
  1922. * @param color Color source to calculate brightness from
  1923. * @returns number representing the perceived brightness, or zero if color is undefined
  1924. */
  1925. _GLTFMaterial._GetPerceivedBrightness = function (color) {
  1926. if (color) {
  1927. return Math.sqrt(0.299 * color.r * color.r + 0.587 * color.g * color.g + 0.114 * color.b * color.b);
  1928. }
  1929. return 0;
  1930. };
  1931. /**
  1932. * Returns the maximum color component value
  1933. * @param color
  1934. * @returns maximum color component value, or zero if color is null or undefined
  1935. */
  1936. _GLTFMaterial._GetMaxComponent = function (color) {
  1937. if (color) {
  1938. return Math.max(color.r, Math.max(color.g, color.b));
  1939. }
  1940. return 0;
  1941. };
  1942. /**
  1943. * Convert a PBRMaterial (Metallic/Roughness) to Metallic Roughness factors
  1944. * @param babylonPBRMaterial BJS PBR Metallic Roughness Material
  1945. * @param mimeType mime type to use for the textures
  1946. * @param images array of glTF image interfaces
  1947. * @param textures array of glTF texture interfaces
  1948. * @param glTFPbrMetallicRoughness glTF PBR Metallic Roughness interface
  1949. * @param imageData map of image file name to data
  1950. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  1951. * @returns glTF PBR Metallic Roughness factors
  1952. */
  1953. _GLTFMaterial._ConvertMetalRoughFactorsToMetallicRoughness = function (babylonPBRMaterial, mimeType, images, textures, samplers, glTFPbrMetallicRoughness, imageData, hasTextureCoords) {
  1954. var metallicRoughness = {
  1955. baseColor: babylonPBRMaterial.albedoColor,
  1956. metallic: babylonPBRMaterial.metallic,
  1957. roughness: babylonPBRMaterial.roughness
  1958. };
  1959. if (hasTextureCoords) {
  1960. if (babylonPBRMaterial.albedoTexture) {
  1961. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.albedoTexture, mimeType, images, textures, samplers, imageData);
  1962. if (glTFTexture) {
  1963. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1964. }
  1965. }
  1966. if (babylonPBRMaterial.metallicTexture) {
  1967. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.metallicTexture, mimeType, images, textures, samplers, imageData);
  1968. if (glTFTexture != null) {
  1969. glTFPbrMetallicRoughness.metallicRoughnessTexture = glTFTexture;
  1970. }
  1971. }
  1972. }
  1973. return metallicRoughness;
  1974. };
  1975. _GLTFMaterial._GetGLTFTextureSampler = function (texture) {
  1976. var sampler = _GLTFMaterial._GetGLTFTextureWrapModesSampler(texture);
  1977. var samplingMode = texture instanceof BABYLON.Texture ? texture.samplingMode : null;
  1978. if (samplingMode != null) {
  1979. switch (samplingMode) {
  1980. case BABYLON.Texture.LINEAR_LINEAR: {
  1981. sampler.magFilter = 9729 /* LINEAR */;
  1982. sampler.minFilter = 9729 /* LINEAR */;
  1983. break;
  1984. }
  1985. case BABYLON.Texture.LINEAR_NEAREST: {
  1986. sampler.magFilter = 9729 /* LINEAR */;
  1987. sampler.minFilter = 9728 /* NEAREST */;
  1988. break;
  1989. }
  1990. case BABYLON.Texture.NEAREST_LINEAR: {
  1991. sampler.magFilter = 9728 /* NEAREST */;
  1992. sampler.minFilter = 9729 /* LINEAR */;
  1993. break;
  1994. }
  1995. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR: {
  1996. sampler.magFilter = 9728 /* NEAREST */;
  1997. sampler.minFilter = 9987 /* LINEAR_MIPMAP_LINEAR */;
  1998. break;
  1999. }
  2000. case BABYLON.Texture.NEAREST_NEAREST: {
  2001. sampler.magFilter = 9728 /* NEAREST */;
  2002. sampler.minFilter = 9728 /* NEAREST */;
  2003. break;
  2004. }
  2005. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST: {
  2006. sampler.magFilter = 9728 /* NEAREST */;
  2007. sampler.minFilter = 9985 /* LINEAR_MIPMAP_NEAREST */;
  2008. break;
  2009. }
  2010. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST: {
  2011. sampler.magFilter = 9729 /* LINEAR */;
  2012. sampler.minFilter = 9984 /* NEAREST_MIPMAP_NEAREST */;
  2013. break;
  2014. }
  2015. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR: {
  2016. sampler.magFilter = 9729 /* LINEAR */;
  2017. sampler.minFilter = 9986 /* NEAREST_MIPMAP_LINEAR */;
  2018. break;
  2019. }
  2020. case BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR: {
  2021. sampler.magFilter = 9728 /* NEAREST */;
  2022. sampler.minFilter = 9986 /* NEAREST_MIPMAP_LINEAR */;
  2023. break;
  2024. }
  2025. case BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR: {
  2026. sampler.magFilter = 9729 /* LINEAR */;
  2027. sampler.minFilter = 9987 /* LINEAR_MIPMAP_LINEAR */;
  2028. break;
  2029. }
  2030. case BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST: {
  2031. sampler.magFilter = 9729 /* LINEAR */;
  2032. sampler.minFilter = 9985 /* LINEAR_MIPMAP_NEAREST */;
  2033. break;
  2034. }
  2035. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST: {
  2036. sampler.magFilter = 9728 /* NEAREST */;
  2037. sampler.minFilter = 9984 /* NEAREST_MIPMAP_NEAREST */;
  2038. break;
  2039. }
  2040. }
  2041. }
  2042. return sampler;
  2043. };
  2044. _GLTFMaterial._GetGLTFTextureWrapMode = function (wrapMode) {
  2045. switch (wrapMode) {
  2046. case BABYLON.Texture.WRAP_ADDRESSMODE: {
  2047. return 10497 /* REPEAT */;
  2048. }
  2049. case BABYLON.Texture.CLAMP_ADDRESSMODE: {
  2050. return 33071 /* CLAMP_TO_EDGE */;
  2051. }
  2052. case BABYLON.Texture.MIRROR_ADDRESSMODE: {
  2053. return 33648 /* MIRRORED_REPEAT */;
  2054. }
  2055. default: {
  2056. BABYLON.Tools.Error("Unsupported Texture Wrap Mode " + wrapMode + "!");
  2057. return 10497 /* REPEAT */;
  2058. }
  2059. }
  2060. };
  2061. _GLTFMaterial._GetGLTFTextureWrapModesSampler = function (texture) {
  2062. var wrapS = _GLTFMaterial._GetGLTFTextureWrapMode(texture instanceof BABYLON.Texture ? texture.wrapU : BABYLON.Texture.WRAP_ADDRESSMODE);
  2063. var wrapT = _GLTFMaterial._GetGLTFTextureWrapMode(texture instanceof BABYLON.Texture ? texture.wrapV : BABYLON.Texture.WRAP_ADDRESSMODE);
  2064. if (wrapS === 10497 /* REPEAT */ && wrapT === 10497 /* REPEAT */) { // default wrapping mode in glTF, so omitting
  2065. return {};
  2066. }
  2067. return { wrapS: wrapS, wrapT: wrapT };
  2068. };
  2069. /**
  2070. * Convert a PBRMaterial (Specular/Glossiness) to Metallic Roughness factors
  2071. * @param babylonPBRMaterial BJS PBR Metallic Roughness Material
  2072. * @param mimeType mime type to use for the textures
  2073. * @param images array of glTF image interfaces
  2074. * @param textures array of glTF texture interfaces
  2075. * @param glTFPbrMetallicRoughness glTF PBR Metallic Roughness interface
  2076. * @param imageData map of image file name to data
  2077. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  2078. * @returns glTF PBR Metallic Roughness factors
  2079. */
  2080. _GLTFMaterial._ConvertSpecGlossFactorsToMetallicRoughness = function (babylonPBRMaterial, mimeType, images, textures, samplers, glTFPbrMetallicRoughness, imageData, hasTextureCoords) {
  2081. var specGloss = {
  2082. diffuseColor: babylonPBRMaterial.albedoColor || BABYLON.Color3.White(),
  2083. specularColor: babylonPBRMaterial.reflectivityColor || BABYLON.Color3.White(),
  2084. glossiness: babylonPBRMaterial.microSurface || 1,
  2085. };
  2086. var samplerIndex = null;
  2087. var sampler = this._GetGLTFTextureSampler(babylonPBRMaterial.albedoTexture);
  2088. if (sampler.magFilter != null && sampler.minFilter != null && sampler.wrapS != null && sampler.wrapT != null) {
  2089. samplers.push(sampler);
  2090. samplerIndex = samplers.length - 1;
  2091. }
  2092. if (babylonPBRMaterial.reflectivityTexture && !babylonPBRMaterial.useMicroSurfaceFromReflectivityMapAlpha) {
  2093. BABYLON.Tools.Error("_ConvertPBRMaterial: Glossiness values not included in the reflectivity texture currently not supported");
  2094. return null;
  2095. }
  2096. var metallicRoughnessFactors = this._ConvertSpecularGlossinessTexturesToMetallicRoughness(babylonPBRMaterial.albedoTexture, babylonPBRMaterial.reflectivityTexture, specGloss, mimeType);
  2097. if (!metallicRoughnessFactors) {
  2098. metallicRoughnessFactors = this._ConvertSpecularGlossinessToMetallicRoughness(specGloss);
  2099. }
  2100. else {
  2101. if (hasTextureCoords) {
  2102. if (metallicRoughnessFactors.baseColorTextureBase64) {
  2103. var glTFBaseColorTexture = _GLTFMaterial._GetTextureInfoFromBase64(metallicRoughnessFactors.baseColorTextureBase64, "bjsBaseColorTexture_" + (textures.length) + ".png", mimeType, images, textures, babylonPBRMaterial.albedoTexture.coordinatesIndex, samplerIndex, imageData);
  2104. if (glTFBaseColorTexture != null) {
  2105. glTFPbrMetallicRoughness.baseColorTexture = glTFBaseColorTexture;
  2106. }
  2107. }
  2108. if (metallicRoughnessFactors.metallicRoughnessTextureBase64) {
  2109. var glTFMRColorTexture = _GLTFMaterial._GetTextureInfoFromBase64(metallicRoughnessFactors.metallicRoughnessTextureBase64, "bjsMetallicRoughnessTexture_" + (textures.length) + ".png", mimeType, images, textures, babylonPBRMaterial.reflectivityTexture.coordinatesIndex, samplerIndex, imageData);
  2110. if (glTFMRColorTexture != null) {
  2111. glTFPbrMetallicRoughness.metallicRoughnessTexture = glTFMRColorTexture;
  2112. }
  2113. }
  2114. }
  2115. }
  2116. return metallicRoughnessFactors;
  2117. };
  2118. /**
  2119. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material
  2120. * @param babylonPBRMaterial BJS PBR Metallic Roughness Material
  2121. * @param mimeType mime type to use for the textures
  2122. * @param images array of glTF image interfaces
  2123. * @param textures array of glTF texture interfaces
  2124. * @param materials array of glTF material interfaces
  2125. * @param imageData map of image file name to data
  2126. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  2127. */
  2128. _GLTFMaterial._ConvertPBRMaterial = function (babylonPBRMaterial, mimeType, images, textures, samplers, materials, imageData, hasTextureCoords) {
  2129. var glTFPbrMetallicRoughness = {};
  2130. var metallicRoughness;
  2131. var glTFMaterial = {
  2132. name: babylonPBRMaterial.name
  2133. };
  2134. var useMetallicRoughness = babylonPBRMaterial.isMetallicWorkflow();
  2135. if (useMetallicRoughness) {
  2136. metallicRoughness = this._ConvertMetalRoughFactorsToMetallicRoughness(babylonPBRMaterial, mimeType, images, textures, samplers, glTFPbrMetallicRoughness, imageData, hasTextureCoords);
  2137. }
  2138. else {
  2139. metallicRoughness = this._ConvertSpecGlossFactorsToMetallicRoughness(babylonPBRMaterial, mimeType, images, textures, samplers, glTFPbrMetallicRoughness, imageData, hasTextureCoords);
  2140. }
  2141. if (metallicRoughness) {
  2142. if (!(this.FuzzyEquals(metallicRoughness.baseColor, BABYLON.Color3.White(), this._epsilon) && babylonPBRMaterial.alpha >= this._epsilon)) {
  2143. glTFPbrMetallicRoughness.baseColorFactor = [
  2144. metallicRoughness.baseColor.r,
  2145. metallicRoughness.baseColor.g,
  2146. metallicRoughness.baseColor.b,
  2147. babylonPBRMaterial.alpha
  2148. ];
  2149. }
  2150. if (metallicRoughness.metallic != null && metallicRoughness.metallic !== 1) {
  2151. glTFPbrMetallicRoughness.metallicFactor = metallicRoughness.metallic;
  2152. }
  2153. if (metallicRoughness.roughness != null && metallicRoughness.roughness !== 1) {
  2154. glTFPbrMetallicRoughness.roughnessFactor = metallicRoughness.roughness;
  2155. }
  2156. if (babylonPBRMaterial.backFaceCulling != null && !babylonPBRMaterial.backFaceCulling) {
  2157. if (!babylonPBRMaterial.twoSidedLighting) {
  2158. BABYLON.Tools.Warn(babylonPBRMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  2159. }
  2160. glTFMaterial.doubleSided = true;
  2161. }
  2162. if (hasTextureCoords) {
  2163. if (babylonPBRMaterial.bumpTexture) {
  2164. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.bumpTexture, mimeType, images, textures, samplers, imageData);
  2165. if (glTFTexture) {
  2166. glTFMaterial.normalTexture = glTFTexture;
  2167. if (babylonPBRMaterial.bumpTexture.level !== 1) {
  2168. glTFMaterial.normalTexture.scale = babylonPBRMaterial.bumpTexture.level;
  2169. }
  2170. }
  2171. }
  2172. if (babylonPBRMaterial.ambientTexture) {
  2173. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.ambientTexture, mimeType, images, textures, samplers, imageData);
  2174. if (glTFTexture) {
  2175. var occlusionTexture = {
  2176. index: glTFTexture.index
  2177. };
  2178. glTFMaterial.occlusionTexture = occlusionTexture;
  2179. if (babylonPBRMaterial.ambientTextureStrength) {
  2180. occlusionTexture.strength = babylonPBRMaterial.ambientTextureStrength;
  2181. }
  2182. }
  2183. }
  2184. if (babylonPBRMaterial.emissiveTexture) {
  2185. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.emissiveTexture, mimeType, images, textures, samplers, imageData);
  2186. if (glTFTexture != null) {
  2187. glTFMaterial.emissiveTexture = glTFTexture;
  2188. }
  2189. }
  2190. }
  2191. if (!this.FuzzyEquals(babylonPBRMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  2192. glTFMaterial.emissiveFactor = babylonPBRMaterial.emissiveColor.asArray();
  2193. }
  2194. if (babylonPBRMaterial.transparencyMode != null) {
  2195. var alphaMode = _GLTFMaterial._GetAlphaMode(babylonPBRMaterial);
  2196. if (alphaMode) {
  2197. if (alphaMode !== "OPAQUE" /* OPAQUE */) { //glTF defaults to opaque
  2198. glTFMaterial.alphaMode = alphaMode;
  2199. if (alphaMode === "MASK" /* MASK */) {
  2200. glTFMaterial.alphaCutoff = babylonPBRMaterial.alphaCutOff;
  2201. }
  2202. }
  2203. }
  2204. }
  2205. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  2206. materials.push(glTFMaterial);
  2207. }
  2208. };
  2209. _GLTFMaterial.GetPixelsFromTexture = function (babylonTexture) {
  2210. var pixels = babylonTexture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT ? babylonTexture.readPixels() : babylonTexture.readPixels();
  2211. return pixels;
  2212. };
  2213. /**
  2214. * Extracts a texture from a Babylon texture into file data and glTF data
  2215. * @param babylonTexture Babylon texture to extract
  2216. * @param mimeType Mime Type of the babylonTexture
  2217. * @param images Array of glTF images
  2218. * @param textures Array of glTF textures
  2219. * @param imageData map of image file name and data
  2220. * @return glTF texture info, or null if the texture format is not supported
  2221. */
  2222. _GLTFMaterial._ExportTexture = function (babylonTexture, mimeType, images, textures, samplers, imageData) {
  2223. var sampler = _GLTFMaterial._GetGLTFTextureSampler(babylonTexture);
  2224. var samplerIndex = null;
  2225. // if a pre-existing sampler with identical parameters exists, then reuse the previous sampler
  2226. var foundSamplerIndex = null;
  2227. for (var i = 0; i < samplers.length; ++i) {
  2228. var s = samplers[i];
  2229. if (s.minFilter === sampler.minFilter && s.magFilter === sampler.magFilter &&
  2230. s.wrapS === sampler.wrapS && s.wrapT === sampler.wrapT) {
  2231. foundSamplerIndex = i;
  2232. break;
  2233. }
  2234. }
  2235. if (foundSamplerIndex == null) {
  2236. samplers.push(sampler);
  2237. samplerIndex = samplers.length - 1;
  2238. }
  2239. else {
  2240. samplerIndex = foundSamplerIndex;
  2241. }
  2242. var textureName = "texture_" + (textures.length - 1).toString();
  2243. var textureData = babylonTexture.getInternalTexture();
  2244. if (textureData != null) {
  2245. textureName = textureData.url || textureName;
  2246. }
  2247. textureName = BABYLON.Tools.GetFilename(textureName);
  2248. var baseFile = textureName.split('.')[0];
  2249. var extension = "";
  2250. if (mimeType === "image/jpeg" /* JPEG */) {
  2251. extension = ".jpg";
  2252. }
  2253. else if (mimeType === "image/png" /* PNG */) {
  2254. extension = ".png";
  2255. }
  2256. else {
  2257. BABYLON.Tools.Error("Unsupported mime type " + mimeType);
  2258. return null;
  2259. }
  2260. textureName = baseFile + extension;
  2261. var pixels = _GLTFMaterial.GetPixelsFromTexture(babylonTexture);
  2262. var size = babylonTexture.getSize();
  2263. var base64Data = this._CreateBase64FromCanvas(pixels, size.width, size.height, mimeType);
  2264. return this._GetTextureInfoFromBase64(base64Data, textureName, mimeType, images, textures, babylonTexture.coordinatesIndex, samplerIndex, imageData);
  2265. };
  2266. /**
  2267. * Builds a texture from base64 string
  2268. * @param base64Texture base64 texture string
  2269. * @param textureName Name to use for the texture
  2270. * @param mimeType image mime type for the texture
  2271. * @param images array of images
  2272. * @param textures array of textures
  2273. * @param imageData map of image data
  2274. * @returns glTF texture info, or null if the texture format is not supported
  2275. */
  2276. _GLTFMaterial._GetTextureInfoFromBase64 = function (base64Texture, textureName, mimeType, images, textures, texCoordIndex, samplerIndex, imageData) {
  2277. var textureInfo = null;
  2278. var glTFTexture = {
  2279. source: images.length,
  2280. name: textureName
  2281. };
  2282. if (samplerIndex != null) {
  2283. glTFTexture.sampler = samplerIndex;
  2284. }
  2285. var binStr = atob(base64Texture.split(',')[1]);
  2286. var arrBuff = new ArrayBuffer(binStr.length);
  2287. var arr = new Uint8Array(arrBuff);
  2288. for (var i = 0, length_1 = binStr.length; i < length_1; ++i) {
  2289. arr[i] = binStr.charCodeAt(i);
  2290. }
  2291. var imageValues = { data: arr, mimeType: mimeType };
  2292. imageData[textureName] = imageValues;
  2293. if (mimeType === "image/jpeg" /* JPEG */ || mimeType === "image/png" /* PNG */) {
  2294. var glTFImage = {
  2295. uri: textureName
  2296. };
  2297. var foundIndex = null;
  2298. for (var i = 0; i < images.length; ++i) {
  2299. if (images[i].uri === textureName) {
  2300. foundIndex = i;
  2301. break;
  2302. }
  2303. }
  2304. if (foundIndex == null) {
  2305. images.push(glTFImage);
  2306. glTFTexture.source = images.length - 1;
  2307. }
  2308. else {
  2309. glTFTexture.source = foundIndex;
  2310. }
  2311. textures.push(glTFTexture);
  2312. textureInfo = {
  2313. index: textures.length - 1
  2314. };
  2315. if (texCoordIndex) {
  2316. textureInfo.texCoord = texCoordIndex;
  2317. }
  2318. }
  2319. return textureInfo;
  2320. };
  2321. /**
  2322. * Represents the dielectric specular values for R, G and B
  2323. */
  2324. _GLTFMaterial._dielectricSpecular = new BABYLON.Color3(0.04, 0.04, 0.04);
  2325. /**
  2326. * Allows the maximum specular power to be defined for material calculations
  2327. */
  2328. _GLTFMaterial._maxSpecularPower = 1024;
  2329. /**
  2330. * Numeric tolerance value
  2331. */
  2332. _GLTFMaterial._epsilon = 1e-6;
  2333. return _GLTFMaterial;
  2334. }());
  2335. GLTF2._GLTFMaterial = _GLTFMaterial;
  2336. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2337. })(BABYLON || (BABYLON = {}));
  2338. //# sourceMappingURL=babylon.glTFMaterial.js.map
  2339. /// <reference path="../../../../dist/preview release/gltf2Interface/babylon.glTF2Interface.d.ts"/>
  2340. var BABYLON;
  2341. (function (BABYLON) {
  2342. var GLTF2;
  2343. (function (GLTF2) {
  2344. /**
  2345. * @hidden
  2346. * Enum for handling in tangent and out tangent.
  2347. */
  2348. var _TangentType;
  2349. (function (_TangentType) {
  2350. /**
  2351. * Specifies that input tangents are used.
  2352. */
  2353. _TangentType[_TangentType["INTANGENT"] = 0] = "INTANGENT";
  2354. /**
  2355. * Specifies that output tangents are used.
  2356. */
  2357. _TangentType[_TangentType["OUTTANGENT"] = 1] = "OUTTANGENT";
  2358. })(_TangentType || (_TangentType = {}));
  2359. /**
  2360. * @hidden
  2361. * Utility class for generating glTF animation data from BabylonJS.
  2362. */
  2363. var _GLTFAnimation = /** @class */ (function () {
  2364. function _GLTFAnimation() {
  2365. }
  2366. /**
  2367. * @ignore
  2368. *
  2369. * Creates glTF channel animation from BabylonJS animation.
  2370. * @param babylonTransformNode - BabylonJS mesh.
  2371. * @param animation - animation.
  2372. * @param animationChannelTargetPath - The target animation channel.
  2373. * @param convertToRightHandedSystem - Specifies if the values should be converted to right-handed.
  2374. * @param useQuaternion - Specifies if quaternions are used.
  2375. * @returns nullable IAnimationData
  2376. */
  2377. _GLTFAnimation._CreateNodeAnimation = function (babylonTransformNode, animation, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion, animationSampleRate) {
  2378. var inputs = [];
  2379. var outputs = [];
  2380. var keyFrames = animation.getKeys();
  2381. var minMaxKeyFrames = _GLTFAnimation.calculateMinMaxKeyFrames(keyFrames);
  2382. var interpolationOrBake = _GLTFAnimation._DeduceInterpolation(keyFrames, animationChannelTargetPath, useQuaternion);
  2383. var frameDelta = minMaxKeyFrames.max - minMaxKeyFrames.min;
  2384. var interpolation = interpolationOrBake.interpolationType;
  2385. var shouldBakeAnimation = interpolationOrBake.shouldBakeAnimation;
  2386. if (shouldBakeAnimation) {
  2387. _GLTFAnimation._CreateBakedAnimation(babylonTransformNode, animation, animationChannelTargetPath, minMaxKeyFrames.min, minMaxKeyFrames.max, animation.framePerSecond, animationSampleRate, inputs, outputs, minMaxKeyFrames, convertToRightHandedSystem, useQuaternion);
  2388. }
  2389. else {
  2390. if (interpolation === "LINEAR" /* LINEAR */ || interpolation === "STEP" /* STEP */) {
  2391. _GLTFAnimation._CreateLinearOrStepAnimation(babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion);
  2392. }
  2393. else if (interpolation === "CUBICSPLINE" /* CUBICSPLINE */) {
  2394. _GLTFAnimation._CreateCubicSplineAnimation(babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion);
  2395. }
  2396. else {
  2397. _GLTFAnimation._CreateBakedAnimation(babylonTransformNode, animation, animationChannelTargetPath, minMaxKeyFrames.min, minMaxKeyFrames.max, animation.framePerSecond, animationSampleRate, inputs, outputs, minMaxKeyFrames, convertToRightHandedSystem, useQuaternion);
  2398. }
  2399. }
  2400. if (inputs.length && outputs.length) {
  2401. var result = {
  2402. inputs: inputs,
  2403. outputs: outputs,
  2404. samplerInterpolation: interpolation,
  2405. inputsMin: shouldBakeAnimation ? minMaxKeyFrames.min : BABYLON.Tools.FloatRound(minMaxKeyFrames.min / animation.framePerSecond),
  2406. inputsMax: shouldBakeAnimation ? minMaxKeyFrames.max : BABYLON.Tools.FloatRound(minMaxKeyFrames.max / animation.framePerSecond)
  2407. };
  2408. return result;
  2409. }
  2410. return null;
  2411. };
  2412. _GLTFAnimation._DeduceAnimationInfo = function (animation) {
  2413. var animationChannelTargetPath = null;
  2414. var dataAccessorType = "VEC3" /* VEC3 */;
  2415. var useQuaternion = false;
  2416. var property = animation.targetProperty.split('.');
  2417. switch (property[0]) {
  2418. case 'scaling': {
  2419. animationChannelTargetPath = "scale" /* SCALE */;
  2420. break;
  2421. }
  2422. case 'position': {
  2423. animationChannelTargetPath = "translation" /* TRANSLATION */;
  2424. break;
  2425. }
  2426. case 'rotation': {
  2427. dataAccessorType = "VEC4" /* VEC4 */;
  2428. animationChannelTargetPath = "rotation" /* ROTATION */;
  2429. break;
  2430. }
  2431. case 'rotationQuaternion': {
  2432. dataAccessorType = "VEC4" /* VEC4 */;
  2433. useQuaternion = true;
  2434. animationChannelTargetPath = "rotation" /* ROTATION */;
  2435. break;
  2436. }
  2437. default: {
  2438. BABYLON.Tools.Error("Unsupported animatable property " + property[0]);
  2439. }
  2440. }
  2441. if (animationChannelTargetPath) {
  2442. return { animationChannelTargetPath: animationChannelTargetPath, dataAccessorType: dataAccessorType, useQuaternion: useQuaternion };
  2443. }
  2444. else {
  2445. BABYLON.Tools.Error('animation channel target path and data accessor type could be deduced');
  2446. }
  2447. return null;
  2448. };
  2449. /**
  2450. * @ignore
  2451. * Create node animations from the transform node animations
  2452. * @param babylonTransformNode
  2453. * @param runtimeGLTFAnimation
  2454. * @param idleGLTFAnimations
  2455. * @param nodeMap
  2456. * @param nodes
  2457. * @param binaryWriter
  2458. * @param bufferViews
  2459. * @param accessors
  2460. * @param convertToRightHandedSystem
  2461. */
  2462. _GLTFAnimation._CreateNodeAnimationFromTransformNodeAnimations = function (babylonTransformNode, runtimeGLTFAnimation, idleGLTFAnimations, nodeMap, nodes, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationSampleRate) {
  2463. var glTFAnimation;
  2464. if (babylonTransformNode.animations) {
  2465. for (var _i = 0, _a = babylonTransformNode.animations; _i < _a.length; _i++) {
  2466. var animation = _a[_i];
  2467. var animationInfo = _GLTFAnimation._DeduceAnimationInfo(animation);
  2468. if (animationInfo) {
  2469. glTFAnimation = {
  2470. name: animation.name,
  2471. samplers: [],
  2472. channels: []
  2473. };
  2474. _GLTFAnimation.AddAnimation("" + animation.name, animation.hasRunningRuntimeAnimations ? runtimeGLTFAnimation : glTFAnimation, babylonTransformNode, animation, animationInfo.dataAccessorType, animationInfo.animationChannelTargetPath, nodeMap, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationInfo.useQuaternion, animationSampleRate);
  2475. if (glTFAnimation.samplers.length && glTFAnimation.channels.length) {
  2476. idleGLTFAnimations.push(glTFAnimation);
  2477. }
  2478. }
  2479. }
  2480. ;
  2481. }
  2482. };
  2483. /**
  2484. * @ignore
  2485. * Create node animations from the animation groups
  2486. * @param babylonScene
  2487. * @param glTFAnimations
  2488. * @param nodeMap
  2489. * @param nodes
  2490. * @param binaryWriter
  2491. * @param bufferViews
  2492. * @param accessors
  2493. * @param convertToRightHandedSystem
  2494. */
  2495. _GLTFAnimation._CreateNodeAnimationFromAnimationGroups = function (babylonScene, glTFAnimations, nodeMap, nodes, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationSampleRate) {
  2496. var glTFAnimation;
  2497. if (babylonScene.animationGroups) {
  2498. var animationGroups = babylonScene.animationGroups;
  2499. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  2500. var animationGroup = animationGroups_1[_i];
  2501. glTFAnimation = {
  2502. name: animationGroup.name,
  2503. channels: [],
  2504. samplers: []
  2505. };
  2506. for (var _a = 0, _b = animationGroup.targetedAnimations; _a < _b.length; _a++) {
  2507. var targetAnimation = _b[_a];
  2508. var target = targetAnimation.target;
  2509. var animation = targetAnimation.animation;
  2510. if (target instanceof BABYLON.Mesh || target.length === 1 && target[0] instanceof BABYLON.Mesh) { // TODO: Update to support bones
  2511. var animationInfo = _GLTFAnimation._DeduceAnimationInfo(targetAnimation.animation);
  2512. if (animationInfo) {
  2513. var babylonMesh = target instanceof BABYLON.Mesh ? target : target[0];
  2514. _GLTFAnimation.AddAnimation("" + animation.name, glTFAnimation, babylonMesh, animation, animationInfo.dataAccessorType, animationInfo.animationChannelTargetPath, nodeMap, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationInfo.useQuaternion, animationSampleRate);
  2515. }
  2516. }
  2517. }
  2518. ;
  2519. if (glTFAnimation.channels.length && glTFAnimation.samplers.length) {
  2520. glTFAnimations.push(glTFAnimation);
  2521. }
  2522. }
  2523. ;
  2524. }
  2525. };
  2526. _GLTFAnimation.AddAnimation = function (name, glTFAnimation, babylonTransformNode, animation, dataAccessorType, animationChannelTargetPath, nodeMap, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, useQuaternion, animationSampleRate) {
  2527. var animationData = _GLTFAnimation._CreateNodeAnimation(babylonTransformNode, animation, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion, animationSampleRate);
  2528. var bufferView;
  2529. var accessor;
  2530. var keyframeAccessorIndex;
  2531. var dataAccessorIndex;
  2532. var outputLength;
  2533. var animationSampler;
  2534. var animationChannel;
  2535. if (animationData) {
  2536. var nodeIndex = nodeMap[babylonTransformNode.uniqueId];
  2537. // Creates buffer view and accessor for key frames.
  2538. var byteLength = animationData.inputs.length * 4;
  2539. bufferView = GLTF2._GLTFUtilities.CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, undefined, name + " keyframe data view");
  2540. bufferViews.push(bufferView);
  2541. animationData.inputs.forEach(function (input) {
  2542. binaryWriter.setFloat32(input);
  2543. });
  2544. accessor = GLTF2._GLTFUtilities.CreateAccessor(bufferViews.length - 1, name + " keyframes", "SCALAR" /* SCALAR */, 5126 /* FLOAT */, animationData.inputs.length, null, [animationData.inputsMin], [animationData.inputsMax]);
  2545. accessors.push(accessor);
  2546. keyframeAccessorIndex = accessors.length - 1;
  2547. // create bufferview and accessor for keyed values.
  2548. outputLength = animationData.outputs.length;
  2549. byteLength = dataAccessorType === "VEC3" /* VEC3 */ ? animationData.outputs.length * 12 : animationData.outputs.length * 16;
  2550. // check for in and out tangents
  2551. bufferView = GLTF2._GLTFUtilities.CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, undefined, name + " data view");
  2552. bufferViews.push(bufferView);
  2553. animationData.outputs.forEach(function (output) {
  2554. output.forEach(function (entry) {
  2555. binaryWriter.setFloat32(entry);
  2556. });
  2557. });
  2558. accessor = GLTF2._GLTFUtilities.CreateAccessor(bufferViews.length - 1, name + " data", dataAccessorType, 5126 /* FLOAT */, outputLength, null, null, null);
  2559. accessors.push(accessor);
  2560. dataAccessorIndex = accessors.length - 1;
  2561. // create sampler
  2562. animationSampler = {
  2563. interpolation: animationData.samplerInterpolation,
  2564. input: keyframeAccessorIndex,
  2565. output: dataAccessorIndex
  2566. };
  2567. glTFAnimation.samplers.push(animationSampler);
  2568. // create channel
  2569. animationChannel = {
  2570. sampler: glTFAnimation.samplers.length - 1,
  2571. target: {
  2572. node: nodeIndex,
  2573. path: animationChannelTargetPath
  2574. }
  2575. };
  2576. glTFAnimation.channels.push(animationChannel);
  2577. }
  2578. };
  2579. /**
  2580. * Create a baked animation
  2581. * @param babylonTransformNode BabylonJS mesh
  2582. * @param animation BabylonJS animation corresponding to the BabylonJS mesh
  2583. * @param animationChannelTargetPath animation target channel
  2584. * @param minFrame minimum animation frame
  2585. * @param maxFrame maximum animation frame
  2586. * @param fps frames per second of the animation
  2587. * @param inputs input key frames of the animation
  2588. * @param outputs output key frame data of the animation
  2589. * @param convertToRightHandedSystem converts the values to right-handed
  2590. * @param useQuaternion specifies if quaternions should be used
  2591. */
  2592. _GLTFAnimation._CreateBakedAnimation = function (babylonTransformNode, animation, animationChannelTargetPath, minFrame, maxFrame, fps, sampleRate, inputs, outputs, minMaxFrames, convertToRightHandedSystem, useQuaternion) {
  2593. var value;
  2594. var quaternionCache = BABYLON.Quaternion.Identity();
  2595. var previousTime = null;
  2596. var time;
  2597. var maxUsedFrame = null;
  2598. var currKeyFrame = null;
  2599. var nextKeyFrame = null;
  2600. var prevKeyFrame = null;
  2601. var endFrame = null;
  2602. minMaxFrames.min = BABYLON.Tools.FloatRound(minFrame / fps);
  2603. var keyFrames = animation.getKeys();
  2604. for (var i = 0, length_1 = keyFrames.length; i < length_1; ++i) {
  2605. endFrame = null;
  2606. currKeyFrame = keyFrames[i];
  2607. if (i + 1 < length_1) {
  2608. nextKeyFrame = keyFrames[i + 1];
  2609. if (currKeyFrame.value.equals(nextKeyFrame.value)) {
  2610. if (i === 0) { // set the first frame to itself
  2611. endFrame = currKeyFrame.frame;
  2612. }
  2613. else {
  2614. continue;
  2615. }
  2616. }
  2617. else {
  2618. endFrame = nextKeyFrame.frame;
  2619. }
  2620. }
  2621. else {
  2622. // at the last key frame
  2623. prevKeyFrame = keyFrames[i - 1];
  2624. if (currKeyFrame.value.equals(prevKeyFrame.value)) {
  2625. continue;
  2626. }
  2627. else {
  2628. endFrame = maxFrame;
  2629. }
  2630. }
  2631. if (endFrame) {
  2632. for (var f = currKeyFrame.frame; f <= endFrame; f += sampleRate) {
  2633. time = BABYLON.Tools.FloatRound(f / fps);
  2634. if (time === previousTime) {
  2635. continue;
  2636. }
  2637. previousTime = time;
  2638. maxUsedFrame = time;
  2639. value = animation._interpolate(f, 0, undefined, animation.loopMode);
  2640. _GLTFAnimation._SetInterpolatedValue(babylonTransformNode, value, time, animation, animationChannelTargetPath, quaternionCache, inputs, outputs, convertToRightHandedSystem, useQuaternion);
  2641. }
  2642. }
  2643. }
  2644. if (maxUsedFrame) {
  2645. minMaxFrames.max = maxUsedFrame;
  2646. }
  2647. };
  2648. _GLTFAnimation._ConvertFactorToVector3OrQuaternion = function (factor, babylonTransformNode, animation, animationType, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion) {
  2649. var property;
  2650. var componentName;
  2651. var value = null;
  2652. var basePositionRotationOrScale = _GLTFAnimation._GetBasePositionRotationOrScale(babylonTransformNode, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion);
  2653. if (animationType === BABYLON.Animation.ANIMATIONTYPE_FLOAT) { // handles single component x, y, z or w component animation by using a base property and animating over a component.
  2654. property = animation.targetProperty.split('.');
  2655. componentName = property ? property[1] : ''; // x, y, or z component
  2656. value = useQuaternion ? BABYLON.Quaternion.FromArray(basePositionRotationOrScale).normalize() : BABYLON.Vector3.FromArray(basePositionRotationOrScale);
  2657. switch (componentName) {
  2658. case 'x': {
  2659. value[componentName] = (convertToRightHandedSystem && useQuaternion && (animationChannelTargetPath !== "scale" /* SCALE */)) ? -factor : factor;
  2660. break;
  2661. }
  2662. case 'y': {
  2663. value[componentName] = (convertToRightHandedSystem && useQuaternion && (animationChannelTargetPath !== "scale" /* SCALE */)) ? -factor : factor;
  2664. break;
  2665. }
  2666. case 'z': {
  2667. value[componentName] = (convertToRightHandedSystem && !useQuaternion && (animationChannelTargetPath !== "scale" /* SCALE */)) ? -factor : factor;
  2668. break;
  2669. }
  2670. case 'w': {
  2671. value.w = factor;
  2672. break;
  2673. }
  2674. default: {
  2675. BABYLON.Tools.Error("glTFAnimation: Unsupported component type \"" + componentName + "\" for scale animation!");
  2676. }
  2677. }
  2678. }
  2679. return value;
  2680. };
  2681. _GLTFAnimation._SetInterpolatedValue = function (babylonTransformNode, value, time, animation, animationChannelTargetPath, quaternionCache, inputs, outputs, convertToRightHandedSystem, useQuaternion) {
  2682. var animationType = animation.dataType;
  2683. var cacheValue;
  2684. inputs.push(time);
  2685. if (typeof value === "number") {
  2686. value = this._ConvertFactorToVector3OrQuaternion(value, babylonTransformNode, animation, animationType, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion);
  2687. }
  2688. if (value) {
  2689. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  2690. if (useQuaternion) {
  2691. quaternionCache = value;
  2692. }
  2693. else {
  2694. cacheValue = value;
  2695. BABYLON.Quaternion.RotationYawPitchRollToRef(cacheValue.y, cacheValue.x, cacheValue.z, quaternionCache);
  2696. }
  2697. if (convertToRightHandedSystem) {
  2698. GLTF2._GLTFUtilities.GetRightHandedQuaternionFromRef(quaternionCache);
  2699. if (!babylonTransformNode.parent) {
  2700. quaternionCache = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(quaternionCache);
  2701. }
  2702. }
  2703. outputs.push(quaternionCache.asArray());
  2704. }
  2705. else {
  2706. cacheValue = value;
  2707. if (convertToRightHandedSystem && (animationChannelTargetPath !== "scale" /* SCALE */)) {
  2708. GLTF2._GLTFUtilities.GetRightHandedPositionVector3FromRef(cacheValue);
  2709. if (!babylonTransformNode.parent) {
  2710. cacheValue.x *= -1;
  2711. cacheValue.z *= -1;
  2712. }
  2713. }
  2714. outputs.push(cacheValue.asArray());
  2715. }
  2716. }
  2717. };
  2718. /**
  2719. * Creates linear animation from the animation key frames
  2720. * @param babylonTransformNode BabylonJS mesh
  2721. * @param animation BabylonJS animation
  2722. * @param animationChannelTargetPath The target animation channel
  2723. * @param frameDelta The difference between the last and first frame of the animation
  2724. * @param inputs Array to store the key frame times
  2725. * @param outputs Array to store the key frame data
  2726. * @param convertToRightHandedSystem Specifies if the position data should be converted to right handed
  2727. * @param useQuaternion Specifies if quaternions are used in the animation
  2728. */
  2729. _GLTFAnimation._CreateLinearOrStepAnimation = function (babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion) {
  2730. for (var _i = 0, _a = animation.getKeys(); _i < _a.length; _i++) {
  2731. var keyFrame = _a[_i];
  2732. inputs.push(keyFrame.frame / animation.framePerSecond); // keyframes in seconds.
  2733. _GLTFAnimation._AddKeyframeValue(keyFrame, animation, outputs, animationChannelTargetPath, babylonTransformNode, convertToRightHandedSystem, useQuaternion);
  2734. }
  2735. ;
  2736. };
  2737. /**
  2738. * Creates cubic spline animation from the animation key frames
  2739. * @param babylonTransformNode BabylonJS mesh
  2740. * @param animation BabylonJS animation
  2741. * @param animationChannelTargetPath The target animation channel
  2742. * @param frameDelta The difference between the last and first frame of the animation
  2743. * @param inputs Array to store the key frame times
  2744. * @param outputs Array to store the key frame data
  2745. * @param convertToRightHandedSystem Specifies if the position data should be converted to right handed
  2746. * @param useQuaternion Specifies if quaternions are used in the animation
  2747. */
  2748. _GLTFAnimation._CreateCubicSplineAnimation = function (babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion) {
  2749. animation.getKeys().forEach(function (keyFrame) {
  2750. inputs.push(keyFrame.frame / animation.framePerSecond); // keyframes in seconds.
  2751. _GLTFAnimation.AddSplineTangent(babylonTransformNode, _TangentType.INTANGENT, outputs, animationChannelTargetPath, "CUBICSPLINE" /* CUBICSPLINE */, keyFrame, frameDelta, useQuaternion, convertToRightHandedSystem);
  2752. _GLTFAnimation._AddKeyframeValue(keyFrame, animation, outputs, animationChannelTargetPath, babylonTransformNode, convertToRightHandedSystem, useQuaternion);
  2753. _GLTFAnimation.AddSplineTangent(babylonTransformNode, _TangentType.OUTTANGENT, outputs, animationChannelTargetPath, "CUBICSPLINE" /* CUBICSPLINE */, keyFrame, frameDelta, useQuaternion, convertToRightHandedSystem);
  2754. });
  2755. };
  2756. _GLTFAnimation._GetBasePositionRotationOrScale = function (babylonTransformNode, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion) {
  2757. var basePositionRotationOrScale;
  2758. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  2759. if (useQuaternion) {
  2760. if (babylonTransformNode.rotationQuaternion) {
  2761. basePositionRotationOrScale = babylonTransformNode.rotationQuaternion.asArray();
  2762. if (convertToRightHandedSystem) {
  2763. GLTF2._GLTFUtilities.GetRightHandedQuaternionArrayFromRef(basePositionRotationOrScale);
  2764. if (!babylonTransformNode.parent) {
  2765. basePositionRotationOrScale = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(BABYLON.Quaternion.FromArray(basePositionRotationOrScale)).asArray();
  2766. }
  2767. }
  2768. }
  2769. else {
  2770. basePositionRotationOrScale = BABYLON.Quaternion.Identity().asArray();
  2771. }
  2772. }
  2773. else {
  2774. basePositionRotationOrScale = babylonTransformNode.rotation.asArray();
  2775. GLTF2._GLTFUtilities.GetRightHandedNormalArray3FromRef(basePositionRotationOrScale);
  2776. }
  2777. }
  2778. else if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  2779. basePositionRotationOrScale = babylonTransformNode.position.asArray();
  2780. if (convertToRightHandedSystem) {
  2781. GLTF2._GLTFUtilities.GetRightHandedPositionArray3FromRef(basePositionRotationOrScale);
  2782. }
  2783. }
  2784. else { // scale
  2785. basePositionRotationOrScale = babylonTransformNode.scaling.asArray();
  2786. }
  2787. return basePositionRotationOrScale;
  2788. };
  2789. /**
  2790. * Adds a key frame value
  2791. * @param keyFrame
  2792. * @param animation
  2793. * @param outputs
  2794. * @param animationChannelTargetPath
  2795. * @param basePositionRotationOrScale
  2796. * @param convertToRightHandedSystem
  2797. * @param useQuaternion
  2798. */
  2799. _GLTFAnimation._AddKeyframeValue = function (keyFrame, animation, outputs, animationChannelTargetPath, babylonTransformNode, convertToRightHandedSystem, useQuaternion) {
  2800. var value;
  2801. var newPositionRotationOrScale;
  2802. var animationType = animation.dataType;
  2803. if (animationType === BABYLON.Animation.ANIMATIONTYPE_VECTOR3) {
  2804. value = keyFrame.value.asArray();
  2805. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  2806. var array = BABYLON.Vector3.FromArray(value);
  2807. var rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(array.y, array.x, array.z);
  2808. if (convertToRightHandedSystem) {
  2809. GLTF2._GLTFUtilities.GetRightHandedQuaternionFromRef(rotationQuaternion);
  2810. if (!babylonTransformNode.parent) {
  2811. rotationQuaternion = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(rotationQuaternion);
  2812. }
  2813. }
  2814. value = rotationQuaternion.asArray();
  2815. }
  2816. else if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  2817. if (convertToRightHandedSystem) {
  2818. GLTF2._GLTFUtilities.GetRightHandedNormalArray3FromRef(value);
  2819. if (!babylonTransformNode.parent) {
  2820. value[0] *= -1;
  2821. value[2] *= -1;
  2822. }
  2823. }
  2824. }
  2825. outputs.push(value); // scale vector.
  2826. }
  2827. else if (animationType === BABYLON.Animation.ANIMATIONTYPE_FLOAT) { // handles single component x, y, z or w component animation by using a base property and animating over a component.
  2828. newPositionRotationOrScale = this._ConvertFactorToVector3OrQuaternion(keyFrame.value, babylonTransformNode, animation, animationType, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion);
  2829. if (newPositionRotationOrScale) {
  2830. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  2831. var posRotScale = useQuaternion ? newPositionRotationOrScale : BABYLON.Quaternion.RotationYawPitchRoll(newPositionRotationOrScale.y, newPositionRotationOrScale.x, newPositionRotationOrScale.z).normalize();
  2832. if (convertToRightHandedSystem) {
  2833. GLTF2._GLTFUtilities.GetRightHandedQuaternionFromRef(posRotScale);
  2834. if (!babylonTransformNode.parent) {
  2835. posRotScale = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(posRotScale);
  2836. }
  2837. }
  2838. outputs.push(posRotScale.asArray());
  2839. }
  2840. else if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  2841. if (convertToRightHandedSystem) {
  2842. GLTF2._GLTFUtilities.GetRightHandedNormalVector3FromRef(newPositionRotationOrScale);
  2843. if (!babylonTransformNode.parent) {
  2844. newPositionRotationOrScale.x *= -1;
  2845. newPositionRotationOrScale.z *= -1;
  2846. }
  2847. }
  2848. }
  2849. outputs.push(newPositionRotationOrScale.asArray());
  2850. }
  2851. }
  2852. else if (animationType === BABYLON.Animation.ANIMATIONTYPE_QUATERNION) {
  2853. value = keyFrame.value.normalize().asArray();
  2854. if (convertToRightHandedSystem) {
  2855. GLTF2._GLTFUtilities.GetRightHandedQuaternionArrayFromRef(value);
  2856. if (!babylonTransformNode.parent) {
  2857. value = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(BABYLON.Quaternion.FromArray(value)).asArray();
  2858. }
  2859. }
  2860. outputs.push(value);
  2861. }
  2862. else {
  2863. BABYLON.Tools.Error('glTFAnimation: Unsupported key frame values for animation!');
  2864. }
  2865. };
  2866. /**
  2867. * Determine the interpolation based on the key frames
  2868. * @param keyFrames
  2869. * @param animationChannelTargetPath
  2870. * @param useQuaternion
  2871. */
  2872. _GLTFAnimation._DeduceInterpolation = function (keyFrames, animationChannelTargetPath, useQuaternion) {
  2873. var interpolationType;
  2874. var shouldBakeAnimation = false;
  2875. var key;
  2876. if (animationChannelTargetPath === "rotation" /* ROTATION */ && !useQuaternion) {
  2877. return { interpolationType: "LINEAR" /* LINEAR */, shouldBakeAnimation: true };
  2878. }
  2879. for (var i = 0, length_2 = keyFrames.length; i < length_2; ++i) {
  2880. key = keyFrames[i];
  2881. if (key.inTangent || key.outTangent) {
  2882. if (interpolationType) {
  2883. if (interpolationType !== "CUBICSPLINE" /* CUBICSPLINE */) {
  2884. interpolationType = "LINEAR" /* LINEAR */;
  2885. shouldBakeAnimation = true;
  2886. break;
  2887. }
  2888. }
  2889. else {
  2890. interpolationType = "CUBICSPLINE" /* CUBICSPLINE */;
  2891. }
  2892. }
  2893. else {
  2894. if (interpolationType) {
  2895. if (interpolationType === "CUBICSPLINE" /* CUBICSPLINE */ ||
  2896. (key.interpolation && (key.interpolation === BABYLON.AnimationKeyInterpolation.STEP) && interpolationType !== "STEP" /* STEP */)) {
  2897. interpolationType = "LINEAR" /* LINEAR */;
  2898. shouldBakeAnimation = true;
  2899. break;
  2900. }
  2901. }
  2902. else {
  2903. if (key.interpolation && (key.interpolation === BABYLON.AnimationKeyInterpolation.STEP)) {
  2904. interpolationType = "STEP" /* STEP */;
  2905. }
  2906. else {
  2907. interpolationType = "LINEAR" /* LINEAR */;
  2908. }
  2909. }
  2910. }
  2911. }
  2912. if (!interpolationType) {
  2913. interpolationType = "LINEAR" /* LINEAR */;
  2914. }
  2915. return { interpolationType: interpolationType, shouldBakeAnimation: shouldBakeAnimation };
  2916. };
  2917. /**
  2918. * Adds an input tangent or output tangent to the output data
  2919. * If an input tangent or output tangent is missing, it uses the zero vector or zero quaternion
  2920. * @param tangentType Specifies which type of tangent to handle (inTangent or outTangent)
  2921. * @param outputs The animation data by keyframe
  2922. * @param animationChannelTargetPath The target animation channel
  2923. * @param interpolation The interpolation type
  2924. * @param keyFrame The key frame with the animation data
  2925. * @param frameDelta Time difference between two frames used to scale the tangent by the frame delta
  2926. * @param useQuaternion Specifies if quaternions are used
  2927. * @param convertToRightHandedSystem Specifies if the values should be converted to right-handed
  2928. */
  2929. _GLTFAnimation.AddSplineTangent = function (babylonTransformNode, tangentType, outputs, animationChannelTargetPath, interpolation, keyFrame, frameDelta, useQuaternion, convertToRightHandedSystem) {
  2930. var tangent;
  2931. var tangentValue = tangentType === _TangentType.INTANGENT ? keyFrame.inTangent : keyFrame.outTangent;
  2932. if (interpolation === "CUBICSPLINE" /* CUBICSPLINE */) {
  2933. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  2934. if (tangentValue) {
  2935. if (useQuaternion) {
  2936. tangent = tangentValue.scale(frameDelta).asArray();
  2937. }
  2938. else {
  2939. var array = tangentValue.scale(frameDelta);
  2940. tangent = BABYLON.Quaternion.RotationYawPitchRoll(array.y, array.x, array.z).asArray();
  2941. }
  2942. if (convertToRightHandedSystem) {
  2943. GLTF2._GLTFUtilities.GetRightHandedQuaternionArrayFromRef(tangent);
  2944. if (!babylonTransformNode.parent) {
  2945. tangent = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(BABYLON.Quaternion.FromArray(tangent)).asArray();
  2946. }
  2947. }
  2948. }
  2949. else {
  2950. tangent = [0, 0, 0, 0];
  2951. }
  2952. }
  2953. else {
  2954. if (tangentValue) {
  2955. tangent = tangentValue.scale(frameDelta).asArray();
  2956. if (convertToRightHandedSystem) {
  2957. if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  2958. GLTF2._GLTFUtilities.GetRightHandedPositionArray3FromRef(tangent);
  2959. if (!babylonTransformNode.parent) {
  2960. tangent[0] *= -1; // x
  2961. tangent[2] *= -1; // z
  2962. }
  2963. }
  2964. }
  2965. }
  2966. else {
  2967. tangent = [0, 0, 0];
  2968. }
  2969. }
  2970. outputs.push(tangent);
  2971. }
  2972. };
  2973. /**
  2974. * Get the minimum and maximum key frames' frame values
  2975. * @param keyFrames animation key frames
  2976. * @returns the minimum and maximum key frame value
  2977. */
  2978. _GLTFAnimation.calculateMinMaxKeyFrames = function (keyFrames) {
  2979. var min = Infinity;
  2980. var max = -Infinity;
  2981. keyFrames.forEach(function (keyFrame) {
  2982. min = Math.min(min, keyFrame.frame);
  2983. max = Math.max(max, keyFrame.frame);
  2984. });
  2985. return { min: min, max: max };
  2986. };
  2987. return _GLTFAnimation;
  2988. }());
  2989. GLTF2._GLTFAnimation = _GLTFAnimation;
  2990. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2991. })(BABYLON || (BABYLON = {}));
  2992. //# sourceMappingURL=babylon.glTFAnimation.js.map
  2993. /// <reference path="../../../../dist/preview release/gltf2Interface/babylon.glTF2Interface.d.ts"/>
  2994. var BABYLON;
  2995. (function (BABYLON) {
  2996. var GLTF2;
  2997. (function (GLTF2) {
  2998. /**
  2999. * @hidden
  3000. */
  3001. var _GLTFUtilities = /** @class */ (function () {
  3002. function _GLTFUtilities() {
  3003. }
  3004. /**
  3005. * Creates a buffer view based on the supplied arguments
  3006. * @param bufferIndex index value of the specified buffer
  3007. * @param byteOffset byte offset value
  3008. * @param byteLength byte length of the bufferView
  3009. * @param byteStride byte distance between conequential elements
  3010. * @param name name of the buffer view
  3011. * @returns bufferView for glTF
  3012. */
  3013. _GLTFUtilities.CreateBufferView = function (bufferIndex, byteOffset, byteLength, byteStride, name) {
  3014. var bufferview = { buffer: bufferIndex, byteLength: byteLength };
  3015. if (byteOffset) {
  3016. bufferview.byteOffset = byteOffset;
  3017. }
  3018. if (name) {
  3019. bufferview.name = name;
  3020. }
  3021. if (byteStride) {
  3022. bufferview.byteStride = byteStride;
  3023. }
  3024. return bufferview;
  3025. };
  3026. /**
  3027. * Creates an accessor based on the supplied arguments
  3028. * @param bufferviewIndex The index of the bufferview referenced by this accessor
  3029. * @param name The name of the accessor
  3030. * @param type The type of the accessor
  3031. * @param componentType The datatype of components in the attribute
  3032. * @param count The number of attributes referenced by this accessor
  3033. * @param byteOffset The offset relative to the start of the bufferView in bytes
  3034. * @param min Minimum value of each component in this attribute
  3035. * @param max Maximum value of each component in this attribute
  3036. * @returns accessor for glTF
  3037. */
  3038. _GLTFUtilities.CreateAccessor = function (bufferviewIndex, name, type, componentType, count, byteOffset, min, max) {
  3039. var accessor = { name: name, bufferView: bufferviewIndex, componentType: componentType, count: count, type: type };
  3040. if (min != null) {
  3041. accessor.min = min;
  3042. }
  3043. if (max != null) {
  3044. accessor.max = max;
  3045. }
  3046. if (byteOffset != null) {
  3047. accessor.byteOffset = byteOffset;
  3048. }
  3049. return accessor;
  3050. };
  3051. /**
  3052. * Calculates the minimum and maximum values of an array of position floats
  3053. * @param positions Positions array of a mesh
  3054. * @param vertexStart Starting vertex offset to calculate min and max values
  3055. * @param vertexCount Number of vertices to check for min and max values
  3056. * @returns min number array and max number array
  3057. */
  3058. _GLTFUtilities.CalculateMinMaxPositions = function (positions, vertexStart, vertexCount, convertToRightHandedSystem) {
  3059. var min = [Infinity, Infinity, Infinity];
  3060. var max = [-Infinity, -Infinity, -Infinity];
  3061. var positionStrideSize = 3;
  3062. var indexOffset;
  3063. var position;
  3064. var vector;
  3065. if (vertexCount) {
  3066. for (var i = vertexStart, length_1 = vertexStart + vertexCount; i < length_1; ++i) {
  3067. indexOffset = positionStrideSize * i;
  3068. position = BABYLON.Vector3.FromArray(positions, indexOffset);
  3069. if (convertToRightHandedSystem) {
  3070. _GLTFUtilities.GetRightHandedPositionVector3FromRef(position);
  3071. }
  3072. vector = position.asArray();
  3073. for (var j = 0; j < positionStrideSize; ++j) {
  3074. var num = vector[j];
  3075. if (num < min[j]) {
  3076. min[j] = num;
  3077. }
  3078. if (num > max[j]) {
  3079. max[j] = num;
  3080. }
  3081. ++indexOffset;
  3082. }
  3083. }
  3084. }
  3085. return { min: min, max: max };
  3086. };
  3087. /**
  3088. * Converts a new right-handed Vector3
  3089. * @param vector vector3 array
  3090. * @returns right-handed Vector3
  3091. */
  3092. _GLTFUtilities.GetRightHandedPositionVector3 = function (vector) {
  3093. return new BABYLON.Vector3(vector.x, vector.y, -vector.z);
  3094. };
  3095. /**
  3096. * Converts a Vector3 to right-handed
  3097. * @param vector Vector3 to convert to right-handed
  3098. */
  3099. _GLTFUtilities.GetRightHandedPositionVector3FromRef = function (vector) {
  3100. vector.z *= -1;
  3101. };
  3102. /**
  3103. * Converts a three element number array to right-handed
  3104. * @param vector number array to convert to right-handed
  3105. */
  3106. _GLTFUtilities.GetRightHandedPositionArray3FromRef = function (vector) {
  3107. vector[2] *= -1;
  3108. };
  3109. /**
  3110. * Converts a new right-handed Vector3
  3111. * @param vector vector3 array
  3112. * @returns right-handed Vector3
  3113. */
  3114. _GLTFUtilities.GetRightHandedNormalVector3 = function (vector) {
  3115. return new BABYLON.Vector3(vector.x, vector.y, -vector.z);
  3116. };
  3117. /**
  3118. * Converts a Vector3 to right-handed
  3119. * @param vector Vector3 to convert to right-handed
  3120. */
  3121. _GLTFUtilities.GetRightHandedNormalVector3FromRef = function (vector) {
  3122. vector.z *= -1;
  3123. };
  3124. /**
  3125. * Converts a three element number array to right-handed
  3126. * @param vector number array to convert to right-handed
  3127. */
  3128. _GLTFUtilities.GetRightHandedNormalArray3FromRef = function (vector) {
  3129. vector[2] *= -1;
  3130. };
  3131. /**
  3132. * Converts a Vector4 to right-handed
  3133. * @param vector Vector4 to convert to right-handed
  3134. */
  3135. _GLTFUtilities.GetRightHandedVector4FromRef = function (vector) {
  3136. vector.z *= -1;
  3137. vector.w *= -1;
  3138. };
  3139. /**
  3140. * Converts a Vector4 to right-handed
  3141. * @param vector Vector4 to convert to right-handed
  3142. */
  3143. _GLTFUtilities.GetRightHandedArray4FromRef = function (vector) {
  3144. vector[2] *= -1;
  3145. vector[3] *= -1;
  3146. };
  3147. /**
  3148. * Converts a Quaternion to right-handed
  3149. * @param quaternion Source quaternion to convert to right-handed
  3150. */
  3151. _GLTFUtilities.GetRightHandedQuaternionFromRef = function (quaternion) {
  3152. quaternion.x *= -1;
  3153. quaternion.y *= -1;
  3154. };
  3155. /**
  3156. * Converts a Quaternion to right-handed
  3157. * @param quaternion Source quaternion to convert to right-handed
  3158. */
  3159. _GLTFUtilities.GetRightHandedQuaternionArrayFromRef = function (quaternion) {
  3160. quaternion[0] *= -1;
  3161. quaternion[1] *= -1;
  3162. };
  3163. return _GLTFUtilities;
  3164. }());
  3165. GLTF2._GLTFUtilities = _GLTFUtilities;
  3166. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3167. })(BABYLON || (BABYLON = {}));
  3168. //# sourceMappingURL=babylon.glTFUtilities.js.map