webgl_materials_envmaps_parallax.html 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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;
  109. sampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;
  110. sampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;
  111. #ifdef TEXTURE_LOD_EXT
  112. vec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );
  113. #else
  114. vec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );
  115. #endif
  116. envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;
  117. #elif defined( ENVMAP_TYPE_SPHERE )
  118. vec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );
  119. #ifdef TEXTURE_LOD_EXT
  120. vec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );
  121. #else
  122. vec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );
  123. #endif
  124. envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;
  125. #endif
  126. return envMapColor.rgb * envMapIntensity;
  127. }
  128. #endif
  129. `;
  130. // scene size
  131. var WIDTH = window.innerWidth;
  132. var HEIGHT = window.innerHeight;
  133. // camera
  134. var VIEW_ANGLE = 45;
  135. var ASPECT = WIDTH / HEIGHT;
  136. var NEAR = 1;
  137. var FAR = 800;
  138. var camera, cubeCamera, scene, renderer;
  139. var cameraControls;
  140. var groundPlane, wallMat;
  141. init();
  142. function init() {
  143. var container = document.getElementById( 'container' );
  144. // renderer
  145. renderer = new THREE.WebGLRenderer( { antialias: true } );
  146. renderer.setPixelRatio( window.devicePixelRatio );
  147. renderer.setSize( WIDTH, HEIGHT );
  148. container.appendChild( renderer.domElement );
  149. // gui controls
  150. var gui = new GUI();
  151. var params = {
  152. 'box projected': true
  153. };
  154. var bpcemGui = gui.add( params, 'box projected' );
  155. bpcemGui.onChange( function ( value ) {
  156. if ( value ) {
  157. groundPlane.material = boxProjectedMat;
  158. } else {
  159. groundPlane.material = defaultMat;
  160. }
  161. render();
  162. } );
  163. // scene
  164. scene = new THREE.Scene();
  165. // camera
  166. camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR );
  167. camera.position.set( 280, 106, - 5 );
  168. cameraControls = new OrbitControls( camera, renderer.domElement );
  169. cameraControls.target.set( 0, - 10, 0 );
  170. cameraControls.maxDistance = 400;
  171. cameraControls.minDistance = 10;
  172. cameraControls.addEventListener( 'change', render );
  173. cameraControls.update();
  174. // cube camera for environment map
  175. cubeCamera = new THREE.CubeCamera( 1, 1000, 512 );
  176. cubeCamera.renderTarget.texture.generateMipmaps = true;
  177. cubeCamera.renderTarget.texture.minFilter = THREE.LinearMipmapLinearFilter;
  178. cubeCamera.renderTarget.texture.mapping = THREE.CubeReflectionMapping;
  179. cubeCamera.position.set( 0, - 100, 0 );
  180. scene.add( cubeCamera );
  181. // ground floor ( with box projected environment mapping )
  182. var loader = new THREE.TextureLoader();
  183. var rMap = loader.load( 'textures/lava/lavatile.jpg' );
  184. rMap.wrapS = THREE.RepeatWrapping;
  185. rMap.wrapT = THREE.RepeatWrapping;
  186. rMap.repeat.set( 2, 1 );
  187. var defaultMat = new THREE.MeshPhysicalMaterial( {
  188. roughness: 1,
  189. envMap: cubeCamera.renderTarget.texture,
  190. roughnessMap: rMap
  191. } );
  192. var boxProjectedMat = new THREE.MeshPhysicalMaterial( {
  193. color: new THREE.Color( '#ffffff' ),
  194. roughness: 1,
  195. envMap: cubeCamera.renderTarget.texture,
  196. roughnessMap: rMap
  197. } );
  198. boxProjectedMat.onBeforeCompile = function ( shader ) {
  199. //these parameters are for the cubeCamera texture
  200. shader.uniforms.cubeMapSize = { value: new THREE.Vector3( 200, 200, 100 ) };
  201. shader.uniforms.cubeMapPos = { value: new THREE.Vector3( 0, - 50, 0 ) };
  202. //replace shader chunks with box projection chunks
  203. shader.vertexShader = 'varying vec3 vWorldPosition;\n' + shader.vertexShader;
  204. shader.vertexShader = shader.vertexShader.replace(
  205. '#include <worldpos_vertex>',
  206. worldposReplace
  207. );
  208. shader.fragmentShader = shader.fragmentShader.replace(
  209. '#include <envmap_physical_pars_fragment>',
  210. envmapPhysicalParsReplace
  211. );
  212. };
  213. groundPlane = new THREE.Mesh( new THREE.PlaneBufferGeometry( 200, 100, 100 ), boxProjectedMat );
  214. groundPlane.rotateX( - Math.PI / 2 );
  215. groundPlane.position.set( 0, - 49, 0 );
  216. scene.add( groundPlane );
  217. // walls
  218. var diffuseTex = loader.load( 'textures/brick_diffuse.jpg', function () {
  219. updateCubeMap();
  220. } );
  221. var bumpTex = loader.load( 'textures/brick_bump.jpg', function () {
  222. updateCubeMap();
  223. } );
  224. wallMat = new THREE.MeshPhysicalMaterial( {
  225. map: diffuseTex,
  226. bumpMap: bumpTex,
  227. bumpScale: 0.3,
  228. } );
  229. var planeGeo = new THREE.PlaneBufferGeometry( 100, 100 );
  230. var planeBack1 = new THREE.Mesh( planeGeo, wallMat );
  231. planeBack1.position.z = - 50;
  232. planeBack1.position.x = - 50;
  233. scene.add( planeBack1 );
  234. var planeBack2 = new THREE.Mesh( planeGeo, wallMat );
  235. planeBack2.position.z = - 50;
  236. planeBack2.position.x = 50;
  237. scene.add( planeBack2 );
  238. var planeFront1 = new THREE.Mesh( planeGeo, wallMat );
  239. planeFront1.position.z = 50;
  240. planeFront1.position.x = - 50;
  241. planeFront1.rotateY( Math.PI );
  242. scene.add( planeFront1 );
  243. var planeFront2 = new THREE.Mesh( planeGeo, wallMat );
  244. planeFront2.position.z = 50;
  245. planeFront2.position.x = 50;
  246. planeFront2.rotateY( Math.PI );
  247. scene.add( planeFront2 );
  248. var planeRight = new THREE.Mesh( planeGeo, wallMat );
  249. planeRight.position.x = 100;
  250. planeRight.rotateY( - Math.PI / 2 );
  251. scene.add( planeRight );
  252. var planeLeft = new THREE.Mesh( planeGeo, wallMat );
  253. planeLeft.position.x = - 100;
  254. planeLeft.rotateY( Math.PI / 2 );
  255. scene.add( planeLeft );
  256. //lights
  257. var width = 50;
  258. var height = 50;
  259. var intensity = 10;
  260. RectAreaLightUniformsLib.init();
  261. var blueRectLight = new THREE.RectAreaLight( 0xf3aaaa, intensity, width, height );
  262. blueRectLight.position.set( 99, 5, 0 );
  263. blueRectLight.lookAt( 0, 5, 0 );
  264. scene.add( blueRectLight );
  265. var blueRectLightHelper = new RectAreaLightHelper( blueRectLight, 0xffffff );
  266. blueRectLight.add( blueRectLightHelper );
  267. var redRectLight = new THREE.RectAreaLight( 0x9aaeff, intensity, width, height );
  268. redRectLight.position.set( - 99, 5, 0 );
  269. redRectLight.lookAt( 0, 5, 0 );
  270. scene.add( redRectLight );
  271. var redRectLightHelper = new RectAreaLightHelper( redRectLight, 0xffffff );
  272. redRectLight.add( redRectLightHelper );
  273. render();
  274. }
  275. function updateCubeMap() {
  276. //disable specular highlights on walls in the environment map
  277. wallMat.roughness = 1;
  278. groundPlane.visible = false;
  279. cubeCamera.position.copy( groundPlane.position );
  280. cubeCamera.update( renderer, scene );
  281. wallMat.roughness = 0.6;
  282. groundPlane.visible = true;
  283. render();
  284. }
  285. function render() {
  286. renderer.render( scene, camera );
  287. }
  288. </script>
  289. </body>
  290. </html>