ColladaExporter.js 16 KB

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