webgl_tiled_forward.html 11 KB

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