WebGLDeferredRenderer.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  1. /**
  2. * @author alteredq / http://alteredqualia.com/
  3. * @author MPanknin / http://www.redplant.de/
  4. */
  5. THREE.WebGLDeferredRenderer = function ( parameters ) {
  6. var _this = this;
  7. var fullWidth = parameters.width !== undefined ? parameters.width : 800;
  8. var fullHeight = parameters.height !== undefined ? parameters.height : 600;
  9. var currentScale = parameters.scale !== undefined ? parameters.scale : 1;
  10. var scaledWidth = Math.floor( currentScale * fullWidth );
  11. var scaledHeight = Math.floor( currentScale * fullHeight );
  12. var brightness = parameters.brightness !== undefined ? parameters.brightness : 1;
  13. var tonemapping = parameters.tonemapping !== undefined ? parameters.tonemapping : THREE.SimpleOperator;
  14. var antialias = parameters.antialias !== undefined ? parameters.antialias : false;
  15. this.renderer = parameters.renderer;
  16. if ( this.renderer === undefined ) {
  17. this.renderer = new THREE.WebGLRenderer( { alpha: false, antialias: false } );
  18. this.renderer.setSize( fullWidth, fullHeight );
  19. this.renderer.setClearColorHex( 0x000000, 0 );
  20. this.renderer.autoClear = false;
  21. }
  22. this.domElement = this.renderer.domElement;
  23. //
  24. var gl = this.renderer.context;
  25. //
  26. var positionVS = new THREE.Vector3();
  27. var directionVS = new THREE.Vector3();
  28. var tempVS = new THREE.Vector3();
  29. var rightVS = new THREE.Vector3();
  30. var normalVS = new THREE.Vector3();
  31. var upVS = new THREE.Vector3();
  32. //
  33. var geometryLightSphere = new THREE.SphereGeometry( 1, 16, 8 );
  34. var geometryLightPlane = new THREE.PlaneGeometry( 2, 2 );
  35. var black = new THREE.Color( 0x000000 );
  36. var colorShader = THREE.ShaderDeferred[ "color" ];
  37. var normalDepthShader = THREE.ShaderDeferred[ "normalDepth" ];
  38. //
  39. var emissiveLightShader = THREE.ShaderDeferred[ "emissiveLight" ];
  40. var pointLightShader = THREE.ShaderDeferred[ "pointLight" ];
  41. var spotLightShader = THREE.ShaderDeferred[ "spotLight" ];
  42. var directionalLightShader = THREE.ShaderDeferred[ "directionalLight" ];
  43. var hemisphereLightShader = THREE.ShaderDeferred[ "hemisphereLight" ];
  44. var areaLightShader = THREE.ShaderDeferred[ "areaLight" ];
  45. var compositeShader = THREE.ShaderDeferred[ "composite" ];
  46. //
  47. var compColor, compNormal, compDepth, compLight, compFinal;
  48. var passColor, passNormal, passDepth, passLightFullscreen, passLightProxy, compositePass;
  49. var effectFXAA;
  50. //
  51. var lightSceneFullscreen, lightSceneProxy;
  52. //
  53. var resizableMaterials = [];
  54. //
  55. var invisibleMaterial = new THREE.ShaderMaterial();
  56. invisibleMaterial.visible = false;
  57. var defaultNormalDepthMaterial = new THREE.ShaderMaterial( {
  58. uniforms: THREE.UniformsUtils.clone( normalDepthShader.uniforms ),
  59. vertexShader: normalDepthShader.vertexShader,
  60. fragmentShader: normalDepthShader.fragmentShader,
  61. blending: THREE.NoBlending
  62. } );
  63. //
  64. var initDeferredMaterials = function ( object ) {
  65. if ( object.material instanceof THREE.MeshFaceMaterial ) {
  66. var colorMaterials = [];
  67. var normalDepthMaterials = [];
  68. var materials = object.material.materials;
  69. for ( var i = 0, il = materials.length; i < il; i ++ ) {
  70. var deferredMaterials = createDeferredMaterials( materials[ i ] );
  71. if ( deferredMaterials.transparent ) {
  72. colorMaterials.push( invisibleMaterial );
  73. normalDepthMaterials.push( invisibleMaterial );
  74. } else {
  75. colorMaterials.push( deferredMaterials.colorMaterial );
  76. normalDepthMaterials.push( deferredMaterials.normalDepthMaterial );
  77. }
  78. }
  79. object.userData.colorMaterial = new THREE.MeshFaceMaterial( colorMaterials );
  80. object.userData.normalDepthMaterial = new THREE.MeshFaceMaterial( normalDepthMaterials );
  81. } else {
  82. var deferredMaterials = createDeferredMaterials( object.material );
  83. object.userData.colorMaterial = deferredMaterials.colorMaterial;
  84. object.userData.normalDepthMaterial = deferredMaterials.normalDepthMaterial;
  85. object.userData.transparent = deferredMaterials.transparent;
  86. }
  87. };
  88. var createDeferredMaterials = function ( originalMaterial ) {
  89. var deferredMaterials = {};
  90. // color material
  91. // -----------------
  92. // diffuse color
  93. // specular color
  94. // shininess
  95. // diffuse map
  96. // vertex colors
  97. // alphaTest
  98. // morphs
  99. var uniforms = THREE.UniformsUtils.clone( colorShader.uniforms );
  100. var defines = { "USE_MAP": !! originalMaterial.map, "USE_ENVMAP": !! originalMaterial.envMap, "GAMMA_INPUT": true };
  101. var material = new THREE.ShaderMaterial( {
  102. fragmentShader: colorShader.fragmentShader,
  103. vertexShader: colorShader.vertexShader,
  104. uniforms: uniforms,
  105. defines: defines,
  106. shading: originalMaterial.shading
  107. } );
  108. if ( originalMaterial instanceof THREE.MeshBasicMaterial ) {
  109. var diffuse = black;
  110. var emissive = originalMaterial.color;
  111. } else {
  112. var diffuse = originalMaterial.color;
  113. var emissive = originalMaterial.emissive !== undefined ? originalMaterial.emissive : black;
  114. }
  115. var specular = originalMaterial.specular !== undefined ? originalMaterial.specular : black;
  116. var shininess = originalMaterial.shininess !== undefined ? originalMaterial.shininess : 1;
  117. var wrapAround = originalMaterial.wrapAround !== undefined ? ( originalMaterial.wrapAround ? -1 : 1 ) : 1;
  118. var additiveSpecular = originalMaterial.metal !== undefined ? ( originalMaterial.metal ? 1 : -1 ) : -1;
  119. uniforms.emissive.value.copyGammaToLinear( emissive );
  120. uniforms.diffuse.value.copyGammaToLinear( diffuse );
  121. uniforms.specular.value.copyGammaToLinear( specular );
  122. uniforms.shininess.value = shininess;
  123. uniforms.wrapAround.value = wrapAround;
  124. uniforms.additiveSpecular.value = additiveSpecular;
  125. uniforms.map.value = originalMaterial.map;
  126. if ( originalMaterial.envMap ) {
  127. uniforms.envMap.value = originalMaterial.envMap;
  128. uniforms.useRefract.value = originalMaterial.envMap.mapping instanceof THREE.CubeRefractionMapping;
  129. uniforms.refractionRatio.value = originalMaterial.refractionRatio;
  130. uniforms.combine.value = originalMaterial.combine;
  131. uniforms.reflectivity.value = originalMaterial.reflectivity;
  132. uniforms.flipEnvMap.value = ( originalMaterial.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  133. uniforms.samplerNormalDepth.value = compNormalDepth.renderTarget2;
  134. uniforms.viewWidth.value = scaledWidth;
  135. uniforms.viewHeight.value = scaledHeight;
  136. resizableMaterials.push( { "material": material } );
  137. }
  138. material.vertexColors = originalMaterial.vertexColors;
  139. material.morphTargets = originalMaterial.morphTargets;
  140. material.morphNormals = originalMaterial.morphNormals;
  141. material.skinning = originalMaterial.skinning;
  142. material.alphaTest = originalMaterial.alphaTest;
  143. material.wireframe = originalMaterial.wireframe;
  144. // uv repeat and offset setting priorities
  145. // 1. color map
  146. // 2. specular map
  147. // 3. normal map
  148. // 4. bump map
  149. var uvScaleMap;
  150. if ( originalMaterial.map ) {
  151. uvScaleMap = originalMaterial.map;
  152. } else if ( originalMaterial.specularMap ) {
  153. uvScaleMap = originalMaterial.specularMap;
  154. } else if ( originalMaterial.normalMap ) {
  155. uvScaleMap = originalMaterial.normalMap;
  156. } else if ( originalMaterial.bumpMap ) {
  157. uvScaleMap = originalMaterial.bumpMap;
  158. }
  159. if ( uvScaleMap !== undefined ) {
  160. var offset = uvScaleMap.offset;
  161. var repeat = uvScaleMap.repeat;
  162. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  163. }
  164. deferredMaterials.colorMaterial = material;
  165. // normal + depth material
  166. // -----------------
  167. // vertex normals
  168. // morph normals
  169. // bump map
  170. // bump scale
  171. // clip depth
  172. if ( originalMaterial.morphTargets || originalMaterial.skinning || originalMaterial.bumpMap ) {
  173. var uniforms = THREE.UniformsUtils.clone( normalDepthShader.uniforms );
  174. var defines = { "USE_BUMPMAP": !!originalMaterial.bumpMap };
  175. var normalDepthMaterial = new THREE.ShaderMaterial( {
  176. uniforms: uniforms,
  177. vertexShader: normalDepthShader.vertexShader,
  178. fragmentShader: normalDepthShader.fragmentShader,
  179. shading: originalMaterial.shading,
  180. defines: defines,
  181. blending: THREE.NoBlending
  182. } );
  183. normalDepthMaterial.morphTargets = originalMaterial.morphTargets;
  184. normalDepthMaterial.morphNormals = originalMaterial.morphNormals;
  185. normalDepthMaterial.skinning = originalMaterial.skinning;
  186. if ( originalMaterial.bumpMap ) {
  187. uniforms.bumpMap.value = originalMaterial.bumpMap;
  188. uniforms.bumpScale.value = originalMaterial.bumpScale;
  189. var offset = originalMaterial.bumpMap.offset;
  190. var repeat = originalMaterial.bumpMap.repeat;
  191. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  192. }
  193. } else {
  194. var normalDepthMaterial = defaultNormalDepthMaterial.clone();
  195. }
  196. normalDepthMaterial.wireframe = originalMaterial.wireframe;
  197. normalDepthMaterial.vertexColors = originalMaterial.vertexColors;
  198. deferredMaterials.normalDepthMaterial = normalDepthMaterial;
  199. //
  200. deferredMaterials.transparent = originalMaterial.transparent;
  201. return deferredMaterials;
  202. };
  203. var updatePointLightProxy = function ( lightProxy ) {
  204. var light = lightProxy.userData.originalLight;
  205. var uniforms = lightProxy.material.uniforms;
  206. // skip infinite pointlights
  207. // right now you can't switch between infinite and finite pointlights
  208. // it's just too messy as they use different proxies
  209. var distance = light.distance;
  210. if ( distance > 0 ) {
  211. lightProxy.scale.set( 1, 1, 1 ).multiplyScalar( distance );
  212. uniforms[ "lightRadius" ].value = distance;
  213. positionVS.getPositionFromMatrix( light.matrixWorld );
  214. positionVS.applyMatrix4( camera.matrixWorldInverse );
  215. uniforms[ "lightPositionVS" ].value.copy( positionVS );
  216. lightProxy.position.getPositionFromMatrix( light.matrixWorld );
  217. } else {
  218. uniforms[ "lightRadius" ].value = Infinity;
  219. }
  220. // linear space colors
  221. var intensity = light.intensity * light.intensity;
  222. uniforms[ "lightIntensity" ].value = intensity;
  223. uniforms[ "lightColor" ].value.copyGammaToLinear( light.color );
  224. };
  225. var createDeferredPointLight = function ( light ) {
  226. // setup light material
  227. var materialLight = new THREE.ShaderMaterial( {
  228. uniforms: THREE.UniformsUtils.clone( pointLightShader.uniforms ),
  229. vertexShader: pointLightShader.vertexShader,
  230. fragmentShader: pointLightShader.fragmentShader,
  231. blending: THREE.AdditiveBlending,
  232. depthWrite: false,
  233. transparent: true,
  234. side: THREE.BackSide
  235. } );
  236. // infinite pointlights use full-screen quad proxy
  237. // regular pointlights use sphere proxy
  238. var geometry;
  239. if ( light.distance > 0 ) {
  240. geometry = geometryLightSphere;
  241. } else {
  242. geometry = geometryLightPlane;
  243. materialLight.depthTest = false;
  244. materialLight.side = THREE.FrontSide;
  245. }
  246. materialLight.uniforms[ "viewWidth" ].value = scaledWidth;
  247. materialLight.uniforms[ "viewHeight" ].value = scaledHeight;
  248. materialLight.uniforms[ 'samplerColor' ].value = compColor.renderTarget2;
  249. materialLight.uniforms[ 'samplerNormalDepth' ].value = compNormalDepth.renderTarget2;
  250. // create light proxy mesh
  251. var meshLight = new THREE.Mesh( geometry, materialLight );
  252. // keep reference for color and intensity updates
  253. meshLight.userData.originalLight = light;
  254. // keep reference for size reset
  255. resizableMaterials.push( { "material": materialLight } );
  256. // sync proxy uniforms to the original light
  257. updatePointLightProxy( meshLight );
  258. return meshLight;
  259. };
  260. var updateSpotLightProxy = function ( lightProxy ) {
  261. var light = lightProxy.userData.originalLight;
  262. var uniforms = lightProxy.material.uniforms;
  263. var viewMatrix = camera.matrixWorldInverse;
  264. var modelMatrix = light.matrixWorld;
  265. positionVS.getPositionFromMatrix( modelMatrix );
  266. positionVS.applyMatrix4( viewMatrix );
  267. directionVS.getPositionFromMatrix( modelMatrix );
  268. tempVS.getPositionFromMatrix( light.target.matrixWorld );
  269. directionVS.sub( tempVS );
  270. directionVS.normalize();
  271. directionVS.transformDirection( viewMatrix );
  272. uniforms[ "lightPositionVS" ].value.copy( positionVS );
  273. uniforms[ "lightDirectionVS" ].value.copy( directionVS );
  274. uniforms[ "lightAngle" ].value = light.angle;
  275. uniforms[ "lightDistance" ].value = light.distance;
  276. // linear space colors
  277. var intensity = light.intensity * light.intensity;
  278. uniforms[ "lightIntensity" ].value = intensity;
  279. uniforms[ "lightColor" ].value.copyGammaToLinear( light.color );
  280. };
  281. var createDeferredSpotLight = function ( light ) {
  282. // setup light material
  283. var uniforms = THREE.UniformsUtils.clone( spotLightShader.uniforms );
  284. var materialLight = new THREE.ShaderMaterial( {
  285. uniforms: uniforms,
  286. vertexShader: spotLightShader.vertexShader,
  287. fragmentShader: spotLightShader.fragmentShader,
  288. blending: THREE.AdditiveBlending,
  289. depthWrite: false,
  290. depthTest: false,
  291. transparent: true
  292. } );
  293. uniforms[ "viewWidth" ].value = scaledWidth;
  294. uniforms[ "viewHeight" ].value = scaledHeight;
  295. uniforms[ 'samplerColor' ].value = compColor.renderTarget2;
  296. uniforms[ 'samplerNormalDepth' ].value = compNormalDepth.renderTarget2;
  297. // create light proxy mesh
  298. var meshLight = new THREE.Mesh( geometryLightPlane, materialLight );
  299. // keep reference for color and intensity updates
  300. meshLight.userData.originalLight = light;
  301. // keep reference for size reset
  302. resizableMaterials.push( { "material": materialLight } );
  303. // sync proxy uniforms to the original light
  304. updateSpotLightProxy( meshLight );
  305. return meshLight;
  306. };
  307. var updateDirectionalLightProxy = function ( lightProxy ) {
  308. var light = lightProxy.userData.originalLight;
  309. var uniforms = lightProxy.material.uniforms;
  310. directionVS.getPositionFromMatrix( light.matrixWorld );
  311. tempVS.getPositionFromMatrix( light.target.matrixWorld );
  312. directionVS.sub( tempVS );
  313. directionVS.normalize();
  314. directionVS.transformDirection( camera.matrixWorldInverse );
  315. uniforms[ "lightDirectionVS" ].value.copy( directionVS );
  316. // linear space colors
  317. var intensity = light.intensity * light.intensity;
  318. uniforms[ "lightIntensity" ].value = intensity;
  319. uniforms[ "lightColor" ].value.copyGammaToLinear( light.color );
  320. };
  321. var createDeferredDirectionalLight = function ( light ) {
  322. // setup light material
  323. var uniforms = THREE.UniformsUtils.clone( directionalLightShader.uniforms );
  324. var materialLight = new THREE.ShaderMaterial( {
  325. uniforms: uniforms,
  326. vertexShader: directionalLightShader.vertexShader,
  327. fragmentShader: directionalLightShader.fragmentShader,
  328. blending: THREE.AdditiveBlending,
  329. depthWrite: false,
  330. depthTest: false,
  331. transparent: true
  332. } );
  333. uniforms[ "viewWidth" ].value = scaledWidth;
  334. uniforms[ "viewHeight" ].value = scaledHeight;
  335. uniforms[ 'samplerColor' ].value = compColor.renderTarget2;
  336. uniforms[ 'samplerNormalDepth' ].value = compNormalDepth.renderTarget2;
  337. // create light proxy mesh
  338. var meshLight = new THREE.Mesh( geometryLightPlane, materialLight );
  339. // keep reference for color and intensity updates
  340. meshLight.userData.originalLight = light;
  341. // keep reference for size reset
  342. resizableMaterials.push( { "material": materialLight } );
  343. // sync proxy uniforms to the original light
  344. updateDirectionalLightProxy( meshLight );
  345. return meshLight;
  346. };
  347. var updateHemisphereLightProxy = function ( lightProxy ) {
  348. var light = lightProxy.userData.originalLight;
  349. var uniforms = lightProxy.material.uniforms;
  350. directionVS.getPositionFromMatrix( light.matrixWorld );
  351. directionVS.normalize();
  352. directionVS.transformDirection( camera.matrixWorldInverse );
  353. uniforms[ "lightDirectionVS" ].value.copy( directionVS );
  354. // linear space colors
  355. var intensity = light.intensity * light.intensity;
  356. uniforms[ "lightIntensity" ].value = intensity;
  357. uniforms[ "lightColorSky" ].value.copyGammaToLinear( light.color );
  358. uniforms[ "lightColorGround" ].value.copyGammaToLinear( light.groundColor );
  359. };
  360. var createDeferredHemisphereLight = function ( light ) {
  361. // setup light material
  362. var uniforms = THREE.UniformsUtils.clone( hemisphereLightShader.uniforms );
  363. var materialLight = new THREE.ShaderMaterial( {
  364. uniforms: uniforms,
  365. vertexShader: hemisphereLightShader.vertexShader,
  366. fragmentShader: hemisphereLightShader.fragmentShader,
  367. blending: THREE.AdditiveBlending,
  368. depthWrite: false,
  369. depthTest: false,
  370. transparent: true
  371. } );
  372. uniforms[ "viewWidth" ].value = scaledWidth;
  373. uniforms[ "viewHeight" ].value = scaledHeight;
  374. uniforms[ 'samplerColor' ].value = compColor.renderTarget2;
  375. uniforms[ 'samplerNormalDepth' ].value = compNormalDepth.renderTarget2;
  376. // create light proxy mesh
  377. var meshLight = new THREE.Mesh( geometryLightPlane, materialLight );
  378. // keep reference for color and intensity updates
  379. meshLight.userData.originalLight = light;
  380. // keep reference for size reset
  381. resizableMaterials.push( { "material": materialLight } );
  382. // sync proxy uniforms to the original light
  383. updateHemisphereLightProxy( meshLight );
  384. return meshLight;
  385. };
  386. var updateAreaLightProxy = function ( lightProxy ) {
  387. var light = lightProxy.userData.originalLight;
  388. var uniforms = lightProxy.material.uniforms;
  389. var modelMatrix = light.matrixWorld;
  390. var viewMatrix = camera.matrixWorldInverse;
  391. positionVS.getPositionFromMatrix( modelMatrix );
  392. positionVS.applyMatrix4( viewMatrix );
  393. uniforms[ "lightPositionVS" ].value.copy( positionVS );
  394. rightVS.copy( light.right );
  395. rightVS.transformDirection( modelMatrix );
  396. rightVS.transformDirection( viewMatrix );
  397. normalVS.copy( light.normal );
  398. normalVS.transformDirection( modelMatrix );
  399. normalVS.transformDirection( viewMatrix );
  400. upVS.crossVectors( rightVS, normalVS );
  401. upVS.normalize();
  402. uniforms[ "lightRightVS" ].value.copy( rightVS );
  403. uniforms[ "lightNormalVS" ].value.copy( normalVS );
  404. uniforms[ "lightUpVS" ].value.copy( upVS );
  405. uniforms[ "lightWidth" ].value = light.width;
  406. uniforms[ "lightHeight" ].value = light.height;
  407. uniforms[ "constantAttenuation" ].value = light.constantAttenuation;
  408. uniforms[ "linearAttenuation" ].value = light.linearAttenuation;
  409. uniforms[ "quadraticAttenuation" ].value = light.quadraticAttenuation;
  410. // linear space colors
  411. var intensity = light.intensity * light.intensity;
  412. uniforms[ "lightIntensity" ].value = intensity;
  413. uniforms[ "lightColor" ].value.copyGammaToLinear( light.color );
  414. };
  415. var createDeferredAreaLight = function ( light ) {
  416. // setup light material
  417. var uniforms = THREE.UniformsUtils.clone( areaLightShader.uniforms );
  418. var materialLight = new THREE.ShaderMaterial( {
  419. uniforms: uniforms,
  420. vertexShader: areaLightShader.vertexShader,
  421. fragmentShader: areaLightShader.fragmentShader,
  422. blending: THREE.AdditiveBlending,
  423. depthWrite: false,
  424. depthTest: false,
  425. transparent: true
  426. } );
  427. uniforms[ "viewWidth" ].value = scaledWidth;
  428. uniforms[ "viewHeight" ].value = scaledHeight;
  429. uniforms[ 'samplerColor' ].value = compColor.renderTarget2;
  430. uniforms[ 'samplerNormalDepth' ].value = compNormalDepth.renderTarget2;
  431. // create light proxy mesh
  432. var meshLight = new THREE.Mesh( geometryLightPlane, materialLight );
  433. // keep reference for color and intensity updates
  434. meshLight.userData.originalLight = light;
  435. // keep reference for size reset
  436. resizableMaterials.push( { "material": materialLight } );
  437. // sync proxy uniforms to the original light
  438. updateAreaLightProxy( meshLight );
  439. return meshLight;
  440. };
  441. var createDeferredEmissiveLight = function () {
  442. // setup light material
  443. var materialLight = new THREE.ShaderMaterial( {
  444. uniforms: THREE.UniformsUtils.clone( emissiveLightShader.uniforms ),
  445. vertexShader: emissiveLightShader.vertexShader,
  446. fragmentShader: emissiveLightShader.fragmentShader,
  447. depthTest: false,
  448. depthWrite: false,
  449. blending: THREE.NoBlending
  450. } );
  451. materialLight.uniforms[ "viewWidth" ].value = scaledWidth;
  452. materialLight.uniforms[ "viewHeight" ].value = scaledHeight;
  453. materialLight.uniforms[ 'samplerColor' ].value = compColor.renderTarget2;
  454. // create light proxy mesh
  455. var meshLight = new THREE.Mesh( geometryLightPlane, materialLight );
  456. // keep reference for size reset
  457. resizableMaterials.push( { "material": materialLight } );
  458. return meshLight;
  459. };
  460. var initDeferredProperties = function ( object ) {
  461. if ( object.userData.deferredInitialized ) return;
  462. if ( object.material ) initDeferredMaterials( object );
  463. if ( object instanceof THREE.PointLight ) {
  464. var proxy = createDeferredPointLight( object );
  465. if ( object.distance > 0 ) {
  466. lightSceneProxy.add( proxy );
  467. } else {
  468. lightSceneFullscreen.add( proxy );
  469. }
  470. } else if ( object instanceof THREE.SpotLight ) {
  471. var proxy = createDeferredSpotLight( object );
  472. lightSceneFullscreen.add( proxy );
  473. } else if ( object instanceof THREE.DirectionalLight ) {
  474. var proxy = createDeferredDirectionalLight( object );
  475. lightSceneFullscreen.add( proxy );
  476. } else if ( object instanceof THREE.HemisphereLight ) {
  477. var proxy = createDeferredHemisphereLight( object );
  478. lightSceneFullscreen.add( proxy );
  479. } else if ( object instanceof THREE.AreaLight ) {
  480. var proxy = createDeferredAreaLight( object );
  481. lightSceneFullscreen.add( proxy );
  482. }
  483. object.userData.deferredInitialized = true;
  484. };
  485. //
  486. var setMaterialColor = function ( object ) {
  487. if ( object.material ) {
  488. if ( object.userData.transparent ) {
  489. object.material = invisibleMaterial;
  490. } else {
  491. object.material = object.userData.colorMaterial;
  492. }
  493. }
  494. };
  495. var setMaterialNormalDepth = function ( object ) {
  496. if ( object.material ) {
  497. if ( object.userData.transparent ) {
  498. object.material = invisibleMaterial;
  499. } else {
  500. object.material = object.userData.normalDepthMaterial;
  501. }
  502. }
  503. };
  504. // external API
  505. this.setAntialias = function ( enabled ) {
  506. antialias = enabled;
  507. if ( antialias ) {
  508. effectFXAA.enabled = true;
  509. compositePass.renderToScreen = false;
  510. } else {
  511. effectFXAA.enabled = false;
  512. compositePass.renderToScreen = true;
  513. }
  514. };
  515. this.getAntialias = function () {
  516. return antialias;
  517. };
  518. this.addEffect = function ( effect, normalDepthUniform, colorUniform ) {
  519. if ( effect.material && effect.uniforms ) {
  520. if ( normalDepthUniform ) effect.uniforms[ normalDepthUniform ].value = compNormalDepth.renderTarget2;
  521. if ( colorUniform ) effect.uniforms[ colorUniform ].value = compColor.renderTarget2;
  522. if ( normalDepthUniform || colorUniform ) {
  523. resizableMaterials.push( { "material": effect.material, "normalDepth": normalDepthUniform, "color": colorUniform } );
  524. }
  525. }
  526. compFinal.insertPass( effect, -1 );
  527. };
  528. this.setScale = function ( scale ) {
  529. currentScale = scale;
  530. scaledWidth = Math.floor( currentScale * fullWidth );
  531. scaledHeight = Math.floor( currentScale * fullHeight );
  532. compNormalDepth.setSize( scaledWidth, scaledHeight );
  533. compColor.setSize( scaledWidth, scaledHeight );
  534. compLight.setSize( scaledWidth, scaledHeight );
  535. compFinal.setSize( scaledWidth, scaledHeight );
  536. compColor.renderTarget2.shareDepthFrom = compNormalDepth.renderTarget2;
  537. compLight.renderTarget2.shareDepthFrom = compNormalDepth.renderTarget2;
  538. for ( var i = 0, il = resizableMaterials.length; i < il; i ++ ) {
  539. var materialEntry = resizableMaterials[ i ];
  540. var material = materialEntry.material;
  541. var uniforms = material.uniforms;
  542. var colorLabel = materialEntry.color !== undefined ? materialEntry.color : 'samplerColor';
  543. var normalDepthLabel = materialEntry.normalDepth !== undefined ? materialEntry.normalDepth : 'samplerNormalDepth';
  544. if ( uniforms[ colorLabel ] ) uniforms[ colorLabel ].value = compColor.renderTarget2;
  545. if ( uniforms[ normalDepthLabel ] ) uniforms[ normalDepthLabel ].value = compNormalDepth.renderTarget2;
  546. if ( uniforms[ 'viewWidth' ] ) uniforms[ "viewWidth" ].value = scaledWidth;
  547. if ( uniforms[ 'viewHeight' ] ) uniforms[ "viewHeight" ].value = scaledHeight;
  548. }
  549. compositePass.uniforms[ 'samplerLight' ].value = compLight.renderTarget2;
  550. effectFXAA.uniforms[ 'resolution' ].value.set( 1 / fullWidth, 1 / fullHeight );
  551. };
  552. this.setSize = function ( width, height ) {
  553. fullWidth = width;
  554. fullHeight = height;
  555. this.renderer.setSize( fullWidth, fullHeight );
  556. this.setScale( currentScale );
  557. };
  558. //
  559. function updateLightProxy ( proxy, camera ) {
  560. var uniforms = proxy.material.uniforms;
  561. if ( uniforms[ "matProjInverse" ] ) uniforms[ "matProjInverse" ].value = camera.projectionMatrixInverse;
  562. if ( uniforms[ "matView" ] ) uniforms[ "matView" ].value = camera.matrixWorldInverse;
  563. var originalLight = proxy.userData.originalLight;
  564. if ( originalLight ) {
  565. proxy.visible = originalLight.visible;
  566. if ( originalLight instanceof THREE.PointLight ) {
  567. updatePointLightProxy( proxy );
  568. } else if ( originalLight instanceof THREE.SpotLight ) {
  569. updateSpotLightProxy( proxy );
  570. } else if ( originalLight instanceof THREE.DirectionalLight ) {
  571. updateDirectionalLightProxy( proxy );
  572. } else if ( originalLight instanceof THREE.HemisphereLight ) {
  573. updateHemisphereLightProxy( proxy );
  574. } else if ( originalLight instanceof THREE.AreaLight ) {
  575. updateAreaLightProxy( proxy );
  576. }
  577. }
  578. };
  579. this.render = function ( scene, camera ) {
  580. // setup deferred properties
  581. if ( ! scene.userData.lightSceneProxy ) {
  582. scene.userData.lightSceneProxy = new THREE.Scene();
  583. scene.userData.lightSceneFullscreen = new THREE.Scene();
  584. var meshLight = createDeferredEmissiveLight();
  585. scene.userData.lightSceneFullscreen.add( meshLight );
  586. }
  587. lightSceneProxy = scene.userData.lightSceneProxy;
  588. lightSceneFullscreen = scene.userData.lightSceneFullscreen;
  589. passColor.camera = camera;
  590. passNormalDepth.camera = camera;
  591. passLightProxy.camera = camera;
  592. passLightFullscreen.camera = THREE.EffectComposer.camera;
  593. passColor.scene = scene;
  594. passNormalDepth.scene = scene;
  595. passLightFullscreen.scene = lightSceneFullscreen;
  596. passLightProxy.scene = lightSceneProxy;
  597. scene.traverse( initDeferredProperties );
  598. // update scene graph only once per frame
  599. // (both color and normalDepth passes use exactly the same scene state)
  600. scene.autoUpdate = false;
  601. scene.updateMatrixWorld();
  602. // 1) g-buffer normals + depth pass
  603. scene.traverse( setMaterialNormalDepth );
  604. // clear shared depth buffer
  605. this.renderer.autoClearDepth = true;
  606. this.renderer.autoClearStencil = true;
  607. // write 1 to shared stencil buffer
  608. // for non-background pixels
  609. //gl.enable( gl.STENCIL_TEST );
  610. gl.stencilOp( gl.REPLACE, gl.REPLACE, gl.REPLACE );
  611. gl.stencilFunc( gl.ALWAYS, 1, 0xffffffff );
  612. gl.clearStencil( 0 );
  613. compNormalDepth.render();
  614. // just touch foreground pixels (stencil == 1)
  615. // both in color and light passes
  616. gl.stencilFunc( gl.EQUAL, 1, 0xffffffff );
  617. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  618. // 2) g-buffer color pass
  619. scene.traverse( setMaterialColor );
  620. // must use clean slate depth buffer
  621. // otherwise there are z-fighting glitches
  622. // not enough precision between two geometry passes
  623. // just to use EQUAL depth test
  624. this.renderer.autoClearDepth = true;
  625. this.renderer.autoClearStencil = false;
  626. compColor.render();
  627. // 3) light pass
  628. // do not clear depth buffer in this pass
  629. // depth from geometry pass is used for light culling
  630. // (write light proxy color pixel if behind scene pixel)
  631. this.renderer.autoClearDepth = false;
  632. scene.autoUpdate = true;
  633. gl.depthFunc( gl.GEQUAL );
  634. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  635. for ( var i = 0, il = lightSceneProxy.children.length; i < il; i ++ ) {
  636. var proxy = lightSceneProxy.children[ i ];
  637. updateLightProxy( proxy, camera );
  638. }
  639. for ( var i = 0, il = lightSceneFullscreen.children.length; i < il; i ++ ) {
  640. var proxy = lightSceneFullscreen.children[ i ];
  641. updateLightProxy( proxy, camera );
  642. }
  643. compLight.render();
  644. // 4) composite pass
  645. // return back to usual depth and stencil handling state
  646. this.renderer.autoClearDepth = true;
  647. this.renderer.autoClearStencil = true;
  648. gl.depthFunc( gl.LEQUAL );
  649. gl.disable( gl.STENCIL_TEST );
  650. compFinal.render( 0.1 );
  651. };
  652. //
  653. var createRenderTargets = function ( ) {
  654. var rtParamsFloatLinear = { minFilter: THREE.NearestFilter, magFilter: THREE.LinearFilter, stencilBuffer: true,
  655. format: THREE.RGBAFormat, type: THREE.FloatType };
  656. var rtParamsFloatNearest = { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, stencilBuffer: true,
  657. format: THREE.RGBAFormat, type: THREE.FloatType };
  658. var rtParamsUByte = { minFilter: THREE.NearestFilter, magFilter: THREE.LinearFilter, stencilBuffer: false,
  659. format: THREE.RGBFormat, type: THREE.UnsignedByteType };
  660. // g-buffers
  661. var rtColor = new THREE.WebGLRenderTarget( scaledWidth, scaledHeight, rtParamsFloatNearest );
  662. var rtNormalDepth = new THREE.WebGLRenderTarget( scaledWidth, scaledHeight, rtParamsFloatNearest );
  663. var rtLight = new THREE.WebGLRenderTarget( scaledWidth, scaledHeight, rtParamsFloatLinear );
  664. var rtFinal = new THREE.WebGLRenderTarget( scaledWidth, scaledHeight, rtParamsUByte );
  665. rtColor.generateMipmaps = false;
  666. rtNormalDepth.generateMipmaps = false;
  667. rtLight.generateMipmaps = false;
  668. rtFinal.generateMipmaps = false;
  669. // normal + depth composer
  670. passNormalDepth = new THREE.RenderPass();
  671. passNormalDepth.clear = true;
  672. compNormalDepth = new THREE.EffectComposer( _this.renderer, rtNormalDepth );
  673. compNormalDepth.addPass( passNormalDepth );
  674. // color composer
  675. passColor = new THREE.RenderPass();
  676. passColor.clear = true;
  677. compColor = new THREE.EffectComposer( _this.renderer, rtColor );
  678. compColor.addPass( passColor );
  679. compColor.renderTarget2.shareDepthFrom = compNormalDepth.renderTarget2;
  680. // light composer
  681. passLightFullscreen = new THREE.RenderPass();
  682. passLightFullscreen.clear = true;
  683. passLightProxy = new THREE.RenderPass();
  684. passLightProxy.clear = false;
  685. compLight = new THREE.EffectComposer( _this.renderer, rtLight );
  686. compLight.addPass( passLightFullscreen );
  687. compLight.addPass( passLightProxy );
  688. compLight.renderTarget2.shareDepthFrom = compNormalDepth.renderTarget2;
  689. // final composer
  690. compositePass = new THREE.ShaderPass( compositeShader );
  691. compositePass.uniforms[ 'samplerLight' ].value = compLight.renderTarget2;
  692. compositePass.uniforms[ 'brightness' ].value = brightness;
  693. compositePass.material.blending = THREE.NoBlending;
  694. compositePass.clear = true;
  695. var defines;
  696. switch ( tonemapping ) {
  697. case THREE.SimpleOperator: defines = { "TONEMAP_SIMPLE": true }; break;
  698. case THREE.LinearOperator: defines = { "TONEMAP_LINEAR": true }; break;
  699. case THREE.ReinhardOperator: defines = { "TONEMAP_REINHARD": true }; break;
  700. case THREE.FilmicOperator: defines = { "TONEMAP_FILMIC": true }; break;
  701. case THREE.UnchartedOperator: defines = { "TONEMAP_UNCHARTED": true }; break;
  702. }
  703. compositePass.material.defines = defines;
  704. // FXAA
  705. effectFXAA = new THREE.ShaderPass( THREE.FXAAShader );
  706. effectFXAA.uniforms[ 'resolution' ].value.set( 1 / fullWidth, 1 / fullHeight );
  707. effectFXAA.renderToScreen = true;
  708. //
  709. compFinal = new THREE.EffectComposer( _this.renderer, rtFinal );
  710. compFinal.addPass( compositePass );
  711. compFinal.addPass( effectFXAA );
  712. if ( antialias ) {
  713. effectFXAA.enabled = true;
  714. compositePass.renderToScreen = false;
  715. } else {
  716. effectFXAA.enabled = false;
  717. compositePass.renderToScreen = true;
  718. }
  719. };
  720. // init
  721. createRenderTargets();
  722. };
  723. // tonemapping operator types
  724. THREE.NoOperator = 0;
  725. THREE.SimpleOperator = 1;
  726. THREE.LinearOperator = 2;
  727. THREE.ReinhardOperator = 3;
  728. THREE.FilmicOperator = 4;
  729. THREE.UnchartedOperator = 5;