webgl_materials_envmaps_parallax.html 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>js webgl - box projected cubemap environment mapping</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. </head>
  9. <body>
  10. <div id="container"></div>
  11. <div id="info">
  12. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - box projected cubemap environment mapping. <br> created by <a href="https://codercat.tk" target="_blank" rel="noopener">codercat</a>
  13. </div>
  14. <script type="module">
  15. import * as THREE from '../build/three.module.js';
  16. import { GUI } from './jsm/libs/dat.gui.module.js';
  17. import { OrbitControls } from './jsm/controls/OrbitControls.js';
  18. import { RectAreaLightHelper } from './jsm/helpers/RectAreaLightHelper.js';
  19. import { RectAreaLightUniformsLib } from './jsm/lights/RectAreaLightUniformsLib.js';
  20. // shader injection for box projected cube environment mapping
  21. var worldposReplace = `
  22. #define BOX_PROJECTED_ENV_MAP
  23. #if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )
  24. vec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );
  25. #ifdef BOX_PROJECTED_ENV_MAP
  26. vWorldPosition = worldPosition.xyz;
  27. #endif
  28. #endif
  29. `;
  30. var envmapPhysicalParsReplace = `
  31. #if defined( USE_ENVMAP )
  32. #define BOX_PROJECTED_ENV_MAP
  33. #ifdef BOX_PROJECTED_ENV_MAP
  34. uniform vec3 cubeMapSize;
  35. uniform vec3 cubeMapPos;
  36. varying vec3 vWorldPosition;
  37. vec3 parallaxCorrectNormal( vec3 v, vec3 cubeSize, vec3 cubePos ) {
  38. vec3 nDir = normalize( v );
  39. vec3 rbmax = ( .5 * cubeSize + cubePos - vWorldPosition ) / nDir;
  40. vec3 rbmin = ( -.5 * cubeSize + cubePos - vWorldPosition ) / nDir;
  41. vec3 rbminmax;
  42. rbminmax.x = ( nDir.x > 0. ) ? rbmax.x : rbmin.x;
  43. rbminmax.y = ( nDir.y > 0. ) ? rbmax.y : rbmin.y;
  44. rbminmax.z = ( nDir.z > 0. ) ? rbmax.z : rbmin.z;
  45. float correction = min( min( rbminmax.x, rbminmax.y ), rbminmax.z );
  46. vec3 boxIntersection = vWorldPosition + nDir * correction;
  47. return boxIntersection - cubePos;
  48. }
  49. #endif
  50. #ifdef ENVMAP_MODE_REFRACTION
  51. uniform float refractionRatio;
  52. #endif
  53. vec3 getLightProbeIndirectIrradiance( /*const in SpecularLightProbe specularLightProbe,*/ const in GeometricContext geometry, const in int maxMIPLevel ) {
  54. vec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );
  55. #ifdef ENVMAP_TYPE_CUBE
  56. #ifdef BOX_PROJECTED_ENV_MAP
  57. worldNormal = parallaxCorrectNormal( worldNormal, cubeMapSize, cubeMapPos );
  58. #endif
  59. vec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );
  60. // TODO: replace with properly filtered cubemaps and access the irradiance LOD level, be it the last LOD level
  61. // of a specular cubemap, or just the default level of a specially created irradiance cubemap.
  62. #ifdef TEXTURE_LOD_EXT
  63. vec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );
  64. #else
  65. // force the bias high to get the last LOD level as it is the most blurred.
  66. vec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );
  67. #endif
  68. envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;
  69. #elif defined( ENVMAP_TYPE_CUBE_UV )
  70. vec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );
  71. #else
  72. vec4 envMapColor = vec4( 0.0 );
  73. #endif
  74. return PI * envMapColor.rgb * envMapIntensity;
  75. }
  76. // Trowbridge-Reitz distribution to Mip level, following the logic of http://casual-effects.blogspot.ca/2011/08/plausible-environment-lighting-in-two.html
  77. float getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {
  78. float maxMIPLevelScalar = float( maxMIPLevel );
  79. float sigma = PI * roughness * roughness / ( 1.0 + roughness );
  80. float desiredMIPLevel = maxMIPLevelScalar + log2( sigma );
  81. // clamp to allowable LOD ranges.
  82. return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );
  83. }
  84. vec3 getLightProbeIndirectRadiance( /*const in SpecularLightProbe specularLightProbe,*/ const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {
  85. #ifdef ENVMAP_MODE_REFLECTION
  86. vec3 reflectVec = reflect( -viewDir, normal );
  87. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  88. reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );
  89. #else
  90. vec3 reflectVec = refract( -viewDir, normal, refractionRatio );
  91. #endif
  92. reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
  93. float specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );
  94. #ifdef ENVMAP_TYPE_CUBE
  95. #ifdef BOX_PROJECTED_ENV_MAP
  96. reflectVec = parallaxCorrectNormal( reflectVec, cubeMapSize, cubeMapPos );
  97. #endif
  98. vec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );
  99. #ifdef TEXTURE_LOD_EXT
  100. vec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );
  101. #else
  102. vec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );
  103. #endif
  104. envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;
  105. #elif defined( ENVMAP_TYPE_CUBE_UV )
  106. vec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );
  107. #elif defined( ENVMAP_TYPE_EQUIREC )
  108. vec2 sampleUV = equirectUv( reflectVec );
  109. #ifdef TEXTURE_LOD_EXT
  110. vec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );
  111. #else
  112. vec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );
  113. #endif
  114. envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;
  115. #endif
  116. return envMapColor.rgb * envMapIntensity;
  117. }
  118. #endif
  119. `;
  120. // scene size
  121. var WIDTH = window.innerWidth;
  122. var HEIGHT = window.innerHeight;
  123. // camera
  124. var VIEW_ANGLE = 45;
  125. var ASPECT = WIDTH / HEIGHT;
  126. var NEAR = 1;
  127. var FAR = 800;
  128. var camera, cubeCamera, scene, renderer;
  129. var cameraControls;
  130. var groundPlane, wallMat;
  131. init();
  132. function init() {
  133. var container = document.getElementById( 'container' );
  134. // renderer
  135. renderer = new THREE.WebGLRenderer( { antialias: true } );
  136. renderer.setPixelRatio( window.devicePixelRatio );
  137. renderer.setSize( WIDTH, HEIGHT );
  138. container.appendChild( renderer.domElement );
  139. // gui controls
  140. var gui = new GUI();
  141. var params = {
  142. 'box projected': true
  143. };
  144. var bpcemGui = gui.add( params, 'box projected' );
  145. bpcemGui.onChange( function ( value ) {
  146. if ( value ) {
  147. groundPlane.material = boxProjectedMat;
  148. } else {
  149. groundPlane.material = defaultMat;
  150. }
  151. render();
  152. } );
  153. // scene
  154. scene = new THREE.Scene();
  155. // camera
  156. camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR );
  157. camera.position.set( 280, 106, - 5 );
  158. cameraControls = new OrbitControls( camera, renderer.domElement );
  159. cameraControls.target.set( 0, - 10, 0 );
  160. cameraControls.maxDistance = 400;
  161. cameraControls.minDistance = 10;
  162. cameraControls.addEventListener( 'change', render );
  163. cameraControls.update();
  164. // cube camera for environment map
  165. var cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 512, {
  166. format: THREE.RGBFormat,
  167. generateMipmaps: true,
  168. minFilter: THREE.LinearMipmapLinearFilter
  169. } );
  170. cubeCamera = new THREE.CubeCamera( 1, 1000, cubeRenderTarget );
  171. cubeCamera.position.set( 0, - 100, 0 );
  172. scene.add( cubeCamera );
  173. // ground floor ( with box projected environment mapping )
  174. var loader = new THREE.TextureLoader();
  175. var rMap = loader.load( 'textures/lava/lavatile.jpg' );
  176. rMap.wrapS = THREE.RepeatWrapping;
  177. rMap.wrapT = THREE.RepeatWrapping;
  178. rMap.repeat.set( 2, 1 );
  179. var defaultMat = new THREE.MeshPhysicalMaterial( {
  180. roughness: 1,
  181. envMap: cubeRenderTarget.texture,
  182. roughnessMap: rMap
  183. } );
  184. var boxProjectedMat = new THREE.MeshPhysicalMaterial( {
  185. color: new THREE.Color( '#ffffff' ),
  186. roughness: 1,
  187. envMap: cubeRenderTarget.texture,
  188. roughnessMap: rMap
  189. } );
  190. boxProjectedMat.onBeforeCompile = function ( shader ) {
  191. //these parameters are for the cubeCamera texture
  192. shader.uniforms.cubeMapSize = { value: new THREE.Vector3( 200, 200, 100 ) };
  193. shader.uniforms.cubeMapPos = { value: new THREE.Vector3( 0, - 50, 0 ) };
  194. //replace shader chunks with box projection chunks
  195. shader.vertexShader = 'varying vec3 vWorldPosition;\n' + shader.vertexShader;
  196. shader.vertexShader = shader.vertexShader.replace(
  197. '#include <worldpos_vertex>',
  198. worldposReplace
  199. );
  200. shader.fragmentShader = shader.fragmentShader.replace(
  201. '#include <envmap_physical_pars_fragment>',
  202. envmapPhysicalParsReplace
  203. );
  204. };
  205. groundPlane = new THREE.Mesh( new THREE.PlaneBufferGeometry( 200, 100, 100 ), boxProjectedMat );
  206. groundPlane.rotateX( - Math.PI / 2 );
  207. groundPlane.position.set( 0, - 49, 0 );
  208. scene.add( groundPlane );
  209. // walls
  210. var diffuseTex = loader.load( 'textures/brick_diffuse.jpg', function () {
  211. updateCubeMap();
  212. } );
  213. var bumpTex = loader.load( 'textures/brick_bump.jpg', function () {
  214. updateCubeMap();
  215. } );
  216. wallMat = new THREE.MeshPhysicalMaterial( {
  217. map: diffuseTex,
  218. bumpMap: bumpTex,
  219. bumpScale: 0.3,
  220. } );
  221. var planeGeo = new THREE.PlaneBufferGeometry( 100, 100 );
  222. var planeBack1 = new THREE.Mesh( planeGeo, wallMat );
  223. planeBack1.position.z = - 50;
  224. planeBack1.position.x = - 50;
  225. scene.add( planeBack1 );
  226. var planeBack2 = new THREE.Mesh( planeGeo, wallMat );
  227. planeBack2.position.z = - 50;
  228. planeBack2.position.x = 50;
  229. scene.add( planeBack2 );
  230. var planeFront1 = new THREE.Mesh( planeGeo, wallMat );
  231. planeFront1.position.z = 50;
  232. planeFront1.position.x = - 50;
  233. planeFront1.rotateY( Math.PI );
  234. scene.add( planeFront1 );
  235. var planeFront2 = new THREE.Mesh( planeGeo, wallMat );
  236. planeFront2.position.z = 50;
  237. planeFront2.position.x = 50;
  238. planeFront2.rotateY( Math.PI );
  239. scene.add( planeFront2 );
  240. var planeRight = new THREE.Mesh( planeGeo, wallMat );
  241. planeRight.position.x = 100;
  242. planeRight.rotateY( - Math.PI / 2 );
  243. scene.add( planeRight );
  244. var planeLeft = new THREE.Mesh( planeGeo, wallMat );
  245. planeLeft.position.x = - 100;
  246. planeLeft.rotateY( Math.PI / 2 );
  247. scene.add( planeLeft );
  248. //lights
  249. var width = 50;
  250. var height = 50;
  251. var intensity = 10;
  252. RectAreaLightUniformsLib.init();
  253. var blueRectLight = new THREE.RectAreaLight( 0xf3aaaa, intensity, width, height );
  254. blueRectLight.position.set( 99, 5, 0 );
  255. blueRectLight.lookAt( 0, 5, 0 );
  256. scene.add( blueRectLight );
  257. var blueRectLightHelper = new RectAreaLightHelper( blueRectLight, 0xffffff );
  258. blueRectLight.add( blueRectLightHelper );
  259. var redRectLight = new THREE.RectAreaLight( 0x9aaeff, intensity, width, height );
  260. redRectLight.position.set( - 99, 5, 0 );
  261. redRectLight.lookAt( 0, 5, 0 );
  262. scene.add( redRectLight );
  263. var redRectLightHelper = new RectAreaLightHelper( redRectLight, 0xffffff );
  264. redRectLight.add( redRectLightHelper );
  265. render();
  266. }
  267. function updateCubeMap() {
  268. //disable specular highlights on walls in the environment map
  269. wallMat.roughness = 1;
  270. groundPlane.visible = false;
  271. cubeCamera.position.copy( groundPlane.position );
  272. cubeCamera.update( renderer, scene );
  273. wallMat.roughness = 0.6;
  274. groundPlane.visible = true;
  275. render();
  276. }
  277. function render() {
  278. renderer.render( scene, camera );
  279. }
  280. </script>
  281. </body>
  282. </html>