webgl_renderer_pathtracer.html 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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://unpkg.com/[email protected]/build/index.module.js",
  43. "three-mesh-bvh": "https://unpkg.com/[email protected]/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 { FullScreenQuad } from 'three/addons/postprocessing/Pass.js';
  55. import { PhysicalPathTracingMaterial, PathTracingRenderer, MaterialReducer, BlurredEnvMapGenerator, PathTracingSceneGenerator, GradientEquirectTexture } from 'three-gpu-pathtracer';
  56. let progressBarDiv, samplesEl;
  57. let camera, scene, renderer, controls, gui;
  58. let pathTracer, sceneInfo, fsQuad, floor;
  59. let delaySamples = 0;
  60. const params = {
  61. enable: true,
  62. toneMapping: true,
  63. pause: false,
  64. tiles: 3,
  65. transparentBackground: false,
  66. resolutionScale: 1,
  67. download: () => {
  68. const link = document.createElement( 'a' );
  69. link.download = 'pathtraced-render.png';
  70. link.href = renderer.domElement.toDataURL().replace( 'image/png', 'image/octet-stream' );
  71. link.click();
  72. },
  73. roughness: 0.15,
  74. metalness: 0.9,
  75. };
  76. init();
  77. render();
  78. function init() {
  79. camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 );
  80. camera.position.set( 150, 200, 250 );
  81. // initialize the renderer
  82. renderer = new THREE.WebGLRenderer( { antialias: true, preserveDrawingBuffer: true, premultipliedAlpha: false } );
  83. renderer.setPixelRatio( window.devicePixelRatio );
  84. renderer.setSize( window.innerWidth, window.innerHeight );
  85. renderer.toneMapping = THREE.ACESFilmicToneMapping;
  86. renderer.setClearColor( 0xdddddd );
  87. document.body.appendChild( renderer.domElement );
  88. // initialize the pathtracer
  89. pathTracer = new PathTracingRenderer( renderer );
  90. pathTracer.alpha = true;
  91. pathTracer.tiles.set( params.tiles, params.tiles );
  92. pathTracer.material = new PhysicalPathTracingMaterial();
  93. pathTracer.material.setDefine( 'FEATURE_MIS', 1 );
  94. const gradientMap = new GradientEquirectTexture();
  95. gradientMap.topColor.set( 0xeeeeee );
  96. gradientMap.bottomColor.set( 0xeaeaea );
  97. gradientMap.update();
  98. pathTracer.material.backgroundMap = gradientMap;
  99. pathTracer.camera = camera;
  100. fsQuad = new FullScreenQuad( new THREE.MeshBasicMaterial( {
  101. map: pathTracer.target.texture,
  102. blending: THREE.CustomBlending
  103. } ) );
  104. // scene
  105. scene = new THREE.Scene();
  106. controls = new OrbitControls( camera, renderer.domElement );
  107. controls.addEventListener( 'change', () => {
  108. delaySamples = 5;
  109. pathTracer.reset();
  110. } );
  111. window.addEventListener( 'resize', onWindowResize );
  112. onWindowResize();
  113. progressBarDiv = document.createElement( 'div' );
  114. progressBarDiv.innerText = 'Loading...';
  115. progressBarDiv.style.fontSize = '3em';
  116. progressBarDiv.style.color = '#888';
  117. progressBarDiv.style.display = 'block';
  118. progressBarDiv.style.position = 'absolute';
  119. progressBarDiv.style.top = '50%';
  120. progressBarDiv.style.width = '100%';
  121. progressBarDiv.style.textAlign = 'center';
  122. // load materials and then the model
  123. createGUI();
  124. loadModel();
  125. }
  126. async function loadModel() {
  127. progressBarDiv.innerText = 'Loading...';
  128. let model = null;
  129. let envMap = null;
  130. updateProgressBar( 0 );
  131. showProgressBar();
  132. // only smooth when not rendering with flat colors to improve processing time
  133. const ldrawPromise =
  134. new LDrawLoader()
  135. .setPath( 'models/ldraw/officialLibrary/' )
  136. .loadAsync( 'models/7140-1-X-wingFighter.mpd_Packed.mpd', onProgress )
  137. .then( function ( legoGroup ) {
  138. legoGroup = LDrawUtils.mergeObject( legoGroup );
  139. legoGroup.rotation.x = Math.PI;
  140. // adjust the materials to use transmission, be a bit shinier
  141. legoGroup.traverse( c => {
  142. if ( c.material ) {
  143. c.material.roughness *= 0.25;
  144. if ( c.material.opacity < 1.0 ) {
  145. const oldMaterial = c.material;
  146. const newMaterial = new THREE.MeshPhysicalMaterial();
  147. newMaterial.opacity = 1.0;
  148. newMaterial.transmission = 1.0;
  149. newMaterial.ior = 1.4;
  150. newMaterial.roughness = oldMaterial.roughness;
  151. newMaterial.metalness = 0.0;
  152. const hsl = {};
  153. oldMaterial.color.getHSL( hsl );
  154. hsl.l = Math.max( hsl.l, 0.35 );
  155. newMaterial.color.setHSL( hsl.h, hsl.s, hsl.l );
  156. c.material = newMaterial;
  157. }
  158. }
  159. } );
  160. model = new THREE.Group();
  161. model.add( legoGroup );
  162. // Convert from LDraw coordinates: rotate 180 degrees around OX
  163. model.updateMatrixWorld();
  164. } )
  165. .catch( onError );
  166. const envMapPromise =
  167. new RGBELoader()
  168. .setPath( 'textures/equirectangular/' )
  169. .loadAsync( 'royal_esplanade_1k.hdr' )
  170. .then( tex => {
  171. const envMapGenerator = new BlurredEnvMapGenerator( renderer );
  172. const blurredEnvMap = envMapGenerator.generate( tex, 0 );
  173. scene.environment = blurredEnvMap;
  174. envMap = blurredEnvMap;
  175. } );
  176. await Promise.all( [ envMapPromise, ldrawPromise ] );
  177. hideProgressBar();
  178. document.body.classList.add( 'checkerboard' );
  179. // Adjust camera
  180. const bbox = new THREE.Box3().setFromObject( model );
  181. const size = bbox.getSize( new THREE.Vector3() );
  182. const radius = Math.max( size.x, Math.max( size.y, size.z ) ) * 0.4;
  183. controls.target0.copy( bbox.getCenter( new THREE.Vector3() ) );
  184. controls.position0.set( 2.3, 1, 2 ).multiplyScalar( radius ).add( controls.target0 );
  185. controls.reset();
  186. // add floor
  187. floor = new THREE.Mesh(
  188. new THREE.PlaneGeometry(),
  189. new THREE.MeshStandardMaterial( {
  190. side: THREE.DoubleSide,
  191. roughness: 0.01,
  192. metalness: 1,
  193. map: generateRadialFloorTexture( 1024 ),
  194. transparent: true,
  195. } ),
  196. );
  197. floor.scale.setScalar( 2500 );
  198. floor.rotation.x = - Math.PI / 2;
  199. floor.position.y = bbox.min.y;
  200. model.add( floor );
  201. model.updateMatrixWorld();
  202. // de-duplicate and reduce the number of materials used in place
  203. const reducer = new MaterialReducer();
  204. reducer.process( model );
  205. // reset the progress bar to display bvh generation
  206. progressBarDiv.innerText = 'Generating BVH...';
  207. updateProgressBar( 0 );
  208. const generator = new PathTracingSceneGenerator();
  209. const result = generator.generate( model );
  210. // add the model to the scene
  211. sceneInfo = result;
  212. sceneInfo.scene.traverse( c => {
  213. if ( c.isLineSegments ) {
  214. c.visible = false;
  215. }
  216. } );
  217. scene.add( sceneInfo.scene );
  218. // update the material
  219. const { bvh, textures, materials } = result;
  220. const geometry = bvh.geometry;
  221. const material = pathTracer.material;
  222. material.bvh.updateFrom( bvh );
  223. material.attributesArray.updateFrom(
  224. geometry.attributes.normal,
  225. geometry.attributes.tangent,
  226. geometry.attributes.uv,
  227. geometry.attributes.color,
  228. );
  229. material.materialIndexAttribute.updateFrom( geometry.attributes.materialIndex );
  230. material.textures.setTextures( renderer, 2048, 2048, textures );
  231. material.materials.updateFrom( materials, textures );
  232. pathTracer.material.envMapInfo.updateFrom( envMap );
  233. pathTracer.reset();
  234. }
  235. function onWindowResize() {
  236. const w = window.innerWidth;
  237. const h = window.innerHeight;
  238. const scale = params.resolutionScale;
  239. const dpr = window.devicePixelRatio;
  240. pathTracer.setSize( w * scale * dpr, h * scale * dpr );
  241. pathTracer.reset();
  242. renderer.setSize( w, h );
  243. renderer.setPixelRatio( window.devicePixelRatio * scale );
  244. const aspect = w / h;
  245. camera.aspect = aspect;
  246. camera.updateProjectionMatrix();
  247. }
  248. function createGUI() {
  249. if ( gui ) {
  250. gui.destroy();
  251. }
  252. gui = new GUI();
  253. gui.add( params, 'enable' );
  254. gui.add( params, 'pause' );
  255. gui.add( params, 'toneMapping' );
  256. gui.add( params, 'transparentBackground' ).onChange( v => {
  257. pathTracer.material.backgroundAlpha = v ? 0 : 1;
  258. renderer.setClearAlpha( v ? 0 : 1 );
  259. pathTracer.reset();
  260. } );
  261. gui.add( params, 'resolutionScale', 0.1, 1.0, 0.1 ).onChange( onWindowResize );
  262. gui.add( params, 'tiles', 1, 3, 1 ).onChange( v => {
  263. pathTracer.tiles.set( v, v );
  264. } );
  265. gui.add( params, 'roughness', 0, 1 ).name( 'floor roughness' ).onChange( () => {
  266. pathTracer.reset();
  267. } );
  268. gui.add( params, 'metalness', 0, 1 ).name( 'floor metalness' ).onChange( () => {
  269. pathTracer.reset();
  270. } );
  271. gui.add( params, 'download' ).name( 'download image' );
  272. const renderFolder = gui.addFolder( 'Render' );
  273. samplesEl = document.createElement( 'div' );
  274. samplesEl.classList.add( 'gui-render' );
  275. samplesEl.innerText = 'samples: 0';
  276. renderFolder.$children.appendChild( samplesEl );
  277. renderFolder.open();
  278. }
  279. //
  280. function render() {
  281. requestAnimationFrame( render );
  282. if ( ! sceneInfo ) {
  283. return;
  284. }
  285. renderer.toneMapping = params.toneMapping ? THREE.ACESFilmicToneMapping : THREE.NoToneMapping;
  286. if ( pathTracer.samples < 1.0 || ! params.enable ) {
  287. renderer.render( scene, camera );
  288. }
  289. if ( params.enable && delaySamples === 0 ) {
  290. const samples = Math.floor( pathTracer.samples );
  291. samplesEl.innerText = `samples: ${ samples }`;
  292. floor.material.roughness = params.roughness;
  293. floor.material.metalness = params.metalness;
  294. pathTracer.material.materials.updateFrom( sceneInfo.materials, sceneInfo.textures );
  295. pathTracer.material.filterGlossyFactor = 1;
  296. pathTracer.material.physicalCamera.updateFrom( camera );
  297. camera.updateMatrixWorld();
  298. if ( ! params.pause || pathTracer.samples < 1 ) {
  299. pathTracer.update();
  300. }
  301. renderer.autoClear = false;
  302. fsQuad.render( renderer );
  303. renderer.autoClear = true;
  304. } else if ( delaySamples > 0 ) {
  305. delaySamples --;
  306. }
  307. samplesEl.innerText = `samples: ${ Math.floor( pathTracer.samples ) }`;
  308. }
  309. function onProgress( xhr ) {
  310. if ( xhr.lengthComputable ) {
  311. updateProgressBar( xhr.loaded / xhr.total );
  312. console.log( Math.round( xhr.loaded / xhr.total * 100, 2 ) + '% downloaded' );
  313. }
  314. }
  315. function onError( error ) {
  316. const message = 'Error loading model';
  317. progressBarDiv.innerText = message;
  318. console.log( message );
  319. console.error( error );
  320. }
  321. function showProgressBar() {
  322. document.body.appendChild( progressBarDiv );
  323. }
  324. function hideProgressBar() {
  325. document.body.removeChild( progressBarDiv );
  326. }
  327. function updateProgressBar( fraction ) {
  328. progressBarDiv.innerText = 'Loading... ' + Math.round( fraction * 100, 2 ) + '%';
  329. }
  330. function generateRadialFloorTexture( dim ) {
  331. const data = new Uint8Array( dim * dim * 4 );
  332. for ( let x = 0; x < dim; x ++ ) {
  333. for ( let y = 0; y < dim; y ++ ) {
  334. const xNorm = x / ( dim - 1 );
  335. const yNorm = y / ( dim - 1 );
  336. const xCent = 2.0 * ( xNorm - 0.5 );
  337. const yCent = 2.0 * ( yNorm - 0.5 );
  338. let a = Math.max( Math.min( 1.0 - Math.sqrt( xCent ** 2 + yCent ** 2 ), 1.0 ), 0.0 );
  339. a = a ** 1.5;
  340. a = a * 1.5;
  341. a = Math.min( a, 1.0 );
  342. const i = y * dim + x;
  343. data[ i * 4 + 0 ] = 255;
  344. data[ i * 4 + 1 ] = 255;
  345. data[ i * 4 + 2 ] = 255;
  346. data[ i * 4 + 3 ] = a * 255;
  347. }
  348. }
  349. const tex = new THREE.DataTexture( data, dim, dim );
  350. tex.format = THREE.RGBAFormat;
  351. tex.type = THREE.UnsignedByteType;
  352. tex.minFilter = THREE.LinearFilter;
  353. tex.magFilter = THREE.LinearFilter;
  354. tex.wrapS = THREE.RepeatWrapping;
  355. tex.wrapT = THREE.RepeatWrapping;
  356. tex.needsUpdate = true;
  357. return tex;
  358. }
  359. </script>
  360. <!-- LDraw.org CC BY 2.0 Parts Library attribution -->
  361. <div style="display: block; position: absolute; bottom: 8px; left: 8px; width: 160px; padding: 10px; background-color: #F3F7F8;">
  362. <center>
  363. <a href="http://www.ldraw.org"><img style="width: 145px" src="models/ldraw/ldraw_org_logo/Stamp145.png"></a>
  364. <br />
  365. <a href="http://www.ldraw.org/">This software uses the LDraw Parts Library</a>
  366. </center>
  367. </div>
  368. </body>
  369. </html>