webgl_tiled_forward.html 11 KB

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