GeometryCompressionUtils.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. ( function () {
  2. /**
  3. * Octahedron and Quantization encodings based on work by:
  4. *
  5. * @link https://github.com/tsherif/mesh-quantization-example
  6. *
  7. */
  8. /**
  9. * Make the input mesh.geometry's normal attribute encoded and compressed by 3 different methods.
  10. * Also will change the mesh.material to `PackedPhongMaterial` which let the vertex shader program decode the normal data.
  11. *
  12. * @param {THREE.Mesh} mesh
  13. * @param {String} encodeMethod "DEFAULT" || "OCT1Byte" || "OCT2Byte" || "ANGLES"
  14. *
  15. */
  16. function compressNormals( mesh, encodeMethod ) {
  17. if ( ! mesh.geometry ) {
  18. console.error( 'Mesh must contain geometry. ' );
  19. }
  20. const normal = mesh.geometry.attributes.normal;
  21. if ( ! normal ) {
  22. console.error( 'Geometry must contain normal attribute. ' );
  23. }
  24. if ( normal.isPacked ) return;
  25. if ( normal.itemSize != 3 ) {
  26. console.error( 'normal.itemSize is not 3, which cannot be encoded. ' );
  27. }
  28. const array = normal.array;
  29. const count = normal.count;
  30. let result;
  31. if ( encodeMethod == 'DEFAULT' ) {
  32. // TODO: Add 1 byte to the result, making the encoded length to be 4 bytes.
  33. result = new Uint8Array( count * 3 );
  34. for ( let idx = 0; idx < array.length; idx += 3 ) {
  35. const encoded = defaultEncode( array[ idx ], array[ idx + 1 ], array[ idx + 2 ], 1 );
  36. result[ idx + 0 ] = encoded[ 0 ];
  37. result[ idx + 1 ] = encoded[ 1 ];
  38. result[ idx + 2 ] = encoded[ 2 ];
  39. }
  40. mesh.geometry.setAttribute( 'normal', new THREE.BufferAttribute( result, 3, true ) );
  41. mesh.geometry.attributes.normal.bytes = result.length * 1;
  42. } else if ( encodeMethod == 'OCT1Byte' ) {
  43. /**
  44. * It is not recommended to use 1-byte octahedron normals encoding unless you want to extremely reduce the memory usage
  45. * As it makes vertex data not aligned to a 4 byte boundary which may harm some WebGL implementations and sometimes the normal distortion is visible
  46. * Please refer to @zeux 's comments in https://github.com/mrdoob/three.js/pull/18208
  47. */
  48. result = new Int8Array( count * 2 );
  49. for ( let idx = 0; idx < array.length; idx += 3 ) {
  50. const encoded = octEncodeBest( array[ idx ], array[ idx + 1 ], array[ idx + 2 ], 1 );
  51. result[ idx / 3 * 2 + 0 ] = encoded[ 0 ];
  52. result[ idx / 3 * 2 + 1 ] = encoded[ 1 ];
  53. }
  54. mesh.geometry.setAttribute( 'normal', new THREE.BufferAttribute( result, 2, true ) );
  55. mesh.geometry.attributes.normal.bytes = result.length * 1;
  56. } else if ( encodeMethod == 'OCT2Byte' ) {
  57. result = new Int16Array( count * 2 );
  58. for ( let idx = 0; idx < array.length; idx += 3 ) {
  59. const encoded = octEncodeBest( array[ idx ], array[ idx + 1 ], array[ idx + 2 ], 2 );
  60. result[ idx / 3 * 2 + 0 ] = encoded[ 0 ];
  61. result[ idx / 3 * 2 + 1 ] = encoded[ 1 ];
  62. }
  63. mesh.geometry.setAttribute( 'normal', new THREE.BufferAttribute( result, 2, true ) );
  64. mesh.geometry.attributes.normal.bytes = result.length * 2;
  65. } else if ( encodeMethod == 'ANGLES' ) {
  66. result = new Uint16Array( count * 2 );
  67. for ( let idx = 0; idx < array.length; idx += 3 ) {
  68. const encoded = anglesEncode( array[ idx ], array[ idx + 1 ], array[ idx + 2 ] );
  69. result[ idx / 3 * 2 + 0 ] = encoded[ 0 ];
  70. result[ idx / 3 * 2 + 1 ] = encoded[ 1 ];
  71. }
  72. mesh.geometry.setAttribute( 'normal', new THREE.BufferAttribute( result, 2, true ) );
  73. mesh.geometry.attributes.normal.bytes = result.length * 2;
  74. } else {
  75. console.error( 'Unrecognized encoding method, should be `DEFAULT` or `ANGLES` or `OCT`. ' );
  76. }
  77. mesh.geometry.attributes.normal.needsUpdate = true;
  78. mesh.geometry.attributes.normal.isPacked = true;
  79. mesh.geometry.attributes.normal.packingMethod = encodeMethod;
  80. // modify material
  81. if ( ! ( mesh.material instanceof THREE.PackedPhongMaterial ) ) {
  82. mesh.material = new THREE.PackedPhongMaterial().copy( mesh.material );
  83. }
  84. if ( encodeMethod == 'ANGLES' ) {
  85. mesh.material.defines.USE_PACKED_NORMAL = 0;
  86. }
  87. if ( encodeMethod == 'OCT1Byte' ) {
  88. mesh.material.defines.USE_PACKED_NORMAL = 1;
  89. }
  90. if ( encodeMethod == 'OCT2Byte' ) {
  91. mesh.material.defines.USE_PACKED_NORMAL = 1;
  92. }
  93. if ( encodeMethod == 'DEFAULT' ) {
  94. mesh.material.defines.USE_PACKED_NORMAL = 2;
  95. }
  96. }
  97. /**
  98. * Make the input mesh.geometry's position attribute encoded and compressed.
  99. * Also will change the mesh.material to `PackedPhongMaterial` which let the vertex shader program decode the position data.
  100. *
  101. * @param {THREE.Mesh} mesh
  102. *
  103. */
  104. function compressPositions( mesh ) {
  105. if ( ! mesh.geometry ) {
  106. console.error( 'Mesh must contain geometry. ' );
  107. }
  108. const position = mesh.geometry.attributes.position;
  109. if ( ! position ) {
  110. console.error( 'Geometry must contain position attribute. ' );
  111. }
  112. if ( position.isPacked ) return;
  113. if ( position.itemSize != 3 ) {
  114. console.error( 'position.itemSize is not 3, which cannot be packed. ' );
  115. }
  116. const array = position.array;
  117. const encodingBytes = 2;
  118. const result = quantizedEncode( array, encodingBytes );
  119. const quantized = result.quantized;
  120. const decodeMat = result.decodeMat;
  121. // IMPORTANT: calculate original geometry bounding info first, before updating packed positions
  122. if ( mesh.geometry.boundingBox == null ) mesh.geometry.computeBoundingBox();
  123. if ( mesh.geometry.boundingSphere == null ) mesh.geometry.computeBoundingSphere();
  124. mesh.geometry.setAttribute( 'position', new THREE.BufferAttribute( quantized, 3 ) );
  125. mesh.geometry.attributes.position.isPacked = true;
  126. mesh.geometry.attributes.position.needsUpdate = true;
  127. mesh.geometry.attributes.position.bytes = quantized.length * encodingBytes;
  128. // modify material
  129. if ( ! ( mesh.material instanceof THREE.PackedPhongMaterial ) ) {
  130. mesh.material = new THREE.PackedPhongMaterial().copy( mesh.material );
  131. }
  132. mesh.material.defines.USE_PACKED_POSITION = 0;
  133. mesh.material.uniforms.quantizeMatPos.value = decodeMat;
  134. mesh.material.uniforms.quantizeMatPos.needsUpdate = true;
  135. }
  136. /**
  137. * Make the input mesh.geometry's uv attribute encoded and compressed.
  138. * Also will change the mesh.material to `PackedPhongMaterial` which let the vertex shader program decode the uv data.
  139. *
  140. * @param {THREE.Mesh} mesh
  141. *
  142. */
  143. function compressUvs( mesh ) {
  144. if ( ! mesh.geometry ) {
  145. console.error( 'Mesh must contain geometry property. ' );
  146. }
  147. const uvs = mesh.geometry.attributes.uv;
  148. if ( ! uvs ) {
  149. console.error( 'Geometry must contain uv attribute. ' );
  150. }
  151. if ( uvs.isPacked ) return;
  152. const range = {
  153. min: Infinity,
  154. max: - Infinity
  155. };
  156. const array = uvs.array;
  157. for ( let i = 0; i < array.length; i ++ ) {
  158. range.min = Math.min( range.min, array[ i ] );
  159. range.max = Math.max( range.max, array[ i ] );
  160. }
  161. let result;
  162. if ( range.min >= - 1.0 && range.max <= 1.0 ) {
  163. // use default encoding method
  164. result = new Uint16Array( array.length );
  165. for ( let i = 0; i < array.length; i += 2 ) {
  166. const encoded = defaultEncode( array[ i ], array[ i + 1 ], 0, 2 );
  167. result[ i ] = encoded[ 0 ];
  168. result[ i + 1 ] = encoded[ 1 ];
  169. }
  170. mesh.geometry.setAttribute( 'uv', new THREE.BufferAttribute( result, 2, true ) );
  171. mesh.geometry.attributes.uv.isPacked = true;
  172. mesh.geometry.attributes.uv.needsUpdate = true;
  173. mesh.geometry.attributes.uv.bytes = result.length * 2;
  174. if ( ! ( mesh.material instanceof THREE.PackedPhongMaterial ) ) {
  175. mesh.material = new THREE.PackedPhongMaterial().copy( mesh.material );
  176. }
  177. mesh.material.defines.USE_PACKED_UV = 0;
  178. } else {
  179. // use quantized encoding method
  180. result = quantizedEncodeUV( array, 2 );
  181. mesh.geometry.setAttribute( 'uv', new THREE.BufferAttribute( result.quantized, 2 ) );
  182. mesh.geometry.attributes.uv.isPacked = true;
  183. mesh.geometry.attributes.uv.needsUpdate = true;
  184. mesh.geometry.attributes.uv.bytes = result.quantized.length * 2;
  185. if ( ! ( mesh.material instanceof THREE.PackedPhongMaterial ) ) {
  186. mesh.material = new THREE.PackedPhongMaterial().copy( mesh.material );
  187. }
  188. mesh.material.defines.USE_PACKED_UV = 1;
  189. mesh.material.uniforms.quantizeMatUV.value = result.decodeMat;
  190. mesh.material.uniforms.quantizeMatUV.needsUpdate = true;
  191. }
  192. }
  193. // Encoding functions
  194. function defaultEncode( x, y, z, bytes ) {
  195. if ( bytes == 1 ) {
  196. const tmpx = Math.round( ( x + 1 ) * 0.5 * 255 );
  197. const tmpy = Math.round( ( y + 1 ) * 0.5 * 255 );
  198. const tmpz = Math.round( ( z + 1 ) * 0.5 * 255 );
  199. return new Uint8Array( [ tmpx, tmpy, tmpz ] );
  200. } else if ( bytes == 2 ) {
  201. const tmpx = Math.round( ( x + 1 ) * 0.5 * 65535 );
  202. const tmpy = Math.round( ( y + 1 ) * 0.5 * 65535 );
  203. const tmpz = Math.round( ( z + 1 ) * 0.5 * 65535 );
  204. return new Uint16Array( [ tmpx, tmpy, tmpz ] );
  205. } else {
  206. console.error( 'number of bytes must be 1 or 2' );
  207. }
  208. }
  209. // for `Angles` encoding
  210. function anglesEncode( x, y, z ) {
  211. const normal0 = parseInt( 0.5 * ( 1.0 + Math.atan2( y, x ) / Math.PI ) * 65535 );
  212. const normal1 = parseInt( 0.5 * ( 1.0 + z ) * 65535 );
  213. return new Uint16Array( [ normal0, normal1 ] );
  214. }
  215. // for `Octahedron` encoding
  216. function octEncodeBest( x, y, z, bytes ) {
  217. let oct, dec, best, currentCos, bestCos;
  218. // Test various combinations of ceil and floor
  219. // to minimize rounding errors
  220. best = oct = octEncodeVec3( x, y, z, 'floor', 'floor' );
  221. dec = octDecodeVec2( oct );
  222. bestCos = dot( x, y, z, dec );
  223. oct = octEncodeVec3( x, y, z, 'ceil', 'floor' );
  224. dec = octDecodeVec2( oct );
  225. currentCos = dot( x, y, z, dec );
  226. if ( currentCos > bestCos ) {
  227. best = oct;
  228. bestCos = currentCos;
  229. }
  230. oct = octEncodeVec3( x, y, z, 'floor', 'ceil' );
  231. dec = octDecodeVec2( oct );
  232. currentCos = dot( x, y, z, dec );
  233. if ( currentCos > bestCos ) {
  234. best = oct;
  235. bestCos = currentCos;
  236. }
  237. oct = octEncodeVec3( x, y, z, 'ceil', 'ceil' );
  238. dec = octDecodeVec2( oct );
  239. currentCos = dot( x, y, z, dec );
  240. if ( currentCos > bestCos ) {
  241. best = oct;
  242. }
  243. return best;
  244. function octEncodeVec3( x0, y0, z0, xfunc, yfunc ) {
  245. let x = x0 / ( Math.abs( x0 ) + Math.abs( y0 ) + Math.abs( z0 ) );
  246. let y = y0 / ( Math.abs( x0 ) + Math.abs( y0 ) + Math.abs( z0 ) );
  247. if ( z < 0 ) {
  248. const tempx = ( 1 - Math.abs( y ) ) * ( x >= 0 ? 1 : - 1 );
  249. const tempy = ( 1 - Math.abs( x ) ) * ( y >= 0 ? 1 : - 1 );
  250. x = tempx;
  251. y = tempy;
  252. let diff = 1 - Math.abs( x ) - Math.abs( y );
  253. if ( diff > 0 ) {
  254. diff += 0.001;
  255. x += x > 0 ? diff / 2 : - diff / 2;
  256. y += y > 0 ? diff / 2 : - diff / 2;
  257. }
  258. }
  259. if ( bytes == 1 ) {
  260. return new Int8Array( [ Math[ xfunc ]( x * 127.5 + ( x < 0 ? 1 : 0 ) ), Math[ yfunc ]( y * 127.5 + ( y < 0 ? 1 : 0 ) ) ] );
  261. }
  262. if ( bytes == 2 ) {
  263. return new Int16Array( [ Math[ xfunc ]( x * 32767.5 + ( x < 0 ? 1 : 0 ) ), Math[ yfunc ]( y * 32767.5 + ( y < 0 ? 1 : 0 ) ) ] );
  264. }
  265. }
  266. function octDecodeVec2( oct ) {
  267. let x = oct[ 0 ];
  268. let y = oct[ 1 ];
  269. if ( bytes == 1 ) {
  270. x /= x < 0 ? 127 : 128;
  271. y /= y < 0 ? 127 : 128;
  272. } else if ( bytes == 2 ) {
  273. x /= x < 0 ? 32767 : 32768;
  274. y /= y < 0 ? 32767 : 32768;
  275. }
  276. const z = 1 - Math.abs( x ) - Math.abs( y );
  277. if ( z < 0 ) {
  278. const tmpx = x;
  279. x = ( 1 - Math.abs( y ) ) * ( x >= 0 ? 1 : - 1 );
  280. y = ( 1 - Math.abs( tmpx ) ) * ( y >= 0 ? 1 : - 1 );
  281. }
  282. const length = Math.sqrt( x * x + y * y + z * z );
  283. return [ x / length, y / length, z / length ];
  284. }
  285. function dot( x, y, z, vec3 ) {
  286. return x * vec3[ 0 ] + y * vec3[ 1 ] + z * vec3[ 2 ];
  287. }
  288. }
  289. function quantizedEncode( array, bytes ) {
  290. let quantized, segments;
  291. if ( bytes == 1 ) {
  292. quantized = new Uint8Array( array.length );
  293. segments = 255;
  294. } else if ( bytes == 2 ) {
  295. quantized = new Uint16Array( array.length );
  296. segments = 65535;
  297. } else {
  298. console.error( 'number of bytes error! ' );
  299. }
  300. const decodeMat = new THREE.Matrix4();
  301. const min = new Float32Array( 3 );
  302. const max = new Float32Array( 3 );
  303. min[ 0 ] = min[ 1 ] = min[ 2 ] = Number.MAX_VALUE;
  304. max[ 0 ] = max[ 1 ] = max[ 2 ] = - Number.MAX_VALUE;
  305. for ( let i = 0; i < array.length; i += 3 ) {
  306. min[ 0 ] = Math.min( min[ 0 ], array[ i + 0 ] );
  307. min[ 1 ] = Math.min( min[ 1 ], array[ i + 1 ] );
  308. min[ 2 ] = Math.min( min[ 2 ], array[ i + 2 ] );
  309. max[ 0 ] = Math.max( max[ 0 ], array[ i + 0 ] );
  310. max[ 1 ] = Math.max( max[ 1 ], array[ i + 1 ] );
  311. max[ 2 ] = Math.max( max[ 2 ], array[ i + 2 ] );
  312. }
  313. decodeMat.scale( new THREE.Vector3( ( max[ 0 ] - min[ 0 ] ) / segments, ( max[ 1 ] - min[ 1 ] ) / segments, ( max[ 2 ] - min[ 2 ] ) / segments ) );
  314. decodeMat.elements[ 12 ] = min[ 0 ];
  315. decodeMat.elements[ 13 ] = min[ 1 ];
  316. decodeMat.elements[ 14 ] = min[ 2 ];
  317. decodeMat.transpose();
  318. const multiplier = new Float32Array( [ max[ 0 ] !== min[ 0 ] ? segments / ( max[ 0 ] - min[ 0 ] ) : 0, max[ 1 ] !== min[ 1 ] ? segments / ( max[ 1 ] - min[ 1 ] ) : 0, max[ 2 ] !== min[ 2 ] ? segments / ( max[ 2 ] - min[ 2 ] ) : 0 ] );
  319. for ( let i = 0; i < array.length; i += 3 ) {
  320. quantized[ i + 0 ] = Math.floor( ( array[ i + 0 ] - min[ 0 ] ) * multiplier[ 0 ] );
  321. quantized[ i + 1 ] = Math.floor( ( array[ i + 1 ] - min[ 1 ] ) * multiplier[ 1 ] );
  322. quantized[ i + 2 ] = Math.floor( ( array[ i + 2 ] - min[ 2 ] ) * multiplier[ 2 ] );
  323. }
  324. return {
  325. quantized: quantized,
  326. decodeMat: decodeMat
  327. };
  328. }
  329. function quantizedEncodeUV( array, bytes ) {
  330. let quantized, segments;
  331. if ( bytes == 1 ) {
  332. quantized = new Uint8Array( array.length );
  333. segments = 255;
  334. } else if ( bytes == 2 ) {
  335. quantized = new Uint16Array( array.length );
  336. segments = 65535;
  337. } else {
  338. console.error( 'number of bytes error! ' );
  339. }
  340. const decodeMat = new THREE.Matrix3();
  341. const min = new Float32Array( 2 );
  342. const max = new Float32Array( 2 );
  343. min[ 0 ] = min[ 1 ] = Number.MAX_VALUE;
  344. max[ 0 ] = max[ 1 ] = - Number.MAX_VALUE;
  345. for ( let i = 0; i < array.length; i += 2 ) {
  346. min[ 0 ] = Math.min( min[ 0 ], array[ i + 0 ] );
  347. min[ 1 ] = Math.min( min[ 1 ], array[ i + 1 ] );
  348. max[ 0 ] = Math.max( max[ 0 ], array[ i + 0 ] );
  349. max[ 1 ] = Math.max( max[ 1 ], array[ i + 1 ] );
  350. }
  351. decodeMat.scale( ( max[ 0 ] - min[ 0 ] ) / segments, ( max[ 1 ] - min[ 1 ] ) / segments );
  352. decodeMat.elements[ 6 ] = min[ 0 ];
  353. decodeMat.elements[ 7 ] = min[ 1 ];
  354. decodeMat.transpose();
  355. const multiplier = new Float32Array( [ max[ 0 ] !== min[ 0 ] ? segments / ( max[ 0 ] - min[ 0 ] ) : 0, max[ 1 ] !== min[ 1 ] ? segments / ( max[ 1 ] - min[ 1 ] ) : 0 ] );
  356. for ( let i = 0; i < array.length; i += 2 ) {
  357. quantized[ i + 0 ] = Math.floor( ( array[ i + 0 ] - min[ 0 ] ) * multiplier[ 0 ] );
  358. quantized[ i + 1 ] = Math.floor( ( array[ i + 1 ] - min[ 1 ] ) * multiplier[ 1 ] );
  359. }
  360. return {
  361. quantized: quantized,
  362. decodeMat: decodeMat
  363. };
  364. }
  365. THREE.GeometryCompressionUtils = {};
  366. THREE.GeometryCompressionUtils.compressNormals = compressNormals;
  367. THREE.GeometryCompressionUtils.compressPositions = compressPositions;
  368. THREE.GeometryCompressionUtils.compressUvs = compressUvs;
  369. } )();