WebGLDeferredRenderer.js 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  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.properties.colorMaterial = new THREE.MeshFaceMaterial( colorMaterials );
  80. object.properties.normalDepthMaterial = new THREE.MeshFaceMaterial( normalDepthMaterials );
  81. } else {
  82. var deferredMaterials = createDeferredMaterials( object.material );
  83. object.properties.colorMaterial = deferredMaterials.colorMaterial;
  84. object.properties.normalDepthMaterial = deferredMaterials.normalDepthMaterial;
  85. object.properties.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.properties.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.properties.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.properties.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. viewMatrix.rotateAxis( directionVS );
  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.properties.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.properties.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. camera.matrixWorldInverse.rotateAxis( directionVS );
  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.properties.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.properties.originalLight;
  349. var uniforms = lightProxy.material.uniforms;
  350. directionVS.getPositionFromMatrix( light.matrixWorld );
  351. directionVS.normalize();
  352. camera.matrixWorldInverse.rotateAxis( directionVS );
  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.properties.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.properties.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. normalVS.copy( light.normal );
  396. modelMatrix.rotateAxis( rightVS );
  397. modelMatrix.rotateAxis( normalVS );
  398. viewMatrix.rotateAxis( rightVS );
  399. viewMatrix.rotateAxis( normalVS );
  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.properties.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.properties.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.properties.deferredInitialized = true;
  484. };
  485. //
  486. var setMaterialColor = function ( object ) {
  487. if ( object.material ) {
  488. if ( object.properties.transparent ) {
  489. object.material = invisibleMaterial;
  490. } else {
  491. object.material = object.properties.colorMaterial;
  492. }
  493. }
  494. };
  495. var setMaterialNormalDepth = function ( object ) {
  496. if ( object.material ) {
  497. if ( object.properties.transparent ) {
  498. object.material = invisibleMaterial;
  499. } else {
  500. object.material = object.properties.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.properties.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.properties.lightSceneProxy ) {
  582. scene.properties.lightSceneProxy = new THREE.Scene();
  583. scene.properties.lightSceneFullscreen = new THREE.Scene();
  584. var meshLight = createDeferredEmissiveLight();
  585. scene.properties.lightSceneFullscreen.add( meshLight );
  586. }
  587. lightSceneProxy = scene.properties.lightSceneProxy;
  588. lightSceneFullscreen = scene.properties.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. this.renderer.autoUpdateScene = 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. this.renderer.autoUpdateScene = 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;