ColladaExporter.js 16 KB

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