webgl_tiled_forward.html 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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.outputColorSpace = THREE.LinearSRGBColorSpace;
  154. renderer.toneMapping = THREE.NoToneMapping;
  155. container.appendChild( renderer.domElement );
  156. const renderTarget = new THREE.WebGLRenderTarget();
  157. scene.add( new THREE.AmbientLight( 0xffffff, 0.33 ) );
  158. // At least one regular Pointlight is needed to activate light support
  159. scene.add( new THREE.PointLight( 0xff0000, 0.1, 0.1 ) );
  160. const bloom = new UnrealBloomPass( new THREE.Vector2( window.innerWidth, window.innerHeight ), 0.8, 0.6, 0.8 );
  161. bloom.renderToScreen = true;
  162. const stats = new Stats();
  163. container.appendChild( stats.dom );
  164. const controls = new OrbitControls( camera, renderer.domElement );
  165. controls.minDistance = 120;
  166. controls.maxDistance = 320;
  167. const materials = [];
  168. const Heads = [
  169. { type: 'physical', uniforms: { 'diffuse': 0x888888, 'metalness': 1.0, 'roughness': 0.66 }, defines: {} },
  170. { type: 'standard', uniforms: { 'diffuse': 0x666666, 'metalness': 0.1, 'roughness': 0.33 }, defines: {} },
  171. { type: 'phong', uniforms: { 'diffuse': 0x777777, 'shininess': 20 }, defines: {} },
  172. { type: 'phong', uniforms: { 'diffuse': 0x555555, 'shininess': 10 }, defines: { TOON: 1 } }
  173. ];
  174. function init( geom ) {
  175. const sphereGeom = new THREE.SphereGeometry( 0.5, 32, 32 );
  176. const tIndex = Math.round( Math.random() * 3 );
  177. Object.keys( Heads ).forEach( function ( t, index ) {
  178. const g = new THREE.Group();
  179. const conf = Heads[ t ];
  180. const ml = THREE.ShaderLib[ conf.type ];
  181. const mtl = new THREE.ShaderMaterial( {
  182. lights: true,
  183. fragmentShader: ml.fragmentShader,
  184. vertexShader: ml.vertexShader,
  185. uniforms: THREE.UniformsUtils.clone( ml.uniforms ),
  186. defines: conf.defines,
  187. transparent: tIndex === index ? true : false,
  188. } );
  189. mtl.extensions.derivatives = true;
  190. mtl.uniforms[ 'opacity' ].value = tIndex === index ? 0.9 : 1;
  191. mtl.uniforms[ 'tileData' ] = State.tileData;
  192. mtl.uniforms[ 'tileTexture' ] = State.tileTexture;
  193. mtl.uniforms[ 'lightTexture' ] = State.lightTexture;
  194. for ( const u in conf.uniforms ) {
  195. const vu = conf.uniforms[ u ];
  196. if ( mtl.uniforms[ u ].value.set ) {
  197. mtl.uniforms[ u ].value.set( vu );
  198. } else {
  199. mtl.uniforms[ u ].value = vu;
  200. }
  201. }
  202. mtl.defines[ 'TILED_FORWARD' ] = 1;
  203. materials.push( mtl );
  204. const obj = new THREE.Mesh( geom, mtl );
  205. obj.position.y = - 37;
  206. mtl.side = tIndex === index ? THREE.FrontSide : THREE.DoubleSide;
  207. g.rotation.y = index * Math.PI / 2;
  208. g.position.x = Math.sin( index * Math.PI / 2 ) * RADIUS;
  209. g.position.z = Math.cos( index * Math.PI / 2 ) * RADIUS;
  210. g.add( obj );
  211. for ( let i = 0; i < 8; i ++ ) {
  212. const color = new THREE.Color().setHSL( Math.random(), 1.0, 0.5 );
  213. const l = new THREE.Group();
  214. l.add( new THREE.Mesh(
  215. sphereGeom,
  216. new THREE.MeshBasicMaterial( {
  217. color: color
  218. } )
  219. ) );
  220. l.add( new THREE.Mesh(
  221. sphereGeom,
  222. new THREE.MeshBasicMaterial( {
  223. color: color,
  224. transparent: true,
  225. opacity: 0.033
  226. } )
  227. ) );
  228. l.children[ 1 ].scale.set( 6.66, 6.66, 6.66 );
  229. l._light = {
  230. color: color,
  231. radius: RADIUS,
  232. decay: 1,
  233. sy: Math.random(),
  234. sr: Math.random(),
  235. sc: Math.random(),
  236. py: Math.random() * Math.PI,
  237. pr: Math.random() * Math.PI,
  238. pc: Math.random() * Math.PI,
  239. dir: Math.random() > 0.5 ? 1 : - 1
  240. };
  241. lights.push( l );
  242. g.add( l );
  243. }
  244. scene.add( g );
  245. } );
  246. }
  247. function update( now ) {
  248. lights.forEach( function ( l ) {
  249. const ld = l._light;
  250. const radius = 0.8 + 0.2 * Math.sin( ld.pr + ( 0.6 + 0.3 * ld.sr ) * now );
  251. l.position.x = ( Math.sin( ld.pc + ( 0.8 + 0.2 * ld.sc ) * now * ld.dir ) ) * radius * RADIUS;
  252. l.position.z = ( Math.cos( ld.pc + ( 0.8 + 0.2 * ld.sc ) * now * ld.dir ) ) * radius * RADIUS;
  253. l.position.y = Math.sin( ld.py + ( 0.8 + 0.2 * ld.sy ) * now ) * radius * 32;
  254. } );
  255. }
  256. function onWindowResize() {
  257. renderer.setPixelRatio( window.devicePixelRatio );
  258. renderer.setSize( window.innerWidth, window.innerHeight );
  259. renderTarget.setSize( window.innerWidth, window.innerHeight );
  260. bloom.setSize( window.innerWidth, window.innerHeight );
  261. camera.aspect = window.innerWidth / window.innerHeight;
  262. camera.updateProjectionMatrix();
  263. resizeTiles();
  264. }
  265. function postEffect( renderer ) {
  266. bloom.render( renderer, null, renderTarget );
  267. }
  268. scene.onBeforeRender = tileLights;
  269. scene.onAfterRender = postEffect;
  270. const loader = new OBJLoader();
  271. loader.load( 'models/obj/walt/WaltHead.obj', function ( object ) {
  272. const geometry = object.children[ 0 ].geometry;
  273. window.addEventListener( 'resize', onWindowResize );
  274. init( geometry );
  275. onWindowResize();
  276. renderer.setAnimationLoop( function ( time ) {
  277. update( time / 1000 );
  278. stats.begin();
  279. renderer.setRenderTarget( renderTarget );
  280. renderer.render( scene, camera );
  281. stats.end();
  282. } );
  283. } );
  284. </script>
  285. </body>
  286. </html>