webgl_tiled_forward.html 11 KB

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