threejs-postprocessing-3dlut.html 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. <script src="resources/threejs/r102/three.js"></script>
  23. <script src="resources/threejs/r102/js/controls/OrbitControls.js"></script>
  24. <script src="resources/threejs/r102/js/loaders/GLTFLoader.js"></script>
  25. <script src="resources/threejs/r102/js/shaders/CopyShader.js"></script>
  26. <script src="resources/threejs/r102/js/postprocessing/EffectComposer.js"></script>
  27. <script src="resources/threejs/r102/js/postprocessing/RenderPass.js"></script>
  28. <script src="resources/threejs/r102/js/postprocessing/ShaderPass.js"></script>
  29. <script src="../3rdparty/dat.gui.min.js"></script>
  30. <script src="resources/lut-reader.js"></script>
  31. <script src="resources/drag-and-drop.js"></script>
  32. <script>
  33. 'use strict';
  34. /* global THREE, dat */
  35. function main() {
  36. const canvas = document.querySelector('#c');
  37. const renderer = new THREE.WebGLRenderer({canvas: canvas});
  38. const fov = 45;
  39. const aspect = 2; // the canvas default
  40. const near = 0.1;
  41. const far = 100;
  42. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  43. camera.position.set(0, 10, 20);
  44. const controls = new THREE.OrbitControls(camera, canvas);
  45. controls.target.set(0, 5, 0);
  46. controls.update();
  47. const lutTextures = [
  48. { name: 'identity', size: 2, filter: true , },
  49. { name: 'identity no filter', size: 2, filter: false, },
  50. { name: 'custom', url: 'resources/images/lut/3dlut-red-only-s16.png' },
  51. { name: 'monochrome', url: 'resources/images/lut/monochrome-s8.png' },
  52. { name: 'sepia', url: 'resources/images/lut/sepia-s8.png' },
  53. { name: 'saturated', url: 'resources/images/lut/saturated-s8.png', },
  54. { name: 'posterize', url: 'resources/images/lut/posterize-s8n.png', },
  55. { name: 'posterize-3-rgb', url: 'resources/images/lut/posterize-3-rgb-s8n.png', },
  56. { name: 'posterize-3-lab', url: 'resources/images/lut/posterize-3-lab-s8n.png', },
  57. { name: 'posterize-4-lab', url: 'resources/images/lut/posterize-4-lab-s8n.png', },
  58. { name: 'posterize-more', url: 'resources/images/lut/posterize-more-s8n.png', },
  59. { name: 'inverse', url: 'resources/images/lut/inverse-s8.png', },
  60. { name: 'color negative', url: 'resources/images/lut/color-negative-s8.png', },
  61. { name: 'high contrast', url: 'resources/images/lut/high-contrast-bw-s8.png', },
  62. { name: 'funky contrast', url: 'resources/images/lut/funky-contrast-s8.png', },
  63. { name: 'nightvision', url: 'resources/images/lut/nightvision-s8.png', },
  64. { name: 'thermal', url: 'resources/images/lut/thermal-s8.png', },
  65. { name: 'b/w', url: 'resources/images/lut/black-white-s8n.png', },
  66. { name: 'hue +60', url: 'resources/images/lut/hue-plus-60-s8.png', },
  67. { name: 'hue +180', url: 'resources/images/lut/hue-plus-180-s8.png', },
  68. { name: 'hue -60', url: 'resources/images/lut/hue-minus-60-s8.png', },
  69. { name: 'red to cyan', url: 'resources/images/lut/red-to-cyan-s8.png' },
  70. { name: 'blues', url: 'resources/images/lut/blues-s8.png' },
  71. { name: 'infrared', url: 'resources/images/lut/infrared-s8.png' },
  72. { name: 'radioactive', url: 'resources/images/lut/radioactive-s8.png' },
  73. { name: 'goolgey', url: 'resources/images/lut/googley-s8.png' },
  74. { name: 'bgy', url: 'resources/images/lut/bgy-s8.png' },
  75. ];
  76. const makeIdentityLutTexture = function() {
  77. const identityLUT = new Uint8Array([
  78. 0, 0, 0, 255, // black
  79. 255, 0, 0, 255, // red
  80. 0, 0, 255, 255, // blue
  81. 255, 0, 255, 255, // magenta
  82. 0, 255, 0, 255, // green
  83. 255, 255, 0, 255, // yellow
  84. 0, 255, 255, 255, // cyan
  85. 255, 255, 255, 255, // white
  86. ]);
  87. return function(filter) {
  88. const texture = new THREE.DataTexture(identityLUT, 4, 2, THREE.RGBAFormat);
  89. texture.minFilter = filter;
  90. texture.magFilter = filter;
  91. texture.needsUpdate = true;
  92. texture.flipY = false;
  93. return texture;
  94. };
  95. }();
  96. const makeLUTTexture = function() {
  97. const imgLoader = new THREE.ImageLoader();
  98. const ctx = document.createElement('canvas').getContext('2d');
  99. return function(info) {
  100. const texture = makeIdentityLutTexture(
  101. info.filter ? THREE.LinearFilter : THREE.NearestFilter);
  102. if (info.url) {
  103. const lutSize = info.size;
  104. // set the size to 2 (the identity size). We'll restore it when the
  105. // image has loaded. This way the code using the lut doesn't have to
  106. // care if the image has loaded or not
  107. info.size = 2;
  108. imgLoader.load(info.url, function(image) {
  109. const width = lutSize * lutSize;
  110. const height = lutSize;
  111. info.size = lutSize;
  112. ctx.canvas.width = width;
  113. ctx.canvas.height = height;
  114. ctx.drawImage(image, 0, 0);
  115. const imageData = ctx.getImageData(0, 0, width, height);
  116. texture.image.data = new Uint8Array(imageData.data.buffer);
  117. texture.image.width = width;
  118. texture.image.height = height;
  119. texture.needsUpdate = true;
  120. });
  121. }
  122. return texture;
  123. };
  124. }();
  125. lutTextures.forEach((info) => {
  126. // if not size set get it from the filename
  127. if (!info.size) {
  128. // assumes filename ends in '-s<num>[n]'
  129. // where <num> is the size of the 3DLUT cube
  130. // and [n] means 'no filtering' or 'nearest'
  131. //
  132. // examples:
  133. // 'foo-s16.png' = size:16, filter: true
  134. // 'bar-s8n.png' = size:8, filter: false
  135. const m = /-s(\d+)(n*)\.[^.]+$/.exec(info.url);
  136. if (m) {
  137. info.size = parseInt(m[1]);
  138. info.filter = info.filter === undefined ? m[2] !== 'n' : info.filter;
  139. }
  140. }
  141. info.texture = makeLUTTexture(info);
  142. });
  143. const lutNameIndexMap = {};
  144. lutTextures.forEach((info, ndx) => {
  145. lutNameIndexMap[info.name] = ndx;
  146. });
  147. const lutSettings = {
  148. lut: lutNameIndexMap.custom,
  149. };
  150. const gui = new dat.GUI({ width: 300 });
  151. gui.add(lutSettings, 'lut', lutNameIndexMap);
  152. const scene = new THREE.Scene();
  153. const sceneBG = new THREE.Scene();
  154. const cameraBG = new THREE.OrthographicCamera(-1, 1, 1, -1, -1, 1);
  155. let bgMesh;
  156. let bgTexture;
  157. {
  158. const loader = new THREE.TextureLoader();
  159. bgTexture = loader.load('resources/images/beach.jpg');
  160. const planeGeo = new THREE.PlaneBufferGeometry(2, 2);
  161. const planeMat = new THREE.MeshBasicMaterial({
  162. map: bgTexture,
  163. depthTest: false,
  164. });
  165. bgMesh = new THREE.Mesh(planeGeo, planeMat);
  166. sceneBG.add(bgMesh);
  167. }
  168. function frameArea(sizeToFitOnScreen, boxSize, boxCenter, camera) {
  169. const halfSizeToFitOnScreen = sizeToFitOnScreen * 0.5;
  170. const halfFovY = THREE.Math.degToRad(camera.fov * .5);
  171. const distance = halfSizeToFitOnScreen / Math.tan(halfFovY);
  172. // compute a unit vector that points in the direction the camera is now
  173. // in the xz plane from the center of the box
  174. const direction = (new THREE.Vector3())
  175. .subVectors(camera.position, boxCenter)
  176. .multiply(new THREE.Vector3(1, 0, 1))
  177. .normalize();
  178. // move the camera to a position distance units way from the center
  179. // in whatever direction the camera was from the center already
  180. camera.position.copy(direction.multiplyScalar(distance).add(boxCenter));
  181. // pick some near and far values for the frustum that
  182. // will contain the box.
  183. camera.near = boxSize / 100;
  184. camera.far = boxSize * 100;
  185. camera.updateProjectionMatrix();
  186. // point the camera to look at the center of the box
  187. camera.lookAt(boxCenter.x, boxCenter.y, boxCenter.z);
  188. }
  189. {
  190. const gltfLoader = new THREE.GLTFLoader();
  191. gltfLoader.load('resources/models/3dbustchallange_submission/scene.gltf', (gltf) => {
  192. const root = gltf.scene;
  193. scene.add(root);
  194. root.updateMatrixWorld();
  195. // compute the box that contains all the stuff
  196. // from root and below
  197. const box = new THREE.Box3().setFromObject(root);
  198. const boxSize = box.getSize(new THREE.Vector3()).length();
  199. const boxCenter = box.getCenter(new THREE.Vector3());
  200. frameArea(boxSize * 0.4, boxSize, boxCenter, camera);
  201. // update the Trackball controls to handle the new size
  202. controls.maxDistance = boxSize * 10;
  203. controls.target.copy(boxCenter);
  204. controls.update();
  205. });
  206. }
  207. const lutShader = {
  208. uniforms: {
  209. tDiffuse: { value: null },
  210. lutMap: { value: null },
  211. lutMapSize: { value: 1, },
  212. },
  213. vertexShader: `
  214. varying vec2 vUv;
  215. void main() {
  216. vUv = uv;
  217. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  218. }
  219. `,
  220. fragmentShader: `
  221. #include <common>
  222. #define FILTER_LUT true
  223. uniform sampler2D tDiffuse;
  224. uniform sampler2D lutMap;
  225. uniform float lutMapSize;
  226. varying vec2 vUv;
  227. vec4 sampleAs3DTexture(sampler2D tex, vec3 texCoord, float size) {
  228. float sliceSize = 1.0 / size; // space of 1 slice
  229. float slicePixelSize = sliceSize / size; // space of 1 pixel
  230. float width = size - 1.0;
  231. float sliceInnerSize = slicePixelSize * width; // space of size pixels
  232. float zSlice0 = floor( texCoord.z * width);
  233. float zSlice1 = min( zSlice0 + 1.0, width);
  234. float xOffset = slicePixelSize * 0.5 + texCoord.x * sliceInnerSize;
  235. float yRange = (texCoord.y * width + 0.5) / size;
  236. float s0 = xOffset + (zSlice0 * sliceSize);
  237. #ifdef FILTER_LUT
  238. float s1 = xOffset + (zSlice1 * sliceSize);
  239. vec4 slice0Color = texture2D(tex, vec2(s0, yRange));
  240. vec4 slice1Color = texture2D(tex, vec2(s1, yRange));
  241. float zOffset = mod(texCoord.z * width, 1.0);
  242. return mix(slice0Color, slice1Color, zOffset);
  243. #else
  244. return texture2D(tex, vec2( s0, yRange));
  245. #endif
  246. }
  247. void main() {
  248. vec4 originalColor = texture2D(tDiffuse, vUv);
  249. gl_FragColor = sampleAs3DTexture(lutMap, originalColor.xyz, lutMapSize);
  250. }
  251. `,
  252. };
  253. const lutNearestShader = {
  254. uniforms: Object.assign( {}, lutShader.uniforms ),
  255. vertexShader: lutShader.vertexShader,
  256. fragmentShader: lutShader.fragmentShader.replace('#define FILTER_LUT', '//'),
  257. };
  258. const effectLUT = new THREE.ShaderPass(lutShader);
  259. effectLUT.renderToScreen = true;
  260. const effectLUTNearest = new THREE.ShaderPass(lutNearestShader);
  261. effectLUTNearest.renderToScreen = true;
  262. const renderModel = new THREE.RenderPass(scene, camera);
  263. renderModel.clear = false; // so we don't clear out the background
  264. const renderBG = new THREE.RenderPass(sceneBG, cameraBG);
  265. const rtParameters = {
  266. minFilter: THREE.LinearFilter,
  267. magFilter: THREE.LinearFilter,
  268. format: THREE.RGBFormat,
  269. };
  270. const composer = new THREE.EffectComposer(renderer, new THREE.WebGLRenderTarget(1, 1, rtParameters));
  271. composer.addPass(renderBG);
  272. composer.addPass(renderModel);
  273. composer.addPass(effectLUT);
  274. composer.addPass(effectLUTNearest);
  275. function resizeRendererToDisplaySize(renderer) {
  276. const canvas = renderer.domElement;
  277. const width = canvas.clientWidth * window.devicePixelRatio | 0;
  278. const height = canvas.clientHeight * window.devicePixelRatio | 0;
  279. const needResize = canvas.width !== width || canvas.height !== height;
  280. if (needResize) {
  281. renderer.setSize(width, height, false);
  282. }
  283. return needResize;
  284. }
  285. let then = 0;
  286. function render(now) {
  287. now *= 0.001; // convert to seconds
  288. const delta = now - then;
  289. then = now;
  290. if (resizeRendererToDisplaySize(renderer)) {
  291. const canvas = renderer.domElement;
  292. const canvasAspect = canvas.clientWidth / canvas.clientHeight;
  293. camera.aspect = canvasAspect;
  294. camera.updateProjectionMatrix();
  295. composer.setSize(canvas.width, canvas.height);
  296. // scale the background plane to keep the image's
  297. // aspect correct.
  298. // Note the image may not have loaded yet.
  299. const imageAspect = bgTexture.image ? bgTexture.image.width / bgTexture.image.height : 1;
  300. const aspect = imageAspect / canvasAspect;
  301. bgMesh.scale.x = aspect > 1 ? aspect : 1;
  302. bgMesh.scale.y = aspect > 1 ? 1 : 1 / aspect;
  303. }
  304. const lutInfo = lutTextures[ lutSettings.lut ];
  305. const effect = lutInfo.filter ? effectLUT : effectLUTNearest;
  306. effectLUT.enabled = lutInfo.filter;
  307. effectLUTNearest.enabled = !lutInfo.filter;
  308. const lutTexture = lutInfo.texture;
  309. effect.uniforms.lutMap.value = lutTexture;
  310. effect.uniforms.lutMapSize.value = lutInfo.size;
  311. composer.render(delta);
  312. requestAnimationFrame(render);
  313. }
  314. requestAnimationFrame(render);
  315. }
  316. main();
  317. </script>
  318. </html>