ColladaExporter.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. ( function () {
  2. /**
  3. * https://github.com/gkjohnson/collada-exporter-js
  4. *
  5. * Usage:
  6. * var exporter = new ColladaExporter();
  7. *
  8. * var data = exporter.parse(mesh);
  9. *
  10. * Format Definition:
  11. * https://www.khronos.org/collada/
  12. */
  13. var ColladaExporter = function () {};
  14. ColladaExporter.prototype = {
  15. constructor: ColladaExporter,
  16. parse: function ( object, onDone, options ) {
  17. options = options || {};
  18. options = Object.assign( {
  19. version: '1.4.1',
  20. author: null,
  21. textureDirectory: ''
  22. }, options );
  23. if ( options.textureDirectory !== '' ) {
  24. options.textureDirectory = `${options.textureDirectory}/`.replace( /\\/g, '/' ).replace( /\/+/g, '/' );
  25. }
  26. var version = options.version;
  27. if ( version !== '1.4.1' && version !== '1.5.0' ) {
  28. console.warn( `ColladaExporter : Version ${version} not supported for export. Only 1.4.1 and 1.5.0.` );
  29. return null;
  30. } // Convert the urdf xml into a well-formatted, indented format
  31. function format( urdf ) {
  32. var IS_END_TAG = /^<\//;
  33. var IS_SELF_CLOSING = /(\?>$)|(\/>$)/;
  34. var HAS_TEXT = /<[^>]+>[^<]*<\/[^<]+>/;
  35. var pad = ( ch, num ) => num > 0 ? ch + pad( ch, num - 1 ) : '';
  36. var tagnum = 0;
  37. return urdf.match( /(<[^>]+>[^<]+<\/[^<]+>)|(<[^>]+>)/g ).map( tag => {
  38. if ( ! HAS_TEXT.test( tag ) && ! IS_SELF_CLOSING.test( tag ) && IS_END_TAG.test( tag ) ) {
  39. tagnum --;
  40. }
  41. var res = `${pad( ' ', tagnum )}${tag}`;
  42. if ( ! HAS_TEXT.test( tag ) && ! IS_SELF_CLOSING.test( tag ) && ! IS_END_TAG.test( tag ) ) {
  43. tagnum ++;
  44. }
  45. return res;
  46. } ).join( '\n' );
  47. } // Convert an image into a png format for saving
  48. function base64ToBuffer( str ) {
  49. var b = atob( str );
  50. var buf = new Uint8Array( b.length );
  51. for ( var i = 0, l = buf.length; i < l; i ++ ) {
  52. buf[ i ] = b.charCodeAt( i );
  53. }
  54. return buf;
  55. }
  56. var canvas, ctx;
  57. function imageToData( image, ext ) {
  58. canvas = canvas || document.createElement( 'canvas' );
  59. ctx = ctx || canvas.getContext( '2d' );
  60. canvas.width = image.width;
  61. canvas.height = image.height;
  62. ctx.drawImage( image, 0, 0 ); // Get the base64 encoded data
  63. var base64data = canvas.toDataURL( `image/${ext}`, 1 ).replace( /^data:image\/(png|jpg);base64,/, '' ); // Convert to a uint8 array
  64. return base64ToBuffer( base64data );
  65. } // gets the attribute array. Generate a new array if the attribute is interleaved
  66. var getFuncs = [ 'getX', 'getY', 'getZ', 'getW' ];
  67. function attrBufferToArray( attr ) {
  68. if ( attr.isInterleavedBufferAttribute ) {
  69. // use the typed array constructor to save on memory
  70. var arr = new attr.array.constructor( attr.count * attr.itemSize );
  71. var size = attr.itemSize;
  72. for ( var i = 0, l = attr.count; i < l; i ++ ) {
  73. for ( var j = 0; j < size; j ++ ) {
  74. arr[ i * size + j ] = attr[ getFuncs[ j ] ]( i );
  75. }
  76. }
  77. return arr;
  78. } else {
  79. return attr.array;
  80. }
  81. } // Returns an array of the same type starting at the `st` index,
  82. // and `ct` length
  83. function subArray( arr, st, ct ) {
  84. if ( Array.isArray( arr ) ) return arr.slice( st, st + ct ); else return new arr.constructor( arr.buffer, st * arr.BYTES_PER_ELEMENT, ct );
  85. } // Returns the string for a geometry's attribute
  86. function getAttribute( attr, name, params, type ) {
  87. var array = attrBufferToArray( attr );
  88. var res = `<source id="${name}">` + `<float_array id="${name}-array" count="${array.length}">` + array.join( ' ' ) + '</float_array>' + '<technique_common>' + `<accessor source="#${name}-array" count="${Math.floor( array.length / attr.itemSize )}" stride="${attr.itemSize}">` + params.map( n => `<param name="${n}" type="${type}" />` ).join( '' ) + '</accessor>' + '</technique_common>' + '</source>';
  89. return res;
  90. } // Returns the string for a node's transform information
  91. var transMat;
  92. function getTransform( o ) {
  93. // ensure the object's matrix is up to date
  94. // before saving the transform
  95. o.updateMatrix();
  96. transMat = transMat || new THREE.Matrix4();
  97. transMat.copy( o.matrix );
  98. transMat.transpose();
  99. return `<matrix>${transMat.toArray().join( ' ' )}</matrix>`;
  100. } // Process the given piece of geometry into the geometry library
  101. // Returns the mesh id
  102. function processGeometry( g ) {
  103. var info = geometryInfo.get( g );
  104. if ( ! info ) {
  105. // convert the geometry to bufferGeometry if it isn't already
  106. var bufferGeometry = g;
  107. if ( bufferGeometry.isBufferGeometry !== true ) {
  108. throw new Error( 'THREE.ColladaExporter: Geometry is not of type THREE.BufferGeometry.' );
  109. }
  110. var meshid = `Mesh${libraryGeometries.length + 1}`;
  111. var indexCount = bufferGeometry.index ? bufferGeometry.index.count * bufferGeometry.index.itemSize : bufferGeometry.attributes.position.count;
  112. var groups = bufferGeometry.groups != null && bufferGeometry.groups.length !== 0 ? bufferGeometry.groups : [ {
  113. start: 0,
  114. count: indexCount,
  115. materialIndex: 0
  116. } ];
  117. var gname = g.name ? ` name="${g.name}"` : '';
  118. var gnode = `<geometry id="${meshid}"${gname}><mesh>`; // define the geometry node and the vertices for the geometry
  119. var posName = `${meshid}-position`;
  120. var vertName = `${meshid}-vertices`;
  121. gnode += getAttribute( bufferGeometry.attributes.position, posName, [ 'X', 'Y', 'Z' ], 'float' );
  122. gnode += `<vertices id="${vertName}"><input semantic="POSITION" source="#${posName}" /></vertices>`; // NOTE: We're not optimizing the attribute arrays here, so they're all the same length and
  123. // can therefore share the same triangle indices. However, MeshLab seems to have trouble opening
  124. // models with attributes that share an offset.
  125. // MeshLab Bug#424: https://sourceforge.net/p/meshlab/bugs/424/
  126. // serialize normals
  127. var triangleInputs = `<input semantic="VERTEX" source="#${vertName}" offset="0" />`;
  128. if ( 'normal' in bufferGeometry.attributes ) {
  129. var normName = `${meshid}-normal`;
  130. gnode += getAttribute( bufferGeometry.attributes.normal, normName, [ 'X', 'Y', 'Z' ], 'float' );
  131. triangleInputs += `<input semantic="NORMAL" source="#${normName}" offset="0" />`;
  132. } // serialize uvs
  133. if ( 'uv' in bufferGeometry.attributes ) {
  134. var uvName = `${meshid}-texcoord`;
  135. gnode += getAttribute( bufferGeometry.attributes.uv, uvName, [ 'S', 'T' ], 'float' );
  136. triangleInputs += `<input semantic="TEXCOORD" source="#${uvName}" offset="0" set="0" />`;
  137. } // serialize lightmap uvs
  138. if ( 'uv2' in bufferGeometry.attributes ) {
  139. var uvName = `${meshid}-texcoord2`;
  140. gnode += getAttribute( bufferGeometry.attributes.uv2, uvName, [ 'S', 'T' ], 'float' );
  141. triangleInputs += `<input semantic="TEXCOORD" source="#${uvName}" offset="0" set="1" />`;
  142. } // serialize colors
  143. if ( 'color' in bufferGeometry.attributes ) {
  144. var colName = `${meshid}-color`;
  145. gnode += getAttribute( bufferGeometry.attributes.color, colName, [ 'X', 'Y', 'Z' ], 'uint8' );
  146. triangleInputs += `<input semantic="COLOR" source="#${colName}" offset="0" />`;
  147. }
  148. var indexArray = null;
  149. if ( bufferGeometry.index ) {
  150. indexArray = attrBufferToArray( bufferGeometry.index );
  151. } else {
  152. indexArray = new Array( indexCount );
  153. for ( var i = 0, l = indexArray.length; i < l; i ++ ) indexArray[ i ] = i;
  154. }
  155. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  156. var group = groups[ i ];
  157. var subarr = subArray( indexArray, group.start, group.count );
  158. var polycount = subarr.length / 3;
  159. gnode += `<triangles material="MESH_MATERIAL_${group.materialIndex}" count="${polycount}">`;
  160. gnode += triangleInputs;
  161. gnode += `<p>${subarr.join( ' ' )}</p>`;
  162. gnode += '</triangles>';
  163. }
  164. gnode += '</mesh></geometry>';
  165. libraryGeometries.push( gnode );
  166. info = {
  167. meshid: meshid,
  168. bufferGeometry: bufferGeometry
  169. };
  170. geometryInfo.set( g, info );
  171. }
  172. return info;
  173. } // Process the given texture into the image library
  174. // Returns the image library
  175. function processTexture( tex ) {
  176. var texid = imageMap.get( tex );
  177. if ( texid == null ) {
  178. texid = `image-${libraryImages.length + 1}`;
  179. var ext = 'png';
  180. var name = tex.name || texid;
  181. var imageNode = `<image id="${texid}" name="${name}">`;
  182. if ( version === '1.5.0' ) {
  183. imageNode += `<init_from><ref>${options.textureDirectory}${name}.${ext}</ref></init_from>`;
  184. } else {
  185. // version image node 1.4.1
  186. imageNode += `<init_from>${options.textureDirectory}${name}.${ext}</init_from>`;
  187. }
  188. imageNode += '</image>';
  189. libraryImages.push( imageNode );
  190. imageMap.set( tex, texid );
  191. textures.push( {
  192. directory: options.textureDirectory,
  193. name,
  194. ext,
  195. data: imageToData( tex.image, ext ),
  196. original: tex
  197. } );
  198. }
  199. return texid;
  200. } // Process the given material into the material and effect libraries
  201. // Returns the material id
  202. function processMaterial( m ) {
  203. var matid = materialMap.get( m );
  204. if ( matid == null ) {
  205. matid = `Mat${libraryEffects.length + 1}`;
  206. var type = 'phong';
  207. if ( m.isMeshLambertMaterial === true ) {
  208. type = 'lambert';
  209. } else if ( m.isMeshBasicMaterial === true ) {
  210. type = 'constant';
  211. if ( m.map !== null ) {
  212. // The Collada spec does not support diffuse texture maps with the
  213. // constant shader type.
  214. // mrdoob/three.js#15469
  215. console.warn( 'ColladaExporter: Texture maps not supported with THREE.MeshBasicMaterial.' );
  216. }
  217. }
  218. var emissive = m.emissive ? m.emissive : new THREE.Color( 0, 0, 0 );
  219. var diffuse = m.color ? m.color : new THREE.Color( 0, 0, 0 );
  220. var specular = m.specular ? m.specular : new THREE.Color( 1, 1, 1 );
  221. var shininess = m.shininess || 0;
  222. var reflectivity = m.reflectivity || 0; // Do not export and alpha map for the reasons mentioned in issue (#13792)
  223. // in three.js alpha maps are black and white, but collada expects the alpha
  224. // channel to specify the transparency
  225. var transparencyNode = '';
  226. if ( m.transparent === true ) {
  227. transparencyNode += '<transparent>' + ( m.map ? '<texture texture="diffuse-sampler"></texture>' : '<float>1</float>' ) + '</transparent>';
  228. if ( m.opacity < 1 ) {
  229. transparencyNode += `<transparency><float>${m.opacity}</float></transparency>`;
  230. }
  231. }
  232. var techniqueNode = `<technique sid="common"><${type}>` + '<emission>' + ( m.emissiveMap ? '<texture texture="emissive-sampler" texcoord="TEXCOORD" />' : `<color sid="emission">${emissive.r} ${emissive.g} ${emissive.b} 1</color>` ) + '</emission>' + ( type !== 'constant' ? '<diffuse>' + ( m.map ? '<texture texture="diffuse-sampler" texcoord="TEXCOORD" />' : `<color sid="diffuse">${diffuse.r} ${diffuse.g} ${diffuse.b} 1</color>` ) + '</diffuse>' : '' ) + ( type !== 'constant' ? '<bump>' + ( m.normalMap ? '<texture texture="bump-sampler" texcoord="TEXCOORD" />' : '' ) + '</bump>' : '' ) + ( type === 'phong' ? `<specular><color sid="specular">${specular.r} ${specular.g} ${specular.b} 1</color></specular>` + '<shininess>' + ( m.specularMap ? '<texture texture="specular-sampler" texcoord="TEXCOORD" />' : `<float sid="shininess">${shininess}</float>` ) + '</shininess>' : '' ) + `<reflective><color>${diffuse.r} ${diffuse.g} ${diffuse.b} 1</color></reflective>` + `<reflectivity><float>${reflectivity}</float></reflectivity>` + transparencyNode + `</${type}></technique>`;
  233. var effectnode = `<effect id="${matid}-effect">` + '<profile_COMMON>' + ( m.map ? '<newparam sid="diffuse-surface"><surface type="2D">' + `<init_from>${processTexture( m.map )}</init_from>` + '</surface></newparam>' + '<newparam sid="diffuse-sampler"><sampler2D><source>diffuse-surface</source></sampler2D></newparam>' : '' ) + ( m.specularMap ? '<newparam sid="specular-surface"><surface type="2D">' + `<init_from>${processTexture( m.specularMap )}</init_from>` + '</surface></newparam>' + '<newparam sid="specular-sampler"><sampler2D><source>specular-surface</source></sampler2D></newparam>' : '' ) + ( m.emissiveMap ? '<newparam sid="emissive-surface"><surface type="2D">' + `<init_from>${processTexture( m.emissiveMap )}</init_from>` + '</surface></newparam>' + '<newparam sid="emissive-sampler"><sampler2D><source>emissive-surface</source></sampler2D></newparam>' : '' ) + ( m.normalMap ? '<newparam sid="bump-surface"><surface type="2D">' + `<init_from>${processTexture( m.normalMap )}</init_from>` + '</surface></newparam>' + '<newparam sid="bump-sampler"><sampler2D><source>bump-surface</source></sampler2D></newparam>' : '' ) + techniqueNode + ( m.side === THREE.DoubleSide ? '<extra><technique profile="THREEJS"><double_sided sid="double_sided" type="int">1</double_sided></technique></extra>' : '' ) + '</profile_COMMON>' + '</effect>';
  234. var materialName = m.name ? ` name="${m.name}"` : '';
  235. var materialNode = `<material id="${matid}"${materialName}><instance_effect url="#${matid}-effect" /></material>`;
  236. libraryMaterials.push( materialNode );
  237. libraryEffects.push( effectnode );
  238. materialMap.set( m, matid );
  239. }
  240. return matid;
  241. } // Recursively process the object into a scene
  242. function processObject( o ) {
  243. var node = `<node name="${o.name}">`;
  244. node += getTransform( o );
  245. if ( o.isMesh === true && o.geometry !== null ) {
  246. // function returns the id associated with the mesh and a "BufferGeometry" version
  247. // of the geometry in case it's not a geometry.
  248. var geomInfo = processGeometry( o.geometry );
  249. var meshid = geomInfo.meshid;
  250. var geometry = geomInfo.bufferGeometry; // ids of the materials to bind to the geometry
  251. var matids = null;
  252. var matidsArray = []; // get a list of materials to bind to the sub groups of the geometry.
  253. // If the amount of subgroups is greater than the materials, than reuse
  254. // the materials.
  255. var mat = o.material || new THREE.MeshBasicMaterial();
  256. var materials = Array.isArray( mat ) ? mat : [ mat ];
  257. if ( geometry.groups.length > materials.length ) {
  258. matidsArray = new Array( geometry.groups.length );
  259. } else {
  260. matidsArray = new Array( materials.length );
  261. }
  262. matids = matidsArray.fill().map( ( v, i ) => processMaterial( materials[ i % materials.length ] ) );
  263. node += `<instance_geometry url="#${meshid}">` + ( matids != null ? '<bind_material><technique_common>' + matids.map( ( id, i ) => `<instance_material symbol="MESH_MATERIAL_${i}" target="#${id}" >` + '<bind_vertex_input semantic="TEXCOORD" input_semantic="TEXCOORD" input_set="0" />' + '</instance_material>' ).join( '' ) + '</technique_common></bind_material>' : '' ) + '</instance_geometry>';
  264. }
  265. o.children.forEach( c => node += processObject( c ) );
  266. node += '</node>';
  267. return node;
  268. }
  269. var geometryInfo = new WeakMap();
  270. var materialMap = new WeakMap();
  271. var imageMap = new WeakMap();
  272. var textures = [];
  273. var libraryImages = [];
  274. var libraryGeometries = [];
  275. var libraryEffects = [];
  276. var libraryMaterials = [];
  277. var libraryVisualScenes = processObject( object );
  278. var specLink = version === '1.4.1' ? 'http://www.collada.org/2005/11/COLLADASchema' : 'https://www.khronos.org/collada/';
  279. var dae = '<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + `<COLLADA xmlns="${specLink}" version="${version}">` + '<asset>' + ( '<contributor>' + '<authoring_tool>three.js Collada Exporter</authoring_tool>' + ( options.author !== null ? `<author>${options.author}</author>` : '' ) + '</contributor>' + `<created>${new Date().toISOString()}</created>` + `<modified>${new Date().toISOString()}</modified>` + '<up_axis>Y_UP</up_axis>' ) + '</asset>';
  280. dae += `<library_images>${libraryImages.join( '' )}</library_images>`;
  281. dae += `<library_effects>${libraryEffects.join( '' )}</library_effects>`;
  282. dae += `<library_materials>${libraryMaterials.join( '' )}</library_materials>`;
  283. dae += `<library_geometries>${libraryGeometries.join( '' )}</library_geometries>`;
  284. dae += `<library_visual_scenes><visual_scene id="Scene" name="scene">${libraryVisualScenes}</visual_scene></library_visual_scenes>`;
  285. dae += '<scene><instance_visual_scene url="#Scene"/></scene>';
  286. dae += '</COLLADA>';
  287. var res = {
  288. data: format( dae ),
  289. textures
  290. };
  291. if ( typeof onDone === 'function' ) {
  292. requestAnimationFrame( () => onDone( res ) );
  293. }
  294. return res;
  295. }
  296. };
  297. THREE.ColladaExporter = ColladaExporter;
  298. } )();