ColladaExporter.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  1. console.warn( "THREE.ColladaExporter: As part of the transition to ES6 Modules, the files in 'examples/js' were deprecated in May 2020 (r117) and will be deleted in December 2020 (r124). You can find more information about developing using ES6 Modules in https://threejs.org/docs/#manual/en/introduction/Installation." );
  2. /**
  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.width;
  68. canvas.height = image.height;
  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 lightmap uvs
  171. if ( 'uv2' in bufferGeometry.attributes ) {
  172. var uvName = `${ meshid }-texcoord2`;
  173. gnode += getAttribute( bufferGeometry.attributes.uv2, uvName, [ 'S', 'T' ], 'float' );
  174. triangleInputs += `<input semantic="TEXCOORD" source="#${ uvName }" offset="0" set="1" />`;
  175. }
  176. // serialize colors
  177. if ( 'color' in bufferGeometry.attributes ) {
  178. var colName = `${ meshid }-color`;
  179. gnode += getAttribute( bufferGeometry.attributes.color, colName, [ 'X', 'Y', 'Z' ], 'uint8' );
  180. triangleInputs += `<input semantic="COLOR" source="#${ colName }" offset="0" />`;
  181. }
  182. var indexArray = null;
  183. if ( bufferGeometry.index ) {
  184. indexArray = attrBufferToArray( bufferGeometry.index );
  185. } else {
  186. indexArray = new Array( indexCount );
  187. for ( var i = 0, l = indexArray.length; i < l; i ++ ) indexArray[ i ] = i;
  188. }
  189. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  190. var group = groups[ i ];
  191. var subarr = subArray( indexArray, group.start, group.count );
  192. var polycount = subarr.length / 3;
  193. gnode += `<triangles material="MESH_MATERIAL_${ group.materialIndex }" count="${ polycount }">`;
  194. gnode += triangleInputs;
  195. gnode += `<p>${ subarr.join( ' ' ) }</p>`;
  196. gnode += '</triangles>';
  197. }
  198. gnode += `</mesh></geometry>`;
  199. libraryGeometries.push( gnode );
  200. info = { meshid: meshid, bufferGeometry: bufferGeometry };
  201. geometryInfo.set( g, info );
  202. }
  203. return info;
  204. }
  205. // Process the given texture into the image library
  206. // Returns the image library
  207. function processTexture( tex ) {
  208. var texid = imageMap.get( tex );
  209. if ( texid == null ) {
  210. texid = `image-${ libraryImages.length + 1 }`;
  211. var ext = 'png';
  212. var name = tex.name || texid;
  213. var imageNode = `<image id="${ texid }" name="${ name }">`;
  214. if ( version === '1.5.0' ) {
  215. imageNode += `<init_from><ref>${ options.textureDirectory }${ name }.${ ext }</ref></init_from>`;
  216. } else {
  217. // version image node 1.4.1
  218. imageNode += `<init_from>${ options.textureDirectory }${ name }.${ ext }</init_from>`;
  219. }
  220. imageNode += '</image>';
  221. libraryImages.push( imageNode );
  222. imageMap.set( tex, texid );
  223. textures.push( {
  224. directory: options.textureDirectory,
  225. name,
  226. ext,
  227. data: imageToData( tex.image, ext ),
  228. original: tex
  229. } );
  230. }
  231. return texid;
  232. }
  233. // Process the given material into the material and effect libraries
  234. // Returns the material id
  235. function processMaterial( m ) {
  236. var matid = materialMap.get( m );
  237. if ( matid == null ) {
  238. matid = `Mat${ libraryEffects.length + 1 }`;
  239. var type = 'phong';
  240. if ( m instanceof THREE.MeshLambertMaterial ) {
  241. type = 'lambert';
  242. } else if ( m instanceof THREE.MeshBasicMaterial ) {
  243. type = 'constant';
  244. if ( m.map !== null ) {
  245. // The Collada spec does not support diffuse texture maps with the
  246. // constant shader type.
  247. // mrdoob/three.js#15469
  248. console.warn( 'ColladaExporter: Texture maps not supported with MeshBasicMaterial.' );
  249. }
  250. }
  251. var emissive = m.emissive ? m.emissive : new THREE.Color( 0, 0, 0 );
  252. var diffuse = m.color ? m.color : new THREE.Color( 0, 0, 0 );
  253. var specular = m.specular ? m.specular : new THREE.Color( 1, 1, 1 );
  254. var shininess = m.shininess || 0;
  255. var reflectivity = m.reflectivity || 0;
  256. // Do not export and alpha map for the reasons mentioned in issue (#13792)
  257. // in three.js alpha maps are black and white, but collada expects the alpha
  258. // channel to specify the transparency
  259. var transparencyNode = '';
  260. if ( m.transparent === true ) {
  261. transparencyNode +=
  262. `<transparent>` +
  263. (
  264. m.map ?
  265. `<texture texture="diffuse-sampler"></texture>` :
  266. '<float>1</float>'
  267. ) +
  268. '</transparent>';
  269. if ( m.opacity < 1 ) {
  270. transparencyNode += `<transparency><float>${ m.opacity }</float></transparency>`;
  271. }
  272. }
  273. var techniqueNode = `<technique sid="common"><${ type }>` +
  274. '<emission>' +
  275. (
  276. m.emissiveMap ?
  277. '<texture texture="emissive-sampler" texcoord="TEXCOORD" />' :
  278. `<color sid="emission">${ emissive.r } ${ emissive.g } ${ emissive.b } 1</color>`
  279. ) +
  280. '</emission>' +
  281. (
  282. type !== 'constant' ?
  283. '<diffuse>' +
  284. (
  285. m.map ?
  286. '<texture texture="diffuse-sampler" texcoord="TEXCOORD" />' :
  287. `<color sid="diffuse">${ diffuse.r } ${ diffuse.g } ${ diffuse.b } 1</color>`
  288. ) +
  289. '</diffuse>'
  290. : ''
  291. ) +
  292. (
  293. type !== 'constant' ?
  294. '<bump>' +
  295. (
  296. m.normalMap ? '<texture texture="bump-sampler" texcoord="TEXCOORD" />' : ''
  297. ) +
  298. '</bump>'
  299. : ''
  300. ) +
  301. (
  302. type === 'phong' ?
  303. `<specular><color sid="specular">${ specular.r } ${ specular.g } ${ specular.b } 1</color></specular>` +
  304. '<shininess>' +
  305. (
  306. m.specularMap ?
  307. '<texture texture="specular-sampler" texcoord="TEXCOORD" />' :
  308. `<float sid="shininess">${ shininess }</float>`
  309. ) +
  310. '</shininess>'
  311. : ''
  312. ) +
  313. `<reflective><color>${ diffuse.r } ${ diffuse.g } ${ diffuse.b } 1</color></reflective>` +
  314. `<reflectivity><float>${ reflectivity }</float></reflectivity>` +
  315. transparencyNode +
  316. `</${ type }></technique>`;
  317. var effectnode =
  318. `<effect id="${ matid }-effect">` +
  319. '<profile_COMMON>' +
  320. (
  321. m.map ?
  322. '<newparam sid="diffuse-surface"><surface type="2D">' +
  323. `<init_from>${ processTexture( m.map ) }</init_from>` +
  324. '</surface></newparam>' +
  325. '<newparam sid="diffuse-sampler"><sampler2D><source>diffuse-surface</source></sampler2D></newparam>' :
  326. ''
  327. ) +
  328. (
  329. m.specularMap ?
  330. '<newparam sid="specular-surface"><surface type="2D">' +
  331. `<init_from>${ processTexture( m.specularMap ) }</init_from>` +
  332. '</surface></newparam>' +
  333. '<newparam sid="specular-sampler"><sampler2D><source>specular-surface</source></sampler2D></newparam>' :
  334. ''
  335. ) +
  336. (
  337. m.emissiveMap ?
  338. '<newparam sid="emissive-surface"><surface type="2D">' +
  339. `<init_from>${ processTexture( m.emissiveMap ) }</init_from>` +
  340. '</surface></newparam>' +
  341. '<newparam sid="emissive-sampler"><sampler2D><source>emissive-surface</source></sampler2D></newparam>' :
  342. ''
  343. ) +
  344. (
  345. m.normalMap ?
  346. '<newparam sid="bump-surface"><surface type="2D">' +
  347. `<init_from>${ processTexture( m.normalMap ) }</init_from>` +
  348. '</surface></newparam>' +
  349. '<newparam sid="bump-sampler"><sampler2D><source>bump-surface</source></sampler2D></newparam>' :
  350. ''
  351. ) +
  352. techniqueNode +
  353. (
  354. m.side === THREE.DoubleSide ?
  355. `<extra><technique profile="THREEJS"><double_sided sid="double_sided" type="int">1</double_sided></technique></extra>` :
  356. ''
  357. ) +
  358. '</profile_COMMON>' +
  359. '</effect>';
  360. var materialName = m.name ? ` name="${ m.name }"` : '';
  361. var materialNode = `<material id="${ matid }"${ materialName }><instance_effect url="#${ matid }-effect" /></material>`;
  362. libraryMaterials.push( materialNode );
  363. libraryEffects.push( effectnode );
  364. materialMap.set( m, matid );
  365. }
  366. return matid;
  367. }
  368. // Recursively process the object into a scene
  369. function processObject( o ) {
  370. var node = `<node name="${ o.name }">`;
  371. node += getTransform( o );
  372. if ( o instanceof THREE.Mesh && o.geometry != null ) {
  373. // function returns the id associated with the mesh and a "BufferGeometry" version
  374. // of the geometry in case it's not a geometry.
  375. var geomInfo = processGeometry( o.geometry );
  376. var meshid = geomInfo.meshid;
  377. var geometry = geomInfo.bufferGeometry;
  378. // ids of the materials to bind to the geometry
  379. var matids = null;
  380. var matidsArray = [];
  381. // get a list of materials to bind to the sub groups of the geometry.
  382. // If the amount of subgroups is greater than the materials, than reuse
  383. // the materials.
  384. var mat = o.material || new THREE.MeshBasicMaterial();
  385. var materials = Array.isArray( mat ) ? mat : [ mat ];
  386. if ( geometry.groups.length > materials.length ) {
  387. matidsArray = new Array( geometry.groups.length );
  388. } else {
  389. matidsArray = new Array( materials.length );
  390. }
  391. matids = matidsArray.fill().map( ( v, i ) => processMaterial( materials[ i % materials.length ] ) );
  392. node +=
  393. `<instance_geometry url="#${ meshid }">` +
  394. (
  395. matids != null ?
  396. '<bind_material><technique_common>' +
  397. matids.map( ( id, i ) =>
  398. `<instance_material symbol="MESH_MATERIAL_${ i }" target="#${ id }" >` +
  399. '<bind_vertex_input semantic="TEXCOORD" input_semantic="TEXCOORD" input_set="0" />' +
  400. '</instance_material>'
  401. ).join( '' ) +
  402. '</technique_common></bind_material>' :
  403. ''
  404. ) +
  405. '</instance_geometry>';
  406. }
  407. o.children.forEach( c => node += processObject( c ) );
  408. node += '</node>';
  409. return node;
  410. }
  411. var geometryInfo = new WeakMap();
  412. var materialMap = new WeakMap();
  413. var imageMap = new WeakMap();
  414. var textures = [];
  415. var libraryImages = [];
  416. var libraryGeometries = [];
  417. var libraryEffects = [];
  418. var libraryMaterials = [];
  419. var libraryVisualScenes = processObject( object );
  420. var specLink = version === '1.4.1' ? 'http://www.collada.org/2005/11/COLLADASchema' : 'https://www.khronos.org/collada/';
  421. var dae =
  422. '<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' +
  423. `<COLLADA xmlns="${ specLink }" version="${ version }">` +
  424. '<asset>' +
  425. (
  426. '<contributor>' +
  427. '<authoring_tool>three.js Collada Exporter</authoring_tool>' +
  428. ( options.author !== null ? `<author>${ options.author }</author>` : '' ) +
  429. '</contributor>' +
  430. `<created>${ ( new Date() ).toISOString() }</created>` +
  431. `<modified>${ ( new Date() ).toISOString() }</modified>` +
  432. '<up_axis>Y_UP</up_axis>'
  433. ) +
  434. '</asset>';
  435. dae += `<library_images>${ libraryImages.join( '' ) }</library_images>`;
  436. dae += `<library_effects>${ libraryEffects.join( '' ) }</library_effects>`;
  437. dae += `<library_materials>${ libraryMaterials.join( '' ) }</library_materials>`;
  438. dae += `<library_geometries>${ libraryGeometries.join( '' ) }</library_geometries>`;
  439. dae += `<library_visual_scenes><visual_scene id="Scene" name="scene">${ libraryVisualScenes }</visual_scene></library_visual_scenes>`;
  440. dae += '<scene><instance_visual_scene url="#Scene"/></scene>';
  441. dae += '</COLLADA>';
  442. var res = {
  443. data: format( dae ),
  444. textures
  445. };
  446. if ( typeof onDone === 'function' ) {
  447. requestAnimationFrame( () => onDone( res ) );
  448. }
  449. return res;
  450. }
  451. };