webgl_renderer_pathtracer.html 12 KB

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