1
0

webgl_renderer_pathtracer.html 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - three-gpu-pathtracer</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. <link type="text/css" rel="stylesheet" href="main.css">
  8. <style>
  9. body {
  10. color: #444;
  11. background-color: white;
  12. }
  13. a {
  14. color: #fb8c00;
  15. }
  16. .checkerboard {
  17. background-image:
  18. linear-gradient(45deg, #ddd 25%, transparent 25%),
  19. linear-gradient(-45deg, #ddd 25%, transparent 25%),
  20. linear-gradient(45deg, transparent 75%, #ddd 75%),
  21. linear-gradient(-45deg, transparent 75%, #ddd 75%);
  22. background-size: 20px 20px;
  23. background-position: 0 0, 0 10px, 10px -10px, -10px 0px;
  24. }
  25. .lil-gui .gui-render {
  26. line-height: var(--widget-height);
  27. padding: var(--padding);
  28. }
  29. </style>
  30. </head>
  31. <body>
  32. <div id="info">
  33. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> pathtracer - <a href="https://github.com/gkjohnson/three-gpu-pathtracer" target="_blank" rel="noopener">three-gpu-pathtracer</a><br/>
  34. See <a href="https://github.com/gkjohnson/three-gpu-pathtracer" target="_blank" rel="noopener">main project repository</a> for more information and examples on high fidelity path tracing.
  35. </div>
  36. <script type="importmap">
  37. {
  38. "imports": {
  39. "three": "../build/three.module.js",
  40. "three/addons/": "./jsm/",
  41. "three/examples/": "./",
  42. "three-gpu-pathtracer": "https://cdn.jsdelivr.net/npm/three-gpu-pathtracer@0.0.22/build/index.module.js",
  43. "three-mesh-bvh": "https://cdn.jsdelivr.net/npm/three-mesh-bvh@0.7.4/build/index.module.js"
  44. }
  45. }
  46. </script>
  47. <script type="module">
  48. import * as THREE from 'three';
  49. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  50. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  51. import { RGBELoader } from 'three/addons/loaders/RGBELoader.js';
  52. import { LDrawLoader } from 'three/addons/loaders/LDrawLoader.js';
  53. import { LDrawUtils } from 'three/addons/utils/LDrawUtils.js';
  54. import { WebGLPathTracer, BlurredEnvMapGenerator, GradientEquirectTexture } from 'three-gpu-pathtracer';
  55. let progressBarDiv, samplesEl;
  56. let camera, scene, renderer, controls, gui;
  57. let pathTracer, floor, gradientMap;
  58. const params = {
  59. enable: true,
  60. toneMapping: true,
  61. pause: false,
  62. tiles: 3,
  63. transparentBackground: false,
  64. resolutionScale: 1,
  65. download: () => {
  66. const link = document.createElement( 'a' );
  67. link.download = 'pathtraced-render.png';
  68. link.href = renderer.domElement.toDataURL().replace( 'image/png', 'image/octet-stream' );
  69. link.click();
  70. },
  71. roughness: 0.15,
  72. metalness: 0.9,
  73. };
  74. init();
  75. function init() {
  76. camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 );
  77. camera.position.set( 150, 200, 250 );
  78. // initialize the renderer
  79. renderer = new THREE.WebGLRenderer( { antialias: true, alpha: true, preserveDrawingBuffer: true, premultipliedAlpha: false } );
  80. renderer.setPixelRatio( window.devicePixelRatio );
  81. renderer.setSize( window.innerWidth, window.innerHeight );
  82. renderer.toneMapping = THREE.ACESFilmicToneMapping;
  83. document.body.appendChild( renderer.domElement );
  84. gradientMap = new GradientEquirectTexture();
  85. gradientMap.topColor.set( 0xeeeeee );
  86. gradientMap.bottomColor.set( 0xeaeaea );
  87. gradientMap.update();
  88. // initialize the pathtracer
  89. pathTracer = new WebGLPathTracer( renderer );
  90. pathTracer.filterGlossyFactor = 1;
  91. pathTracer.minSamples = 3;
  92. pathTracer.renderScale = params.resolutionScale;
  93. pathTracer.tiles.set( params.tiles, params.tiles );
  94. // scene
  95. scene = new THREE.Scene();
  96. scene.background = gradientMap;
  97. controls = new OrbitControls( camera, renderer.domElement );
  98. controls.addEventListener( 'change', () => {
  99. pathTracer.updateCamera();
  100. } );
  101. window.addEventListener( 'resize', onWindowResize );
  102. onWindowResize();
  103. progressBarDiv = document.createElement( 'div' );
  104. progressBarDiv.innerText = 'Loading...';
  105. progressBarDiv.style.fontSize = '3em';
  106. progressBarDiv.style.color = '#888';
  107. progressBarDiv.style.display = 'block';
  108. progressBarDiv.style.position = 'absolute';
  109. progressBarDiv.style.top = '50%';
  110. progressBarDiv.style.width = '100%';
  111. progressBarDiv.style.textAlign = 'center';
  112. // load materials and then the model
  113. createGUI();
  114. loadModel();
  115. }
  116. async function loadModel() {
  117. progressBarDiv.innerText = 'Loading...';
  118. let model = null;
  119. let environment = null;
  120. updateProgressBar( 0 );
  121. showProgressBar();
  122. // only smooth when not rendering with flat colors to improve processing time
  123. const ldrawPromise =
  124. new LDrawLoader()
  125. .setPath( 'models/ldraw/officialLibrary/' )
  126. .loadAsync( 'models/7140-1-X-wingFighter.mpd_Packed.mpd', onProgress )
  127. .then( function ( legoGroup ) {
  128. // Convert from LDraw coordinates: rotate 180 degrees around OX
  129. legoGroup = LDrawUtils.mergeObject( legoGroup );
  130. legoGroup.rotation.x = Math.PI;
  131. legoGroup.updateMatrixWorld();
  132. model = legoGroup;
  133. legoGroup.traverse( c => {
  134. // hide the line segments
  135. if ( c.isLineSegments ) {
  136. c.visible = false;
  137. }
  138. // adjust the materials to use transmission, be a bit shinier
  139. if ( c.material ) {
  140. c.material.roughness *= 0.25;
  141. if ( c.material.opacity < 1.0 ) {
  142. const oldMaterial = c.material;
  143. const newMaterial = new THREE.MeshPhysicalMaterial();
  144. newMaterial.opacity = 1.0;
  145. newMaterial.transmission = 1.0;
  146. newMaterial.thickness = 1.0;
  147. newMaterial.ior = 1.4;
  148. newMaterial.roughness = oldMaterial.roughness;
  149. newMaterial.metalness = 0.0;
  150. const hsl = {};
  151. oldMaterial.color.getHSL( hsl );
  152. hsl.l = Math.max( hsl.l, 0.35 );
  153. newMaterial.color.setHSL( hsl.h, hsl.s, hsl.l );
  154. c.material = newMaterial;
  155. }
  156. }
  157. } );
  158. } )
  159. .catch( onError );
  160. const envMapPromise =
  161. new RGBELoader()
  162. .setPath( 'textures/equirectangular/' )
  163. .loadAsync( 'royal_esplanade_1k.hdr' )
  164. .then( tex => {
  165. const envMapGenerator = new BlurredEnvMapGenerator( renderer );
  166. const blurredEnvMap = envMapGenerator.generate( tex, 0 );
  167. environment = blurredEnvMap;
  168. } )
  169. .catch( onError );
  170. await Promise.all( [ envMapPromise, ldrawPromise ] );
  171. hideProgressBar();
  172. document.body.classList.add( 'checkerboard' );
  173. // set environment map
  174. scene.environment = environment;
  175. // Adjust camera
  176. const bbox = new THREE.Box3().setFromObject( model );
  177. const size = bbox.getSize( new THREE.Vector3() );
  178. const radius = Math.max( size.x, Math.max( size.y, size.z ) ) * 0.4;
  179. controls.target0.copy( bbox.getCenter( new THREE.Vector3() ) );
  180. controls.position0.set( 2.3, 1, 2 ).multiplyScalar( radius ).add( controls.target0 );
  181. controls.reset();
  182. // add the model
  183. scene.add( model );
  184. // add floor
  185. floor = new THREE.Mesh(
  186. new THREE.PlaneGeometry(),
  187. new THREE.MeshStandardMaterial( {
  188. side: THREE.DoubleSide,
  189. roughness: params.roughness,
  190. metalness: params.metalness,
  191. map: generateRadialFloorTexture( 1024 ),
  192. transparent: true,
  193. } ),
  194. );
  195. floor.scale.setScalar( 2500 );
  196. floor.rotation.x = - Math.PI / 2;
  197. floor.position.y = bbox.min.y;
  198. scene.add( floor );
  199. // reset the progress bar to display bvh generation
  200. progressBarDiv.innerText = 'Generating BVH...';
  201. updateProgressBar( 0 );
  202. pathTracer.setScene( scene, camera );
  203. renderer.setAnimationLoop( animate );
  204. }
  205. function onWindowResize() {
  206. const w = window.innerWidth;
  207. const h = window.innerHeight;
  208. const dpr = window.devicePixelRatio;
  209. renderer.setSize( w, h );
  210. renderer.setPixelRatio( dpr );
  211. const aspect = w / h;
  212. camera.aspect = aspect;
  213. camera.updateProjectionMatrix();
  214. pathTracer.updateCamera();
  215. }
  216. function createGUI() {
  217. if ( gui ) {
  218. gui.destroy();
  219. }
  220. gui = new GUI();
  221. gui.add( params, 'enable' );
  222. gui.add( params, 'pause' );
  223. gui.add( params, 'toneMapping' );
  224. gui.add( params, 'transparentBackground' ).onChange( v => {
  225. scene.background = v ? null : gradientMap;
  226. pathTracer.updateEnvironment();
  227. } );
  228. gui.add( params, 'resolutionScale', 0.1, 1.0, 0.1 ).onChange( v => {
  229. pathTracer.renderScale = v;
  230. pathTracer.reset();
  231. } );
  232. gui.add( params, 'tiles', 1, 6, 1 ).onChange( v => {
  233. pathTracer.tiles.set( v, v );
  234. } );
  235. gui.add( params, 'roughness', 0, 1 ).name( 'floor roughness' ).onChange( v => {
  236. floor.material.roughness = v;
  237. pathTracer.updateMaterials();
  238. } );
  239. gui.add( params, 'metalness', 0, 1 ).name( 'floor metalness' ).onChange( v => {
  240. floor.material.metalness = v;
  241. pathTracer.updateMaterials();
  242. } );
  243. gui.add( params, 'download' ).name( 'download image' );
  244. const renderFolder = gui.addFolder( 'Render' );
  245. samplesEl = document.createElement( 'div' );
  246. samplesEl.classList.add( 'gui-render' );
  247. samplesEl.innerText = 'samples: 0';
  248. renderFolder.$children.appendChild( samplesEl );
  249. renderFolder.open();
  250. }
  251. //
  252. function animate() {
  253. renderer.toneMapping = params.toneMapping ? THREE.ACESFilmicToneMapping : THREE.NoToneMapping;
  254. const samples = Math.floor( pathTracer.samples );
  255. samplesEl.innerText = `samples: ${ samples }`;
  256. pathTracer.enablePathTracing = params.enable;
  257. pathTracer.pausePathTracing = params.pause;
  258. pathTracer.renderSample();
  259. samplesEl.innerText = `samples: ${ Math.floor( pathTracer.samples ) }`;
  260. }
  261. function onProgress( xhr ) {
  262. if ( xhr.lengthComputable ) {
  263. updateProgressBar( xhr.loaded / xhr.total );
  264. console.log( Math.round( xhr.loaded / xhr.total * 100, 2 ) + '% downloaded' );
  265. }
  266. }
  267. function onError( error ) {
  268. const message = 'Error loading model';
  269. progressBarDiv.innerText = message;
  270. console.log( message );
  271. console.error( error );
  272. }
  273. function showProgressBar() {
  274. document.body.appendChild( progressBarDiv );
  275. }
  276. function hideProgressBar() {
  277. document.body.removeChild( progressBarDiv );
  278. }
  279. function updateProgressBar( fraction ) {
  280. progressBarDiv.innerText = 'Loading... ' + Math.round( fraction * 100, 2 ) + '%';
  281. }
  282. function generateRadialFloorTexture( dim ) {
  283. const data = new Uint8Array( dim * dim * 4 );
  284. for ( let x = 0; x < dim; x ++ ) {
  285. for ( let y = 0; y < dim; y ++ ) {
  286. const xNorm = x / ( dim - 1 );
  287. const yNorm = y / ( dim - 1 );
  288. const xCent = 2.0 * ( xNorm - 0.5 );
  289. const yCent = 2.0 * ( yNorm - 0.5 );
  290. let a = Math.max( Math.min( 1.0 - Math.sqrt( xCent ** 2 + yCent ** 2 ), 1.0 ), 0.0 );
  291. a = a ** 1.5;
  292. a = a * 1.5;
  293. a = Math.min( a, 1.0 );
  294. const i = y * dim + x;
  295. data[ i * 4 + 0 ] = 255;
  296. data[ i * 4 + 1 ] = 255;
  297. data[ i * 4 + 2 ] = 255;
  298. data[ i * 4 + 3 ] = a * 255;
  299. }
  300. }
  301. const tex = new THREE.DataTexture( data, dim, dim );
  302. tex.format = THREE.RGBAFormat;
  303. tex.type = THREE.UnsignedByteType;
  304. tex.minFilter = THREE.LinearFilter;
  305. tex.magFilter = THREE.LinearFilter;
  306. tex.wrapS = THREE.RepeatWrapping;
  307. tex.wrapT = THREE.RepeatWrapping;
  308. tex.needsUpdate = true;
  309. return tex;
  310. }
  311. </script>
  312. <!-- LDraw.org CC BY 2.0 Parts Library attribution -->
  313. <div style="display: block; position: absolute; bottom: 8px; left: 8px; width: 160px; padding: 10px; background-color: #F3F7F8;">
  314. <center>
  315. <a href="http://www.ldraw.org"><img style="width: 145px" src="models/ldraw/ldraw_org_logo/Stamp145.png"></a>
  316. <br />
  317. <a href="http://www.ldraw.org/">This software uses the LDraw Parts Library</a>
  318. </center>
  319. </div>
  320. </body>
  321. </html>