webgl_materials_envmaps_parallax.html 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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="http://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. vec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );
  71. vec4 envMapColor = textureCubeUV( envMap, queryVec, 1.0 );
  72. #else
  73. vec4 envMapColor = vec4( 0.0 );
  74. #endif
  75. return PI * envMapColor.rgb * envMapIntensity;
  76. }
  77. // Trowbridge-Reitz distribution to Mip level, following the logic of http://casual-effects.blogspot.ca/2011/08/plausible-environment-lighting-in-two.html
  78. float getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {
  79. float maxMIPLevelScalar = float( maxMIPLevel );
  80. float sigma = PI * roughness * roughness / ( 1.0 + roughness );
  81. float desiredMIPLevel = maxMIPLevelScalar + log2( sigma );
  82. // clamp to allowable LOD ranges.
  83. return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );
  84. }
  85. vec3 getLightProbeIndirectRadiance( /*const in SpecularLightProbe specularLightProbe,*/ const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {
  86. #ifdef ENVMAP_MODE_REFLECTION
  87. vec3 reflectVec = reflect( -viewDir, normal );
  88. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  89. reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );
  90. #else
  91. vec3 reflectVec = refract( -viewDir, normal, refractionRatio );
  92. #endif
  93. reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
  94. float specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );
  95. #ifdef ENVMAP_TYPE_CUBE
  96. #ifdef BOX_PROJECTED_ENV_MAP
  97. reflectVec = parallaxCorrectNormal( reflectVec, cubeMapSize, cubeMapPos );
  98. #endif
  99. vec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );
  100. #ifdef TEXTURE_LOD_EXT
  101. vec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );
  102. #else
  103. vec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );
  104. #endif
  105. envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;
  106. #elif defined( ENVMAP_TYPE_CUBE_UV )
  107. vec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );
  108. vec4 envMapColor = textureCubeUV( envMap, queryReflectVec, roughness );
  109. #elif defined( ENVMAP_TYPE_EQUIREC )
  110. vec2 sampleUV;
  111. sampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;
  112. sampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;
  113. #ifdef TEXTURE_LOD_EXT
  114. vec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );
  115. #else
  116. vec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );
  117. #endif
  118. envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;
  119. #elif defined( ENVMAP_TYPE_SPHERE )
  120. vec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );
  121. #ifdef TEXTURE_LOD_EXT
  122. vec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );
  123. #else
  124. vec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );
  125. #endif
  126. envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;
  127. #endif
  128. return envMapColor.rgb * envMapIntensity;
  129. }
  130. #endif
  131. `;
  132. // scene size
  133. var WIDTH = window.innerWidth;
  134. var HEIGHT = window.innerHeight;
  135. // camera
  136. var VIEW_ANGLE = 45;
  137. var ASPECT = WIDTH / HEIGHT;
  138. var NEAR = 1;
  139. var FAR = 800;
  140. var camera, cubeCamera, scene, renderer;
  141. var cameraControls;
  142. var groundPlane, wallMat;
  143. init();
  144. function init() {
  145. var container = document.getElementById( 'container' );
  146. // renderer
  147. renderer = new THREE.WebGLRenderer( { antialias: true } );
  148. renderer.setPixelRatio( window.devicePixelRatio );
  149. renderer.setSize( WIDTH, HEIGHT );
  150. container.appendChild( renderer.domElement );
  151. // gui controls
  152. var gui = new GUI();
  153. var params = {
  154. 'box projected': true
  155. };
  156. var bpcemGui = gui.add( params, 'box projected' );
  157. bpcemGui.onChange( function ( value ) {
  158. if ( value ) {
  159. groundPlane.material = boxProjectedMat;
  160. } else {
  161. groundPlane.material = defaultMat;
  162. }
  163. render();
  164. } );
  165. // scene
  166. scene = new THREE.Scene();
  167. // camera
  168. camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR );
  169. camera.position.set( 280, 106, - 5 );
  170. cameraControls = new OrbitControls( camera, renderer.domElement );
  171. cameraControls.target.set( 0, - 10, 0 );
  172. cameraControls.maxDistance = 400;
  173. cameraControls.minDistance = 10;
  174. cameraControls.addEventListener( 'change', render );
  175. cameraControls.update();
  176. // cube camera for environment map
  177. cubeCamera = new THREE.CubeCamera( 1, 1000, 512 );
  178. cubeCamera.renderTarget.texture.generateMipmaps = true;
  179. cubeCamera.renderTarget.texture.minFilter = THREE.LinearMipmapLinearFilter;
  180. cubeCamera.renderTarget.texture.mapping = THREE.CubeReflectionMapping;
  181. cubeCamera.position.set( 0, - 100, 0 );
  182. scene.add( cubeCamera );
  183. // ground floor ( with box projected environment mapping )
  184. var loader = new THREE.TextureLoader();
  185. var rMap = loader.load( 'textures/lava/lavatile.jpg' );
  186. rMap.wrapS = THREE.RepeatWrapping;
  187. rMap.wrapT = THREE.RepeatWrapping;
  188. rMap.repeat.set( 2, 1 );
  189. var defaultMat = new THREE.MeshPhysicalMaterial( {
  190. roughness: 1,
  191. envMap: cubeCamera.renderTarget.texture,
  192. roughnessMap: rMap
  193. } );
  194. var boxProjectedMat = new THREE.MeshPhysicalMaterial( {
  195. color: new THREE.Color( '#ffffff' ),
  196. roughness: 1,
  197. envMap: cubeCamera.renderTarget.texture,
  198. roughnessMap: rMap
  199. } );
  200. boxProjectedMat.onBeforeCompile = function ( shader ) {
  201. //these parameters are for the cubeCamera texture
  202. shader.uniforms.cubeMapSize = { value: new THREE.Vector3( 200, 200, 100 ) };
  203. shader.uniforms.cubeMapPos = { value: new THREE.Vector3( 0, - 50, 0 ) };
  204. shader.uniforms.flipEnvMap.value = true;
  205. //replace shader chunks with box projection chunks
  206. shader.vertexShader = 'varying vec3 vWorldPosition;\n' + shader.vertexShader;
  207. shader.vertexShader = shader.vertexShader.replace(
  208. '#include <worldpos_vertex>',
  209. worldposReplace
  210. );
  211. shader.fragmentShader = shader.fragmentShader.replace(
  212. '#include <envmap_physical_pars_fragment>',
  213. envmapPhysicalParsReplace
  214. );
  215. };
  216. groundPlane = new THREE.Mesh( new THREE.PlaneBufferGeometry( 200, 100, 100 ), boxProjectedMat );
  217. groundPlane.rotateX( - Math.PI / 2 );
  218. groundPlane.position.set( 0, - 49, 0 );
  219. scene.add( groundPlane );
  220. // walls
  221. var diffuseTex = loader.load( 'textures/brick_diffuse.jpg', function () {
  222. updateCubeMap();
  223. } );
  224. var bumpTex = loader.load( 'textures/brick_bump.jpg', function () {
  225. updateCubeMap();
  226. } );
  227. wallMat = new THREE.MeshPhysicalMaterial( {
  228. map: diffuseTex,
  229. bumpMap: bumpTex,
  230. bumpScale: 0.3,
  231. } );
  232. var planeGeo = new THREE.PlaneBufferGeometry( 100, 100 );
  233. var planeBack1 = new THREE.Mesh( planeGeo, wallMat );
  234. planeBack1.position.z = - 50;
  235. planeBack1.position.x = - 50;
  236. scene.add( planeBack1 );
  237. var planeBack2 = new THREE.Mesh( planeGeo, wallMat );
  238. planeBack2.position.z = - 50;
  239. planeBack2.position.x = 50;
  240. scene.add( planeBack2 );
  241. var planeFront1 = new THREE.Mesh( planeGeo, wallMat );
  242. planeFront1.position.z = 50;
  243. planeFront1.position.x = - 50;
  244. planeFront1.rotateY( Math.PI );
  245. scene.add( planeFront1 );
  246. var planeFront2 = new THREE.Mesh( planeGeo, wallMat );
  247. planeFront2.position.z = 50;
  248. planeFront2.position.x = 50;
  249. planeFront2.rotateY( Math.PI );
  250. scene.add( planeFront2 );
  251. var planeRight = new THREE.Mesh( planeGeo, wallMat );
  252. planeRight.position.x = 100;
  253. planeRight.rotateY( - Math.PI / 2 );
  254. scene.add( planeRight );
  255. var planeLeft = new THREE.Mesh( planeGeo, wallMat );
  256. planeLeft.position.x = - 100;
  257. planeLeft.rotateY( Math.PI / 2 );
  258. scene.add( planeLeft );
  259. //lights
  260. var width = 50;
  261. var height = 50;
  262. var intensity = 10;
  263. RectAreaLightUniformsLib.init();
  264. var blueRectLight = new THREE.RectAreaLight( 0xf3aaaa, intensity, width, height );
  265. blueRectLight.position.set( 99, 5, 0 );
  266. blueRectLight.lookAt( 0, 5, 0 );
  267. scene.add( blueRectLight );
  268. var blueRectLightHelper = new RectAreaLightHelper( blueRectLight, 0xffffff );
  269. blueRectLight.add( blueRectLightHelper );
  270. var redRectLight = new THREE.RectAreaLight( 0x9aaeff, intensity, width, height );
  271. redRectLight.position.set( - 99, 5, 0 );
  272. redRectLight.lookAt( 0, 5, 0 );
  273. scene.add( redRectLight );
  274. var redRectLightHelper = new RectAreaLightHelper( redRectLight, 0xffffff );
  275. redRectLight.add( redRectLightHelper );
  276. render();
  277. }
  278. function updateCubeMap() {
  279. //disable specular highlights on walls in the environment map
  280. wallMat.roughness = 1;
  281. groundPlane.visible = false;
  282. cubeCamera.position.copy( groundPlane.position );
  283. cubeCamera.update( renderer, scene );
  284. wallMat.roughness = 0.6;
  285. groundPlane.visible = true;
  286. render();
  287. }
  288. function render() {
  289. renderer.render( scene, camera );
  290. }
  291. </script>
  292. </body>
  293. </html>