postprocessing-3dlut-identity.html 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>Three.js - postprocessing - 3DLUT</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <style>
  8. html, body {
  9. margin: 0;
  10. height: 100%;
  11. }
  12. #c {
  13. width: 100%;
  14. height: 100%;
  15. display: block;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <canvas id="c"></canvas>
  21. </body>
  22. <!-- Import maps polyfill -->
  23. <!-- Remove this when import maps will be widely supported -->
  24. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  25. <script type="importmap">
  26. {
  27. "imports": {
  28. "three": "../../build/three.module.js",
  29. "three/addons/": "../../examples/jsm/"
  30. }
  31. }
  32. </script>
  33. <script type="module">
  34. import * as THREE from 'three';
  35. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  36. import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
  37. import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
  38. import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
  39. import { ShaderPass } from 'three/addons/postprocessing/ShaderPass.js';
  40. import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
  41. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  42. function main() {
  43. const canvas = document.querySelector( '#c' );
  44. const renderer = new THREE.WebGLRenderer( { antialias: true, canvas } );
  45. const fov = 45;
  46. const aspect = 2; // the canvas default
  47. const near = 0.1;
  48. const far = 100;
  49. const camera = new THREE.PerspectiveCamera( fov, aspect, near, far );
  50. camera.position.set( 0, 10, 20 );
  51. const controls = new OrbitControls( camera, canvas );
  52. controls.target.set( 0, 5, 0 );
  53. controls.update();
  54. const makeIdentityLutTexture = function () {
  55. const identityLUT = new Uint8Array( [
  56. 0, 0, 0, 255, // black
  57. 255, 0, 0, 255, // red
  58. 0, 0, 255, 255, // blue
  59. 255, 0, 255, 255, // magenta
  60. 0, 255, 0, 255, // green
  61. 255, 255, 0, 255, // yellow
  62. 0, 255, 255, 255, // cyan
  63. 255, 255, 255, 255, // white
  64. ] );
  65. return function ( filter ) {
  66. const texture = new THREE.DataTexture( identityLUT, 4, 2 );
  67. texture.minFilter = filter;
  68. texture.magFilter = filter;
  69. texture.needsUpdate = true;
  70. texture.flipY = false;
  71. return texture;
  72. };
  73. }();
  74. const lutTextures = [
  75. {
  76. name: 'identity',
  77. size: 2,
  78. filter: true,
  79. texture: makeIdentityLutTexture( THREE.LinearFilter ),
  80. },
  81. {
  82. name: 'identity not filtered',
  83. size: 2,
  84. filter: false,
  85. texture: makeIdentityLutTexture( THREE.NearestFilter ),
  86. },
  87. ];
  88. const lutNameIndexMap = {};
  89. lutTextures.forEach( ( info, ndx ) => {
  90. lutNameIndexMap[ info.name ] = ndx;
  91. } );
  92. const lutSettings = {
  93. lut: lutNameIndexMap.identity,
  94. };
  95. const gui = new GUI( { width: 300 } );
  96. gui.add( lutSettings, 'lut', lutNameIndexMap );
  97. const scene = new THREE.Scene();
  98. const sceneBG = new THREE.Scene();
  99. const cameraBG = new THREE.OrthographicCamera( - 1, 1, 1, - 1, - 1, 1 );
  100. let bgMesh;
  101. let bgTexture;
  102. {
  103. const loader = new THREE.TextureLoader();
  104. bgTexture = loader.load( 'resources/images/beach.jpg' );
  105. bgTexture.colorSpace = THREE.SRGBColorSpace;
  106. const planeGeo = new THREE.PlaneGeometry( 2, 2 );
  107. const planeMat = new THREE.MeshBasicMaterial( {
  108. map: bgTexture,
  109. depthTest: false,
  110. } );
  111. bgMesh = new THREE.Mesh( planeGeo, planeMat );
  112. sceneBG.add( bgMesh );
  113. }
  114. function frameArea( sizeToFitOnScreen, boxSize, boxCenter, camera ) {
  115. const halfSizeToFitOnScreen = sizeToFitOnScreen * 0.5;
  116. const halfFovY = THREE.MathUtils.degToRad( camera.fov * .5 );
  117. const distance = halfSizeToFitOnScreen / Math.tan( halfFovY );
  118. // compute a unit vector that points in the direction the camera is now
  119. // in the xz plane from the center of the box
  120. const direction = ( new THREE.Vector3() )
  121. .subVectors( camera.position, boxCenter )
  122. .multiply( new THREE.Vector3( 1, 0, 1 ) )
  123. .normalize();
  124. // move the camera to a position distance units way from the center
  125. // in whatever direction the camera was from the center already
  126. camera.position.copy( direction.multiplyScalar( distance ).add( boxCenter ) );
  127. // pick some near and far values for the frustum that
  128. // will contain the box.
  129. camera.near = boxSize / 100;
  130. camera.far = boxSize * 100;
  131. camera.updateProjectionMatrix();
  132. // point the camera to look at the center of the box
  133. camera.lookAt( boxCenter.x, boxCenter.y, boxCenter.z );
  134. }
  135. {
  136. const gltfLoader = new GLTFLoader();
  137. gltfLoader.load( 'resources/models/3dbustchallange_submission/scene.gltf', ( gltf ) => {
  138. const root = gltf.scene;
  139. scene.add( root );
  140. // fix materials from r114
  141. root.traverse( ( { material } ) => {
  142. if ( material ) {
  143. material.depthWrite = true;
  144. }
  145. } );
  146. root.updateMatrixWorld();
  147. // compute the box that contains all the stuff
  148. // from root and below
  149. const box = new THREE.Box3().setFromObject( root );
  150. const boxSize = box.getSize( new THREE.Vector3() ).length();
  151. const boxCenter = box.getCenter( new THREE.Vector3() );
  152. frameArea( boxSize * 0.4, boxSize, boxCenter, camera );
  153. // update the Trackball controls to handle the new size
  154. controls.maxDistance = boxSize * 10;
  155. controls.target.copy( boxCenter );
  156. controls.update();
  157. } );
  158. }
  159. const lutShader = {
  160. uniforms: {
  161. tDiffuse: { value: null }, // the previous pass's result
  162. lutMap: { value: null },
  163. lutMapSize: { value: 1, },
  164. },
  165. vertexShader: `
  166. varying vec2 vUv;
  167. void main() {
  168. vUv = uv;
  169. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  170. }
  171. `,
  172. fragmentShader: `
  173. #include <common>
  174. #define FILTER_LUT true
  175. uniform sampler2D tDiffuse;
  176. uniform sampler2D lutMap;
  177. uniform float lutMapSize;
  178. varying vec2 vUv;
  179. vec4 sampleAs3DTexture(sampler2D tex, vec3 texCoord, float size) {
  180. float sliceSize = 1.0 / size; // space of 1 slice
  181. float slicePixelSize = sliceSize / size; // space of 1 pixel
  182. float width = size - 1.0;
  183. float sliceInnerSize = slicePixelSize * width; // space of size pixels
  184. float zSlice0 = floor( texCoord.z * width);
  185. float zSlice1 = min( zSlice0 + 1.0, width);
  186. float xOffset = slicePixelSize * 0.5 + texCoord.x * sliceInnerSize;
  187. float yRange = (texCoord.y * width + 0.5) / size;
  188. float s0 = xOffset + (zSlice0 * sliceSize);
  189. #ifdef FILTER_LUT
  190. float s1 = xOffset + (zSlice1 * sliceSize);
  191. vec4 slice0Color = texture2D(tex, vec2(s0, yRange));
  192. vec4 slice1Color = texture2D(tex, vec2(s1, yRange));
  193. float zOffset = mod(texCoord.z * width, 1.0);
  194. return mix(slice0Color, slice1Color, zOffset);
  195. #else
  196. return texture2D(tex, vec2( s0, yRange));
  197. #endif
  198. }
  199. void main() {
  200. vec4 originalColor = texture2D(tDiffuse, vUv);
  201. gl_FragColor = sampleAs3DTexture(lutMap, originalColor.xyz, lutMapSize);
  202. }
  203. `,
  204. };
  205. const lutNearestShader = {
  206. uniforms: { ...lutShader.uniforms },
  207. vertexShader: lutShader.vertexShader,
  208. fragmentShader: lutShader.fragmentShader.replace( '#define FILTER_LUT', '//' ),
  209. };
  210. const effectLUT = new ShaderPass( lutShader );
  211. const effectLUTNearest = new ShaderPass( lutNearestShader );
  212. const renderModel = new RenderPass( scene, camera );
  213. renderModel.clear = false; // so we don't clear out the background
  214. const renderBG = new RenderPass( sceneBG, cameraBG );
  215. const outputPass = new OutputPass();
  216. const composer = new EffectComposer( renderer );
  217. composer.addPass( renderBG );
  218. composer.addPass( renderModel );
  219. composer.addPass( effectLUT );
  220. composer.addPass( effectLUTNearest );
  221. composer.addPass( outputPass );
  222. function resizeRendererToDisplaySize( renderer ) {
  223. const canvas = renderer.domElement;
  224. const width = canvas.clientWidth * window.devicePixelRatio | 0;
  225. const height = canvas.clientHeight * window.devicePixelRatio | 0;
  226. const needResize = canvas.width !== width || canvas.height !== height;
  227. if ( needResize ) {
  228. renderer.setSize( width, height, false );
  229. }
  230. return needResize;
  231. }
  232. let then = 0;
  233. function render( now ) {
  234. now *= 0.001; // convert to seconds
  235. const delta = now - then;
  236. then = now;
  237. if ( resizeRendererToDisplaySize( renderer ) ) {
  238. const canvas = renderer.domElement;
  239. const canvasAspect = canvas.clientWidth / canvas.clientHeight;
  240. camera.aspect = canvasAspect;
  241. camera.updateProjectionMatrix();
  242. composer.setSize( canvas.width, canvas.height );
  243. // scale the background plane to keep the image's
  244. // aspect correct.
  245. // Note the image may not have loaded yet.
  246. const imageAspect = bgTexture.image ? bgTexture.image.width / bgTexture.image.height : 1;
  247. const aspect = imageAspect / canvasAspect;
  248. bgMesh.scale.x = aspect > 1 ? aspect : 1;
  249. bgMesh.scale.y = aspect > 1 ? 1 : 1 / aspect;
  250. }
  251. const lutInfo = lutTextures[ lutSettings.lut ];
  252. const effect = lutInfo.filter ? effectLUT : effectLUTNearest;
  253. effectLUT.enabled = lutInfo.filter;
  254. effectLUTNearest.enabled = ! lutInfo.filter;
  255. const lutTexture = lutInfo.texture;
  256. effect.uniforms.lutMap.value = lutTexture;
  257. effect.uniforms.lutMapSize.value = lutInfo.size;
  258. composer.render( delta );
  259. requestAnimationFrame( render );
  260. }
  261. requestAnimationFrame( render );
  262. }
  263. main();
  264. </script>
  265. </html>