postprocessing-3dlut-identity.html 9.5 KB

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