WebGLDeferredRenderer.js 31 KB

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