ColladaExporter.js 17 KB

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