webgl_renderer_pathtracer.html 13 KB

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