CTMLoader.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. /**
  2. * Loader for CTM encoded models generated by OpenCTM tools:
  3. * http://openctm.sourceforge.net/
  4. *
  5. * Uses js-openctm library by Juan Mellado
  6. * http://code.google.com/p/js-openctm/
  7. *
  8. * @author alteredq / http://alteredqualia.com/
  9. */
  10. THREE.CTMLoader = function ( showStatus ) {
  11. THREE.Loader.call( this, showStatus );
  12. };
  13. THREE.CTMLoader.prototype = Object.create( THREE.Loader.prototype );
  14. // Load multiple CTM parts defined in JSON
  15. THREE.CTMLoader.prototype.loadParts = function( url, callback, parameters ) {
  16. var scope = this;
  17. var xhr = new XMLHttpRequest();
  18. var basePath = parameters.basePath ? parameters.basePath : this.extractUrlBase( url );
  19. xhr.onreadystatechange = function() {
  20. if ( xhr.readyState === 4 ) {
  21. if ( xhr.status === 200 || xhr.status === 0 ) {
  22. var jsonObject = JSON.parse( xhr.responseText );
  23. var materials = [], geometries = [], counter = 0;
  24. function callbackFinal( geometry ) {
  25. counter += 1;
  26. geometries.push( geometry );
  27. if ( counter === jsonObject.offsets.length ) {
  28. callback( geometries, materials );
  29. }
  30. }
  31. // init materials
  32. for ( var i = 0; i < jsonObject.materials.length; i ++ ) {
  33. materials[ i ] = THREE.Loader.prototype.createMaterial( jsonObject.materials[ i ], basePath );
  34. }
  35. // load joined CTM file
  36. var partUrl = basePath + jsonObject.data;
  37. var parametersPart = { useWorker: parameters.useWorker, useBuffers: parameters.useBuffers, offsets: jsonObject.offsets };
  38. scope.load( partUrl, callbackFinal, parametersPart );
  39. }
  40. }
  41. }
  42. xhr.open( "GET", url, true );
  43. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  44. xhr.setRequestHeader( "Content-Type", "text/plain" );
  45. xhr.send( null );
  46. };
  47. // Load CTMLoader compressed models
  48. // - parameters
  49. // - url (required)
  50. // - callback (required)
  51. THREE.CTMLoader.prototype.load = function( url, callback, parameters ) {
  52. var scope = this;
  53. var offsets = parameters.offsets !== undefined ? parameters.offsets : [ 0 ];
  54. var xhr = new XMLHttpRequest(),
  55. callbackProgress = null;
  56. var length = 0;
  57. xhr.onreadystatechange = function() {
  58. if ( xhr.readyState === 4 ) {
  59. if ( xhr.status === 200 || xhr.status === 0 ) {
  60. var binaryData = xhr.responseText;
  61. //var s = Date.now();
  62. if ( parameters.useWorker ) {
  63. var worker = new Worker( "js/loaders/ctm/CTMWorker.js" );
  64. worker.onmessage = function( event ) {
  65. var files = event.data;
  66. for ( var i = 0; i < files.length; i ++ ) {
  67. var ctmFile = files[ i ];
  68. if ( parameters.useBuffers ) {
  69. scope.createModelBuffers( ctmFile, callback );
  70. } else {
  71. scope.createModelClassic( ctmFile, callback );
  72. }
  73. }
  74. //var e = Date.now();
  75. //console.log( "CTM data parse time [worker]: " + (e-s) + " ms" );
  76. };
  77. worker.postMessage( { "data": binaryData, "offsets": offsets } );
  78. } else {
  79. for ( var i = 0; i < offsets.length; i ++ ) {
  80. var stream = new CTM.Stream( binaryData );
  81. stream.offset = offsets[ i ];
  82. var ctmFile = new CTM.File( stream );
  83. if ( parameters.useBuffers ) {
  84. scope.createModelBuffers( ctmFile, callback );
  85. } else {
  86. scope.createModelClassic( ctmFile, callback );
  87. }
  88. }
  89. //var e = Date.now();
  90. //console.log( "CTM data parse time [inline]: " + (e-s) + " ms" );
  91. }
  92. } else {
  93. console.error( "Couldn't load [" + url + "] [" + xhr.status + "]" );
  94. }
  95. } else if ( xhr.readyState === 3 ) {
  96. if ( callbackProgress ) {
  97. if ( length === 0 ) {
  98. length = xhr.getResponseHeader( "Content-Length" );
  99. }
  100. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  101. }
  102. } else if ( xhr.readyState === 2 ) {
  103. length = xhr.getResponseHeader( "Content-Length" );
  104. }
  105. }
  106. xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  107. xhr.open( "GET", url, true );
  108. xhr.send( null );
  109. };
  110. THREE.CTMLoader.prototype.createModelBuffers = function ( file, callback ) {
  111. var Model = function ( ) {
  112. var scope = this;
  113. var reorderVertices = true;
  114. scope.materials = [];
  115. THREE.BufferGeometry.call( this );
  116. // init GL buffers
  117. var vertexIndexArray = file.body.indices,
  118. vertexPositionArray = file.body.vertices,
  119. vertexNormalArray = file.body.normals;
  120. var vertexUvArray, vertexColorArray;
  121. if ( file.body.uvMaps !== undefined && file.body.uvMaps.length > 0 ) {
  122. vertexUvArray = file.body.uvMaps[ 0 ].uv;
  123. }
  124. if ( file.body.attrMaps !== undefined && file.body.attrMaps.length > 0 && file.body.attrMaps[ 0 ].name === "Color" ) {
  125. vertexColorArray = file.body.attrMaps[ 0 ].attr;
  126. }
  127. // reorder vertices
  128. // (needed for buffer splitting, to keep together face vertices)
  129. if ( reorderVertices ) {
  130. var newFaces = new Uint32Array( vertexIndexArray.length ),
  131. newVertices = new Float32Array( vertexPositionArray.length );
  132. var newNormals, newUvs, newColors;
  133. if ( vertexNormalArray ) newNormals = new Float32Array( vertexNormalArray.length );
  134. if ( vertexUvArray ) newUvs = new Float32Array( vertexUvArray.length );
  135. if ( vertexColorArray ) newColors = new Float32Array( vertexColorArray.length );
  136. var indexMap = {}, vertexCounter = 0;
  137. function handleVertex( v ) {
  138. if ( indexMap[ v ] === undefined ) {
  139. indexMap[ v ] = vertexCounter;
  140. var sx = v * 3,
  141. sy = v * 3 + 1,
  142. sz = v * 3 + 2,
  143. dx = vertexCounter * 3,
  144. dy = vertexCounter * 3 + 1,
  145. dz = vertexCounter * 3 + 2;
  146. newVertices[ dx ] = vertexPositionArray[ sx ];
  147. newVertices[ dy ] = vertexPositionArray[ sy ];
  148. newVertices[ dz ] = vertexPositionArray[ sz ];
  149. if ( vertexNormalArray ) {
  150. newNormals[ dx ] = vertexNormalArray[ sx ];
  151. newNormals[ dy ] = vertexNormalArray[ sy ];
  152. newNormals[ dz ] = vertexNormalArray[ sz ];
  153. }
  154. if ( vertexUvArray ) {
  155. newUvs[ vertexCounter * 2 ] = vertexUvArray[ v * 2 ];
  156. newUvs[ vertexCounter * 2 + 1 ] = vertexUvArray[ v * 2 + 1 ];
  157. }
  158. if ( vertexColorArray ) {
  159. newColors[ vertexCounter * 4 ] = vertexColorArray[ v * 4 ];
  160. newColors[ vertexCounter * 4 + 1 ] = vertexColorArray[ v * 4 + 1 ];
  161. newColors[ vertexCounter * 4 + 2 ] = vertexColorArray[ v * 4 + 2 ];
  162. newColors[ vertexCounter * 4 + 3 ] = vertexColorArray[ v * 4 + 3 ];
  163. }
  164. vertexCounter += 1;
  165. }
  166. }
  167. var a, b, c;
  168. for ( var i = 0; i < vertexIndexArray.length; i += 3 ) {
  169. a = vertexIndexArray[ i ];
  170. b = vertexIndexArray[ i + 1 ];
  171. c = vertexIndexArray[ i + 2 ];
  172. handleVertex( a );
  173. handleVertex( b );
  174. handleVertex( c );
  175. newFaces[ i ] = indexMap[ a ];
  176. newFaces[ i + 1 ] = indexMap[ b ];
  177. newFaces[ i + 2 ] = indexMap[ c ];
  178. }
  179. vertexIndexArray = newFaces;
  180. vertexPositionArray = newVertices;
  181. if ( vertexNormalArray ) vertexNormalArray = newNormals;
  182. if ( vertexUvArray ) vertexUvArray = newUvs;
  183. if ( vertexColorArray ) vertexColorArray = newColors;
  184. }
  185. // compute offsets
  186. scope.offsets = [];
  187. var indices = vertexIndexArray;
  188. var start = 0,
  189. min = vertexPositionArray.length,
  190. max = 0,
  191. minPrev = min;
  192. for ( var i = 0; i < indices.length; ) {
  193. for ( var j = 0; j < 3; ++ j ) {
  194. var idx = indices[ i ++ ];
  195. if ( idx < min ) min = idx;
  196. if ( idx > max ) max = idx;
  197. }
  198. if ( max - min > 65535 ) {
  199. i -= 3;
  200. for ( var k = start; k < i; ++ k ) {
  201. indices[ k ] -= minPrev;
  202. }
  203. scope.offsets.push( { start: start, count: i - start, index: minPrev } );
  204. start = i;
  205. min = vertexPositionArray.length;
  206. max = 0;
  207. }
  208. minPrev = min;
  209. }
  210. for ( var k = start; k < i; ++ k ) {
  211. indices[ k ] -= minPrev;
  212. }
  213. scope.offsets.push( { start: start, count: i - start, index: minPrev } );
  214. // recast CTM 32-bit indices as 16-bit WebGL indices
  215. var vertexIndexArray16 = new Uint16Array( vertexIndexArray );
  216. // attributes
  217. var attributes = scope.attributes;
  218. attributes[ "index" ] = { itemSize: 1, array: vertexIndexArray16, numItems: vertexIndexArray16.length };
  219. attributes[ "position" ] = { itemSize: 3, array: vertexPositionArray, numItems: vertexPositionArray.length };
  220. if ( vertexNormalArray !== undefined ) {
  221. attributes[ "normal" ] = { itemSize: 3, array: vertexNormalArray, numItems: vertexNormalArray.length };
  222. }
  223. if ( vertexUvArray !== undefined ) {
  224. attributes[ "uv" ] = { itemSize: 2, array: vertexUvArray, numItems: vertexUvArray.length };
  225. }
  226. if ( vertexColorArray !== undefined ) {
  227. attributes[ "color" ] = { itemSize: 4, array: vertexColorArray, numItems: vertexColorArray.length };
  228. }
  229. }
  230. Model.prototype = Object.create( THREE.BufferGeometry.prototype );
  231. var geometry = new Model();
  232. // compute vertex normals if not present in the CTM model
  233. if ( geometry.attributes[ "normal" ] === undefined ) {
  234. geometry.computeVertexNormals();
  235. }
  236. callback( geometry );
  237. };
  238. THREE.CTMLoader.prototype.createModelClassic = function ( file, callback ) {
  239. var Model = function ( ) {
  240. var scope = this;
  241. scope.materials = [];
  242. THREE.Geometry.call( this );
  243. var normals = [],
  244. uvs = [],
  245. colors = [];
  246. init_vertices( file.body.vertices );
  247. if ( file.body.normals !== undefined )
  248. init_normals( file.body.normals );
  249. if ( file.body.uvMaps !== undefined && file.body.uvMaps.length > 0 )
  250. init_uvs( file.body.uvMaps[ 0 ].uv );
  251. if ( file.body.attrMaps !== undefined && file.body.attrMaps.length > 0 && file.body.attrMaps[ 0 ].name === "Color" )
  252. init_colors( file.body.attrMaps[ 0 ].attr );
  253. var hasNormals = normals.length > 0 ? true : false,
  254. hasUvs = uvs.length > 0 ? true : false,
  255. hasColors = colors.length > 0 ? true : false;
  256. init_faces( file.body.indices );
  257. this.computeCentroids();
  258. this.computeFaceNormals();
  259. //this.computeTangents();
  260. function init_vertices( buffer ) {
  261. var x, y, z, i, il = buffer.length;
  262. for( i = 0; i < il; i += 3 ) {
  263. x = buffer[ i ];
  264. y = buffer[ i + 1 ];
  265. z = buffer[ i + 2 ];
  266. vertex( scope, x, y, z );
  267. }
  268. };
  269. function init_normals( buffer ) {
  270. var x, y, z, i, il = buffer.length;
  271. for( i = 0; i < il; i += 3 ) {
  272. x = buffer[ i ];
  273. y = buffer[ i + 1 ];
  274. z = buffer[ i + 2 ];
  275. normals.push( x, y, z );
  276. }
  277. };
  278. function init_colors( buffer ) {
  279. var r, g, b, a, i, il = buffer.length;
  280. for( i = 0; i < il; i += 4 ) {
  281. r = buffer[ i ];
  282. g = buffer[ i + 1 ];
  283. b = buffer[ i + 2 ];
  284. a = buffer[ i + 3 ];
  285. var color = new THREE.Color();
  286. color.setRGB( r, g, b );
  287. colors.push( color );
  288. }
  289. };
  290. function init_uvs( buffer ) {
  291. var u, v, i, il = buffer.length;
  292. for( i = 0; i < il; i += 2 ) {
  293. u = buffer[ i ];
  294. v = buffer[ i + 1 ];
  295. uvs.push( u, v );
  296. }
  297. };
  298. function init_faces( buffer ) {
  299. var a, b, c,
  300. u1, v1, u2, v2, u3, v3,
  301. m, face,
  302. i, il = buffer.length;
  303. m = 0; // all faces defaulting to material 0
  304. for( i = 0; i < il; i += 3 ) {
  305. a = buffer[ i ];
  306. b = buffer[ i + 1 ];
  307. c = buffer[ i + 2 ];
  308. if ( hasNormals ){
  309. face = f3n( scope, normals, a, b, c, m, a, b, c );
  310. } else {
  311. face = f3( scope, a, b, c, m );
  312. }
  313. if ( hasColors ) {
  314. face.vertexColors[ 0 ] = colors[ a ];
  315. face.vertexColors[ 1 ] = colors[ b ];
  316. face.vertexColors[ 2 ] = colors[ c ];
  317. }
  318. if ( hasUvs ) {
  319. u1 = uvs[ a * 2 ];
  320. v1 = uvs[ a * 2 + 1 ];
  321. u2 = uvs[ b * 2 ];
  322. v2 = uvs[ b * 2 + 1 ];
  323. u3 = uvs[ c * 2 ];
  324. v3 = uvs[ c * 2 + 1 ];
  325. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  326. }
  327. }
  328. }
  329. };
  330. function vertex ( scope, x, y, z ) {
  331. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  332. };
  333. function f3 ( scope, a, b, c, mi ) {
  334. var face = new THREE.Face3( a, b, c, null, null, mi );
  335. scope.faces.push( face );
  336. return face;
  337. };
  338. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  339. var nax = normals[ na * 3 ],
  340. nay = normals[ na * 3 + 1 ],
  341. naz = normals[ na * 3 + 2 ],
  342. nbx = normals[ nb * 3 ],
  343. nby = normals[ nb * 3 + 1 ],
  344. nbz = normals[ nb * 3 + 2 ],
  345. ncx = normals[ nc * 3 ],
  346. ncy = normals[ nc * 3 + 1 ],
  347. ncz = normals[ nc * 3 + 2 ];
  348. var na = new THREE.Vector3( nax, nay, naz ),
  349. nb = new THREE.Vector3( nbx, nby, nbz ),
  350. nc = new THREE.Vector3( ncx, ncy, ncz );
  351. var face = new THREE.Face3( a, b, c, [ na, nb, nc ], null, mi );
  352. scope.faces.push( face );
  353. return face;
  354. };
  355. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  356. var uv = [];
  357. uv.push( new THREE.UV( u1, v1 ) );
  358. uv.push( new THREE.UV( u2, v2 ) );
  359. uv.push( new THREE.UV( u3, v3 ) );
  360. where.push( uv );
  361. };
  362. Model.prototype = Object.create( THREE.Geometry.prototype );
  363. callback( new Model() );
  364. };