webgl_tiled_forward.html 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - tiled forward lighting</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. </head>
  9. <body>
  10. <div id="info">
  11. <a href="https://threejs.org" target="_blank" rel="noopener">threejs</a> - Tiled forward lighting<br/>
  12. Created by <a href="https://github.com/wizgrav" target="_blank" rel="noopener">wizgrav</a>.
  13. </div>
  14. <script type="module">
  15. import * as THREE from '../build/three.module.js';
  16. import Stats from './jsm/libs/stats.module.js';
  17. import { OrbitControls } from './jsm/controls/OrbitControls.js';
  18. import { OBJLoader } from './jsm/loaders/OBJLoader.js';
  19. import { UnrealBloomPass } from './jsm/postprocessing/UnrealBloomPass.js';
  20. // Simple form of tiled forward lighting
  21. // using texels as bitmasks of 32 lights
  22. const RADIUS = 75;
  23. THREE.ShaderChunk[ 'lights_pars_begin' ] += [
  24. '',
  25. '#if defined TILED_FORWARD',
  26. 'uniform vec4 tileData;',
  27. 'uniform sampler2D tileTexture;',
  28. 'uniform sampler2D lightTexture;',
  29. '#endif'
  30. ].join( '\n' );
  31. THREE.ShaderChunk[ 'lights_fragment_end' ] += [
  32. '',
  33. '#if defined TILED_FORWARD',
  34. 'vec2 tUv = floor(gl_FragCoord.xy / tileData.xy * 32.) / 32. + tileData.zw;',
  35. 'vec4 tile = texture2D(tileTexture, tUv);',
  36. 'for (int i=0; i < 4; i++) {',
  37. ' float tileVal = tile.x * 255.;',
  38. ' tile.xyzw = tile.yzwx;',
  39. ' if(tileVal == 0.){ continue; }',
  40. ' float tileDiv = 128.;',
  41. ' for (int j=0; j < 8; j++) {',
  42. ' if (tileVal < tileDiv) { tileDiv *= 0.5; continue; }',
  43. ' tileVal -= tileDiv;',
  44. ' tileDiv *= 0.5;',
  45. ' PointLight pointlight;',
  46. ' float uvx = (float(8 * i + j) + 0.5) / 32.;',
  47. ' vec4 lightData = texture2D(lightTexture, vec2(uvx, 0.));',
  48. ' vec4 lightColor = texture2D(lightTexture, vec2(uvx, 1.));',
  49. ' pointlight.position = lightData.xyz;',
  50. ' pointlight.distance = lightData.w;',
  51. ' pointlight.color = lightColor.rgb;',
  52. ' pointlight.decay = lightColor.a;',
  53. ' getPointDirectLightIrradiance( pointlight, geometry, directLight );',
  54. ' RE_Direct( directLight, geometry, material, reflectedLight );',
  55. ' }',
  56. '}',
  57. '#endif'
  58. ].join( '\n' );
  59. const lights = [];
  60. const State = {
  61. rows: 0,
  62. cols: 0,
  63. width: 0,
  64. height: 0,
  65. tileData: { value: null },
  66. tileTexture: { value: null },
  67. lightTexture: {
  68. value: new THREE.DataTexture( new Float32Array( 32 * 2 * 4 ), 32, 2, THREE.RGBAFormat, THREE.FloatType )
  69. },
  70. };
  71. function resizeTiles() {
  72. const width = window.innerWidth;
  73. const height = window.innerHeight;
  74. State.width = width;
  75. State.height = height;
  76. State.cols = Math.ceil( width / 32 );
  77. State.rows = Math.ceil( height / 32 );
  78. State.tileData.value = [ width, height, 0.5 / Math.ceil( width / 32 ), 0.5 / Math.ceil( height / 32 ) ];
  79. State.tileTexture.value = new THREE.DataTexture( new Uint8Array( State.cols * State.rows * 4 ), State.cols, State.rows );
  80. }
  81. // Generate the light bitmasks and store them in the tile texture
  82. function tileLights( renderer, scene, camera ) {
  83. if ( ! camera.projectionMatrix ) return;
  84. const d = State.tileTexture.value.image.data;
  85. const ld = State.lightTexture.value.image.data;
  86. const viewMatrix = camera.matrixWorldInverse;
  87. d.fill( 0 );
  88. const vector = new THREE.Vector3();
  89. lights.forEach( function ( light, index ) {
  90. vector.setFromMatrixPosition( light.matrixWorld );
  91. const bs = lightBounds( camera, vector, light._light.radius );
  92. vector.applyMatrix4( viewMatrix );
  93. vector.toArray( ld, 4 * index );
  94. ld[ 4 * index + 3 ] = light._light.radius;
  95. light._light.color.toArray( ld, 32 * 4 + 4 * index );
  96. ld[ 32 * 4 + 4 * index + 3 ] = light._light.decay;
  97. if ( bs[ 1 ] < 0 || bs[ 0 ] > State.width || bs[ 3 ] < 0 || bs[ 2 ] > State.height ) return;
  98. if ( bs[ 0 ] < 0 ) bs[ 0 ] = 0;
  99. if ( bs[ 1 ] > State.width ) bs[ 1 ] = State.width;
  100. if ( bs[ 2 ] < 0 ) bs[ 2 ] = 0;
  101. if ( bs[ 3 ] > State.height ) bs[ 3 ] = State.height;
  102. const i4 = Math.floor( index / 8 ), i8 = 7 - ( index % 8 );
  103. for ( let i = Math.floor( bs[ 2 ] / 32 ); i <= Math.ceil( bs[ 3 ] / 32 ); i ++ ) {
  104. for ( let j = Math.floor( bs[ 0 ] / 32 ); j <= Math.ceil( bs[ 1 ] / 32 ); j ++ ) {
  105. d[ ( State.cols * i + j ) * 4 + i4 ] |= 1 << i8;
  106. }
  107. }
  108. } );
  109. State.tileTexture.value.needsUpdate = true;
  110. State.lightTexture.value.needsUpdate = true;
  111. }
  112. // Screen rectangle bounds from light sphere's world AABB
  113. const lightBounds = function () {
  114. const v = new THREE.Vector3();
  115. return function ( camera, pos, r ) {
  116. let minX = State.width, maxX = 0, minY = State.height, maxY = 0;
  117. const hw = State.width / 2, hh = State.height / 2;
  118. for ( let i = 0; i < 8; i ++ ) {
  119. v.copy( pos );
  120. v.x += i & 1 ? r : - r;
  121. v.y += i & 2 ? r : - r;
  122. v.z += i & 4 ? r : - r;
  123. const vector = v.project( camera );
  124. const x = ( vector.x * hw ) + hw;
  125. const y = ( vector.y * hh ) + hh;
  126. minX = Math.min( minX, x );
  127. maxX = Math.max( maxX, x );
  128. minY = Math.min( minY, y );
  129. maxY = Math.max( maxY, y );
  130. }
  131. return [ minX, maxX, minY, maxY ];
  132. };
  133. }();
  134. // Rendering
  135. const container = document.createElement( 'div' );
  136. document.body.appendChild( container );
  137. const camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 2000 );
  138. camera.position.set( 0.0, 0.0, 240.0 );
  139. const scene = new THREE.Scene();
  140. scene.background = new THREE.Color( 0x111111 );
  141. const renderer = new THREE.WebGLRenderer();
  142. renderer.toneMapping = THREE.NoToneMapping;
  143. container.appendChild( renderer.domElement );
  144. const renderTarget = new THREE.WebGLRenderTarget();
  145. scene.add( new THREE.AmbientLight( 0xffffff, 0.33 ) );
  146. // At least one regular Pointlight is needed to activate light support
  147. scene.add( new THREE.PointLight( 0xff0000, 0.1, 0.1 ) );
  148. const bloom = new UnrealBloomPass( new THREE.Vector2( window.innerWidth, window.innerHeight ), 0.8, 0.6, 0.8 );
  149. bloom.renderToScreen = true;
  150. const stats = new Stats();
  151. container.appendChild( stats.dom );
  152. const controls = new OrbitControls( camera, renderer.domElement );
  153. controls.minDistance = 120;
  154. controls.maxDistance = 320;
  155. const materials = [];
  156. const Heads = [
  157. { type: 'physical', uniforms: { "diffuse": 0x888888, "metalness": 1.0, "roughness": 0.66 }, defines: {} },
  158. { type: 'standard', uniforms: { "diffuse": 0x666666, "metalness": 0.1, "roughness": 0.33 }, defines: {} },
  159. { type: 'phong', uniforms: { "diffuse": 0x777777, "shininess": 20 }, defines: {} },
  160. { type: 'phong', uniforms: { "diffuse": 0x555555, "shininess": 10 }, defines: { TOON: 1 } }
  161. ];
  162. function init( geom ) {
  163. const sphereGeom = new THREE.SphereGeometry( 0.5, 32, 32 );
  164. const tIndex = Math.round( Math.random() * 3 );
  165. Object.keys( Heads ).forEach( function ( t, index ) {
  166. let g = new THREE.Group();
  167. const conf = Heads[ t ];
  168. const ml = THREE.ShaderLib[ conf.type ];
  169. const mtl = new THREE.ShaderMaterial( {
  170. lights: true,
  171. fragmentShader: ml.fragmentShader,
  172. vertexShader: ml.vertexShader,
  173. uniforms: THREE.UniformsUtils.clone( ml.uniforms ),
  174. defines: conf.defines,
  175. transparent: tIndex === index ? true : false,
  176. } );
  177. mtl.extensions.derivatives = true;
  178. mtl.uniforms[ "opacity" ].value = tIndex === index ? 0.9 : 1;
  179. mtl.uniforms[ "tileData" ] = State.tileData;
  180. mtl.uniforms[ "tileTexture" ] = State.tileTexture;
  181. mtl.uniforms[ "lightTexture" ] = State.lightTexture;
  182. for ( const u in conf.uniforms ) {
  183. const vu = conf.uniforms[ u ];
  184. if ( mtl.uniforms[ u ].value.set ) {
  185. mtl.uniforms[ u ].value.set( vu );
  186. } else {
  187. mtl.uniforms[ u ].value = vu;
  188. }
  189. }
  190. mtl.defines[ 'TILED_FORWARD' ] = 1;
  191. materials.push( mtl );
  192. const obj = new THREE.Mesh( geom, mtl );
  193. obj.position.y = - 37;
  194. mtl.side = tIndex === index ? THREE.FrontSide : THREE.DoubleSide;
  195. g.rotation.y = index * Math.PI / 2;
  196. g.position.x = Math.sin( index * Math.PI / 2 ) * RADIUS;
  197. g.position.z = Math.cos( index * Math.PI / 2 ) * RADIUS;
  198. g.add( obj );
  199. for ( let i = 0; i < 8; i ++ ) {
  200. const color = new THREE.Color().setHSL( Math.random(), 1.0, 0.5 );
  201. const l = new THREE.Group();
  202. l.add( new THREE.Mesh(
  203. sphereGeom,
  204. new THREE.MeshBasicMaterial( {
  205. color: color
  206. } )
  207. ) );
  208. l.add( new THREE.Mesh(
  209. sphereGeom,
  210. new THREE.MeshBasicMaterial( {
  211. color: color,
  212. transparent: true,
  213. opacity: 0.033
  214. } )
  215. ) );
  216. l.children[ 1 ].scale.set( 6.66, 6.66, 6.66 );
  217. l._light = {
  218. color: color,
  219. radius: RADIUS,
  220. decay: 1,
  221. sy: Math.random(),
  222. sr: Math.random(),
  223. sc: Math.random(),
  224. py: Math.random() * Math.PI,
  225. pr: Math.random() * Math.PI,
  226. pc: Math.random() * Math.PI,
  227. dir: Math.random() > 0.5 ? 1 : - 1
  228. };
  229. lights.push( l );
  230. g.add( l );
  231. }
  232. scene.add( g );
  233. } );
  234. }
  235. function update( now ) {
  236. lights.forEach( function ( l ) {
  237. const ld = l._light;
  238. const radius = 0.8 + 0.2 * Math.sin( ld.pr + ( 0.6 + 0.3 * ld.sr ) * now );
  239. l.position.x = ( Math.sin( ld.pc + ( 0.8 + 0.2 * ld.sc ) * now * ld.dir ) ) * radius * RADIUS;
  240. l.position.z = ( Math.cos( ld.pc + ( 0.8 + 0.2 * ld.sc ) * now * ld.dir ) ) * radius * RADIUS;
  241. l.position.y = Math.sin( ld.py + ( 0.8 + 0.2 * ld.sy ) * now ) * radius * 32;
  242. } );
  243. }
  244. function onWindowResize() {
  245. renderer.setPixelRatio( window.devicePixelRatio );
  246. renderer.setSize( window.innerWidth, window.innerHeight );
  247. renderTarget.setSize( window.innerWidth, window.innerHeight );
  248. bloom.setSize( window.innerWidth, window.innerHeight );
  249. camera.aspect = window.innerWidth / window.innerHeight;
  250. camera.updateProjectionMatrix();
  251. resizeTiles();
  252. }
  253. function postEffect( renderer ) {
  254. bloom.render( renderer, null, renderTarget );
  255. }
  256. scene.onBeforeRender = tileLights;
  257. scene.onAfterRender = postEffect;
  258. const loader = new OBJLoader();
  259. loader.load( 'models/obj/walt/WaltHead.obj', function ( object ) {
  260. const geometry = object.children[ 0 ].geometry;
  261. window.addEventListener( 'resize', onWindowResize );
  262. init( geometry );
  263. onWindowResize();
  264. renderer.setAnimationLoop( function ( time ) {
  265. update( time / 1000 );
  266. stats.begin();
  267. renderer.setRenderTarget( renderTarget );
  268. renderer.render( scene, camera );
  269. stats.end();
  270. } );
  271. } );
  272. </script>
  273. </body>
  274. </html>