ColladaExporter.js 16 KB

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