ColladaExporter.js 17 KB

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