ColladaExporter.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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 meshid = geometryMap.get( g );
  130. // convert the geometry to bufferGeometry if it isn't already
  131. var processGeom = g;
  132. if ( processGeom instanceof THREE.Geometry ) {
  133. processGeom = ( new THREE.BufferGeometry() ).fromGeometry( processGeom );
  134. }
  135. if ( meshid == null ) {
  136. meshid = `Mesh${ libraryGeometries.length + 1 }`;
  137. var indexCount =
  138. processGeom.index ?
  139. processGeom.index.count * processGeom.index.itemSize :
  140. processGeom.attributes.position.count;
  141. var groups =
  142. processGeom.groups != null && processGeom.groups.length !== 0 ?
  143. processGeom.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( processGeom.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 processGeom.attributes ) {
  158. var normName = `${ meshid }-normal`;
  159. gnode += getAttribute( processGeom.attributes.normal, normName, [ 'X', 'Y', 'Z' ], 'float' );
  160. triangleInputs += `<input semantic="NORMAL" source="#${ normName }" offset="0" />`;
  161. }
  162. // serialize uvs
  163. if ( 'uv' in processGeom.attributes ) {
  164. var uvName = `${ meshid }-texcoord`;
  165. gnode += getAttribute( processGeom.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 processGeom.attributes ) {
  170. var colName = `${ meshid }-color`;
  171. gnode += getAttribute( processGeom.attributes.color, colName, [ 'X', 'Y', 'Z' ], 'uint8' );
  172. triangleInputs += `<input semantic="COLOR" source="#${ colName }" offset="0" />`;
  173. }
  174. var indexArray = null;
  175. if ( processGeom.index ) {
  176. indexArray = attrBufferToArray( processGeom.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. geometryMap.set( g, meshid );
  193. }
  194. return meshid;
  195. }
  196. // Process the given texture into the image library
  197. // Returns the image library
  198. function processTexture( tex ) {
  199. var texid = imageMap.get( tex );
  200. if ( texid == null ) {
  201. texid = `image-${ libraryImages.length + 1 }`;
  202. var ext = 'png';
  203. var name = tex.name || texid;
  204. var imageNode = `<image id="${ texid }" name="${ name }">`;
  205. if ( version === '1.5.0' ) {
  206. imageNode += `<init_from><ref>${ options.textureDirectory }${ name }.${ ext }</ref></init_from>`;
  207. } else {
  208. // version image node 1.4.1
  209. imageNode += `<init_from>${ options.textureDirectory }${ name }.${ ext }</init_from>`;
  210. }
  211. imageNode += '</image>';
  212. libraryImages.push( imageNode );
  213. imageMap.set( tex, texid );
  214. textures.push( {
  215. directory: options.textureDirectory,
  216. name,
  217. ext,
  218. data: imageToData( tex.image, ext ),
  219. original: tex
  220. } );
  221. }
  222. return texid;
  223. }
  224. // Process the given material into the material and effect libraries
  225. // Returns the material id
  226. function processMaterial( m ) {
  227. var matid = materialMap.get( m );
  228. if ( matid == null ) {
  229. matid = `Mat${ libraryEffects.length + 1 }`;
  230. var type = 'phong';
  231. if ( m instanceof THREE.MeshLambertMaterial ) {
  232. type = 'lambert';
  233. } else if ( m instanceof THREE.MeshBasicMaterial ) {
  234. type = 'constant';
  235. }
  236. var emissive = m.emissive ? m.emissive : new THREE.Color( 0, 0, 0 );
  237. var diffuse = m.color ? m.color : new THREE.Color( 0, 0, 0 );
  238. var specular = m.specular ? m.specular : new THREE.Color( 1, 1, 1 );
  239. var shininess = m.shininess || 0;
  240. var reflectivity = m.reflectivity || 0;
  241. // Do not export and alpha map for the reasons mentioned in issue (#13792)
  242. // in THREE.js alpha maps are black and white, but collada expects the alpha
  243. // channel to specify the transparency
  244. var transparencyNode = '';
  245. if ( m.transparent === true ) {
  246. transparencyNode +=
  247. `<transparent>` +
  248. (
  249. m.map ?
  250. `<texture texture="diffuse-sampler"></texture>` :
  251. '<float>1</float>'
  252. ) +
  253. '</transparent>';
  254. if ( m.opacity < 1 ) {
  255. transparencyNode += `<transparency><float>${ m.opacity }</float></transparency>`;
  256. }
  257. }
  258. var techniqueNode = `<technique sid="common"><${ type }>` +
  259. '<emission>' +
  260. (
  261. m.emissiveMap ?
  262. '<texture texture="emissive-sampler" texcoord="TEXCOORD" />' :
  263. `<color sid="emission">${ emissive.r } ${ emissive.g } ${ emissive.b } 1</color>`
  264. ) +
  265. '</emission>' +
  266. '<diffuse>' +
  267. (
  268. m.map ?
  269. '<texture texture="diffuse-sampler" texcoord="TEXCOORD" />' :
  270. `<color sid="diffuse">${ diffuse.r } ${ diffuse.g } ${ diffuse.b } 1</color>`
  271. ) +
  272. '</diffuse>' +
  273. `<specular><color sid="specular">${ specular.r } ${ specular.g } ${ specular.b } 1</color></specular>` +
  274. '<shininess>' +
  275. (
  276. m.specularMap ?
  277. '<texture texture="specular-sampler" texcoord="TEXCOORD" />' :
  278. `<float sid="shininess">${ shininess }</float>`
  279. ) +
  280. '</shininess>' +
  281. `<reflective><color>${ diffuse.r } ${ diffuse.g } ${ diffuse.b } 1</color></reflective>` +
  282. `<reflectivity><float>${ reflectivity }</float></reflectivity>` +
  283. transparencyNode +
  284. `</${ type }></technique>`;
  285. var effectnode =
  286. `<effect id="${ matid }-effect">` +
  287. '<profile_COMMON>' +
  288. (
  289. m.map ?
  290. '<newparam sid="diffuse-surface"><surface type="2D">' +
  291. `<init_from>${ processTexture( m.map ) }</init_from>` +
  292. '</surface></newparam>' +
  293. '<newparam sid="diffuse-sampler"><sampler2D><source>diffuse-surface</source></sampler2D></newparam>' :
  294. ''
  295. ) +
  296. (
  297. m.specularMap ?
  298. '<newparam sid="specular-surface"><surface type="2D">' +
  299. `<init_from>${ processTexture( m.specularMap ) }</init_from>` +
  300. '</surface></newparam>' +
  301. '<newparam sid="specular-sampler"><sampler2D><source>specular-surface</source></sampler2D></newparam>' :
  302. ''
  303. ) +
  304. (
  305. m.emissiveMap ?
  306. '<newparam sid="emissive-surface"><surface type="2D">' +
  307. `<init_from>${ processTexture( m.emissiveMap ) }</init_from>` +
  308. '</surface></newparam>' +
  309. '<newparam sid="emissive-sampler"><sampler2D><source>emissive-surface</source></sampler2D></newparam>' :
  310. ''
  311. ) +
  312. techniqueNode +
  313. (
  314. m.side === THREE.DoubleSide ?
  315. `<extra><technique><double_sided sid="double_sided" type="int">1</double_sided></technique></extra>` :
  316. ''
  317. ) +
  318. '</profile_COMMON>' +
  319. '</effect>';
  320. libraryMaterials.push( `<material id="${ matid }" name="${ m.name }"><instance_effect url="#${ matid }-effect" /></material>` );
  321. libraryEffects.push( effectnode );
  322. materialMap.set( m, matid );
  323. }
  324. return matid;
  325. }
  326. // Recursively process the object into a scene
  327. function processObject( o ) {
  328. var node = `<node name="${ o.name }">`;
  329. node += getTransform( o );
  330. if ( o instanceof THREE.Mesh && o.geometry != null ) {
  331. var meshid = processGeometry( o.geometry, meshid );
  332. // ids of the materials to bind to the geometry
  333. var matids = null;
  334. // get a list of materials to bind to the sub groups of the geometry.
  335. // If the amount of subgroups is greater than the materials, than reuse
  336. // the materials.
  337. var mat = o.material || new THREE.MeshBasicMaterial();
  338. var materials = Array.isArray( mat ) ? mat : [ mat ];
  339. matids = new Array( o.geometry.groups.length )
  340. .fill()
  341. .map( ( v, i ) => processMaterial( materials[ i % materials.length ] ) );
  342. node +=
  343. `<instance_geometry url="#${ meshid }">` +
  344. (
  345. matids != null ?
  346. '<bind_material><technique_common>' +
  347. matids.map( ( id, i ) =>
  348. `<instance_material symbol="MESH_MATERIAL_${ i }" target="#${ id }" >` +
  349. '<bind_vertex_input semantic="TEXCOORD" input_semantic="TEXCOORD" input_set="0" />' +
  350. '</instance_material>'
  351. ).join( '' ) +
  352. '</technique_common></bind_material>' :
  353. ''
  354. ) +
  355. '</instance_geometry>';
  356. }
  357. o.children.forEach( c => node += processObject( c ) );
  358. node += '</node>';
  359. return node;
  360. }
  361. var geometryMap = new WeakMap();
  362. var materialMap = new WeakMap();
  363. var imageMap = new WeakMap();
  364. var textures = [];
  365. var libraryImages = [];
  366. var libraryGeometries = [];
  367. var libraryEffects = [];
  368. var libraryMaterials = [];
  369. var libraryVisualScenes = processObject( object );
  370. var specLink = version === '1.4.1' ? 'http://www.collada.org/2005/11/COLLADASchema' : 'https://www.khronos.org/collada/';
  371. var dae =
  372. '<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' +
  373. `<COLLADA xmlns="${ specLink }" version="${ version }">` +
  374. '<asset>' +
  375. (
  376. '<contributor>' +
  377. '<authoring_tool>THREE.js Collada Exporter</authoring_tool>' +
  378. ( options.author !== null ? `<author>${ options.author }</author>` : '' ) +
  379. '</contributor>' +
  380. `<created>${ ( new Date() ).toISOString() }</created>` +
  381. `<modified>${ ( new Date() ).toISOString() }</modified>` +
  382. '<up_axis>Y_UP</up_axis>'
  383. ) +
  384. '</asset>';
  385. dae += `<library_images>${ libraryImages.join( '' ) }</library_images>`;
  386. dae += `<library_effects>${ libraryEffects.join( '' ) }</library_effects>`;
  387. dae += `<library_materials>${ libraryMaterials.join( '' ) }</library_materials>`;
  388. dae += `<library_geometries>${ libraryGeometries.join( '' ) }</library_geometries>`;
  389. dae += `<library_visual_scenes><visual_scene id="Scene" name="scene">${ libraryVisualScenes }</visual_scene></library_visual_scenes>`;
  390. dae += '<scene><instance_visual_scene url="#Scene"/></scene>';
  391. dae += '</COLLADA>';
  392. var res = {
  393. data: format( dae ),
  394. textures
  395. };
  396. if ( typeof onDone === 'function' ) {
  397. requestAnimationFrame( () => onDone( res ) );
  398. }
  399. return res;
  400. }
  401. };