webgl_tiled_forward.html 11 KB

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