ColladaExporter.js 19 KB

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