webgl_tiled_forward.html 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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/controls/OrbitControls.js"></script>
  35. <script src="js/postprocessing/EffectComposer.js"></script>
  36. <script src="js/postprocessing/RenderPass.js"></script>
  37. <script src="js/postprocessing/MaskPass.js"></script>
  38. <script src="js/postprocessing/ShaderPass.js"></script>
  39. <script src="js/shaders/CopyShader.js"></script>
  40. <script src="js/shaders/ConvolutionShader.js"></script>
  41. <script src="js/shaders/LuminosityHighPassShader.js"></script>
  42. <script src="js/postprocessing/UnrealBloomPass.js"></script>
  43. <script src="js/Detector.js"></script>
  44. <script src="js/libs/stats.min.js"></script>
  45. <script>
  46. // Simple form of tiled forward lighting
  47. // using texels as bitmasks of 32 lights
  48. var RADIUS = 75;
  49. THREE.ShaderChunk["lights_pars"] += [
  50. "#if defined TILED_FORWARD",
  51. "uniform vec4 tileData;",
  52. "uniform sampler2D tileTexture;",
  53. "uniform sampler2D lightTexture;",
  54. "#endif"
  55. ].join("\n");
  56. THREE.ShaderChunk["lights_template"] += [
  57. "",
  58. "#if defined TILED_FORWARD",
  59. "vec2 tUv = floor(gl_FragCoord.xy / tileData.xy * 32.) / 32. + tileData.zw;",
  60. "vec4 tile = texture2D(tileTexture, tUv);",
  61. "for (int i=0; i < 4; i++) {",
  62. " float tileVal = tile.x * 255.;",
  63. " tile.xyzw = tile.yzwx;",
  64. " if(tileVal == 0.){ continue; }",
  65. " float tileDiv = 128.;",
  66. " for (int j=0; j < 8; j++) {",
  67. " if (tileVal < tileDiv) { tileDiv *= 0.5; continue; }",
  68. " tileVal -= tileDiv;",
  69. " tileDiv *= 0.5;",
  70. " PointLight pointlight;",
  71. " float uvx = (float(8 * i + j) + 0.5) / 32.;",
  72. " vec4 lightData = texture2D(lightTexture, vec2(uvx, 0.));",
  73. " vec4 lightColor = texture2D(lightTexture, vec2(uvx, 1.));",
  74. " pointlight.position = lightData.xyz;",
  75. " pointlight.distance = lightData.w;",
  76. " pointlight.color = lightColor.rgb;",
  77. " pointlight.decay = lightColor.a;",
  78. " getPointDirectLightIrradiance( pointlight, geometry, directLight );",
  79. " RE_Direct( directLight, geometry, material, reflectedLight );",
  80. " }",
  81. "}",
  82. "#endif"
  83. ].join("\n");
  84. var lights = [], objects = [];
  85. var State = {
  86. rows:0,
  87. cols:0,
  88. width: 0,
  89. height: 0,
  90. tileData : { type: "v4", value: null },
  91. tileTexture: { type: "t", value: null },
  92. lightTexture: {
  93. type: "t",
  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( { antialias: false } );
  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. mtl.side = tIndex === index ? THREE.FrontSide : THREE.DoubleSide;
  218. g.rotation.y = index * Math.PI / 2;
  219. g.position.x = Math.sin(index * Math.PI / 2) * RADIUS;
  220. g.position.z = Math.cos(index * Math.PI / 2) * RADIUS;
  221. g.add(obj);
  222. for(var i=0; i < 8; i++) {
  223. var sat = Math.floor(33 + 33 * Math.random());
  224. var chroma = Math.random() * 100;
  225. var l = new THREE.Group();
  226. l.add(new THREE.Mesh(
  227. sphereGeom,
  228. new THREE.MeshBasicMaterial( { color: new THREE.Color("hsl(" + chroma + ", " + sat + "%, 50%)") } )
  229. ));
  230. l.add(new THREE.Mesh(
  231. sphereGeom,
  232. new THREE.MeshBasicMaterial( {
  233. color: new THREE.Color("hsl(" + chroma + ", " + sat + "%, 50%)"),
  234. transparent: true,
  235. opacity: 0.033
  236. } )
  237. ));
  238. l.children[1].scale.set(6.66,6.66,6.66);
  239. l._light = {
  240. color: new THREE.Color("hsl(" + chroma + ", " + sat + "%, 50%)"),
  241. radius: RADIUS,
  242. decay: 1,
  243. sy: Math.random(),
  244. sr: Math.random(),
  245. sc: Math.random() ,
  246. py: Math.random() * Math.PI ,
  247. pr: Math.random() * Math.PI ,
  248. pc: Math.random() * Math.PI ,
  249. dir: Math.random() > 0.5 ? 1:-1
  250. };
  251. lights.push(l);
  252. g.add(l);
  253. }
  254. scene.add(g);
  255. });
  256. }
  257. function update(now) {
  258. lights.forEach(function (l) {
  259. var ld = l._light;
  260. var radius = 0.8 + 0.2 * Math.sin(ld.pr + (0.6 + 0.3 * ld.sr) * now);
  261. l.position.x =(Math.sin(ld.pc + (0.8 + 0.2 * ld.sc) * now * ld.dir)) * radius * RADIUS;
  262. l.position.z =(Math.cos(ld.pc + (0.8 + 0.2 * ld.sc) * now * ld.dir)) * radius * RADIUS;
  263. l.position.y = Math.sin(ld.py + (0.8 + 0.2 * ld.sy) * now) * radius * 32;
  264. });
  265. }
  266. function resize() {
  267. renderer.setPixelRatio( window.devicePixelRatio );
  268. renderer.setSize( window.innerWidth, window.innerHeight );
  269. renderTarget.setSize( window.innerWidth, window.innerHeight );
  270. bloom.setSize( window.innerWidth, window.innerHeight );
  271. camera.aspect = window.innerWidth / window.innerHeight;
  272. camera.updateProjectionMatrix();
  273. resizeTiles();
  274. }
  275. function postEffect(renderer, camera, scene, renderTarget) {
  276. bloom.render(renderer, null, renderTarget);
  277. }
  278. scene.onBeforeRender = tileLights;
  279. scene.onAfterRender = postEffect;
  280. var loader = new THREE.JSONLoader();
  281. loader.load('./obj/walt/WaltHead_slim.js', function(geometry) {
  282. window.addEventListener("resize", resize);
  283. init(geometry);
  284. resize();
  285. renderer.animate( function(time) {
  286. update(time/1000);
  287. stats.begin();
  288. renderer.render(scene, camera, renderTarget);
  289. stats.end();
  290. });
  291. });
  292. </script>
  293. </body>
  294. </html>