shadowGenerator.ts 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681
  1. import { SmartArray } from "../../Misc/smartArray";
  2. import { Nullable } from "../../types";
  3. import { Scene } from "../../scene";
  4. import { Matrix, Vector3, Vector2, Color4 } from "../../Maths/math";
  5. import { VertexBuffer } from "../../Meshes/buffer";
  6. import { SubMesh } from "../../Meshes/subMesh";
  7. import { AbstractMesh } from "../../Meshes/abstractMesh";
  8. import { Mesh } from "../../Meshes/mesh";
  9. import { IShadowLight } from "../../Lights/shadowLight";
  10. import { Light } from "../../Lights/light";
  11. import { Material } from "../../Materials/material";
  12. import { MaterialDefines } from "../../Materials/materialDefines";
  13. import { MaterialHelper } from "../../Materials/materialHelper";
  14. import { Effect } from "../../Materials/effect";
  15. import { Texture } from "../../Materials/Textures/texture";
  16. import { RenderTargetTexture } from "../../Materials/Textures/renderTargetTexture";
  17. import { PostProcess } from "../../PostProcesses/postProcess";
  18. import { BlurPostProcess } from "../../PostProcesses/blurPostProcess";
  19. import { _TimeToken } from "../../Instrumentation/timeToken";
  20. import { _DepthCullingState, _StencilState, _AlphaState } from "../../States/index";
  21. import { Constants } from "../../Engines/constants";
  22. import "../../Shaders/shadowMap.fragment";
  23. import "../../Shaders/shadowMap.vertex";
  24. import "../../Shaders/depthBoxBlur.fragment";
  25. import { Observable } from '../../Misc/observable';
  26. import { _DevTools } from '../../Misc/devTools';
  27. /**
  28. * Defines the options associated with the creation of a custom shader for a shadow generator.
  29. */
  30. export interface ICustomShaderOptions {
  31. /**
  32. * Gets or sets the custom shader name to use
  33. */
  34. shaderName: string;
  35. /**
  36. * The list of attribute names used in the shader
  37. */
  38. attributes?: string[];
  39. /**
  40. * The list of unifrom names used in the shader
  41. */
  42. uniforms?: string[];
  43. /**
  44. * The list of sampler names used in the shader
  45. */
  46. samplers?: string[];
  47. /**
  48. * The list of defines used in the shader
  49. */
  50. defines?: string[];
  51. }
  52. /**
  53. * Interface to implement to create a shadow generator compatible with BJS.
  54. */
  55. export interface IShadowGenerator {
  56. /**
  57. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  58. * @returns The render target texture if present otherwise, null
  59. */
  60. getShadowMap(): Nullable<RenderTargetTexture>;
  61. /**
  62. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  63. * @returns The render target texture if the shadow map is present otherwise, null
  64. */
  65. getShadowMapForRendering(): Nullable<RenderTargetTexture>;
  66. /**
  67. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  68. * @param subMesh The submesh we want to render in the shadow map
  69. * @param useInstances Defines wether will draw in the map using instances
  70. * @returns true if ready otherwise, false
  71. */
  72. isReady(subMesh: SubMesh, useInstances: boolean): boolean;
  73. /**
  74. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  75. * @param defines Defines of the material we want to update
  76. * @param lightIndex Index of the light in the enabled light list of the material
  77. */
  78. prepareDefines(defines: MaterialDefines, lightIndex: number): void;
  79. /**
  80. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  81. * defined in the generator but impacting the effect).
  82. * It implies the unifroms available on the materials are the standard BJS ones.
  83. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  84. * @param effect The effect we are binfing the information for
  85. */
  86. bindShadowLight(lightIndex: string, effect: Effect): void;
  87. /**
  88. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  89. * (eq to shadow prjection matrix * light transform matrix)
  90. * @returns The transform matrix used to create the shadow map
  91. */
  92. getTransformMatrix(): Matrix;
  93. /**
  94. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  95. * Cube and 2D textures for instance.
  96. */
  97. recreateShadowMap(): void;
  98. /**
  99. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  100. * @param onCompiled Callback triggered at the and of the effects compilation
  101. * @param options Sets of optional options forcing the compilation with different modes
  102. */
  103. forceCompilation(onCompiled?: (generator: ShadowGenerator) => void, options?: Partial<{ useInstances: boolean }>): void;
  104. /**
  105. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  106. * @param options Sets of optional options forcing the compilation with different modes
  107. * @returns A promise that resolves when the compilation completes
  108. */
  109. forceCompilationAsync(options?: Partial<{ useInstances: boolean }>): Promise<void>;
  110. /**
  111. * Serializes the shadow generator setup to a json object.
  112. * @returns The serialized JSON object
  113. */
  114. serialize(): any;
  115. /**
  116. * Disposes the Shadow map and related Textures and effects.
  117. */
  118. dispose(): void;
  119. }
  120. /**
  121. * Default implementation IShadowGenerator.
  122. * This is the main object responsible of generating shadows in the framework.
  123. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  124. */
  125. export class ShadowGenerator implements IShadowGenerator {
  126. /**
  127. * Shadow generator mode None: no filtering applied.
  128. */
  129. public static readonly FILTER_NONE = 0;
  130. /**
  131. * Shadow generator mode ESM: Exponential Shadow Mapping.
  132. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  133. */
  134. public static readonly FILTER_EXPONENTIALSHADOWMAP = 1;
  135. /**
  136. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  137. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  138. */
  139. public static readonly FILTER_POISSONSAMPLING = 2;
  140. /**
  141. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  142. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  143. */
  144. public static readonly FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  145. /**
  146. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  147. * edge artifacts on steep falloff.
  148. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  149. */
  150. public static readonly FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  151. /**
  152. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  153. * edge artifacts on steep falloff.
  154. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  155. */
  156. public static readonly FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  157. /**
  158. * Shadow generator mode PCF: Percentage Closer Filtering
  159. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  160. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  161. */
  162. public static readonly FILTER_PCF = 6;
  163. /**
  164. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  165. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  166. * Contact Hardening
  167. */
  168. public static readonly FILTER_PCSS = 7;
  169. /**
  170. * Reserved for PCF and PCSS
  171. * Highest Quality.
  172. *
  173. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  174. *
  175. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  176. */
  177. public static readonly QUALITY_HIGH = 0;
  178. /**
  179. * Reserved for PCF and PCSS
  180. * Good tradeoff for quality/perf cross devices
  181. *
  182. * Execute PCF on a 3*3 kernel.
  183. *
  184. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  185. */
  186. public static readonly QUALITY_MEDIUM = 1;
  187. /**
  188. * Reserved for PCF and PCSS
  189. * The lowest quality but the fastest.
  190. *
  191. * Execute PCF on a 1*1 kernel.
  192. *
  193. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  194. */
  195. public static readonly QUALITY_LOW = 2;
  196. /** Gets or sets the custom shader name to use */
  197. public customShaderOptions: ICustomShaderOptions;
  198. /**
  199. * Observable triggered before the shadow is rendered. Can be used to update internal effect state
  200. */
  201. public onBeforeShadowMapRenderObservable = new Observable<Effect>();
  202. /**
  203. * Observable triggered after the shadow is rendered. Can be used to restore internal effect state
  204. */
  205. public onAfterShadowMapRenderObservable = new Observable<Effect>();
  206. /**
  207. * Observable triggered before a mesh is rendered in the shadow map.
  208. * Can be used to update internal effect state (that you can get from the onBeforeShadowMapRenderObservable)
  209. */
  210. public onBeforeShadowMapRenderMeshObservable = new Observable<Mesh>();
  211. /**
  212. * Observable triggered after a mesh is rendered in the shadow map.
  213. * Can be used to update internal effect state (that you can get from the onAfterShadowMapRenderObservable)
  214. */
  215. public onAfterShadowMapRenderMeshObservable = new Observable<Mesh>();
  216. private _bias = 0.00005;
  217. /**
  218. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  219. */
  220. public get bias(): number {
  221. return this._bias;
  222. }
  223. /**
  224. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  225. */
  226. public set bias(bias: number) {
  227. this._bias = bias;
  228. }
  229. private _normalBias = 0;
  230. /**
  231. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  232. */
  233. public get normalBias(): number {
  234. return this._normalBias;
  235. }
  236. /**
  237. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  238. */
  239. public set normalBias(normalBias: number) {
  240. this._normalBias = normalBias;
  241. }
  242. private _blurBoxOffset = 1;
  243. /**
  244. * Gets the blur box offset: offset applied during the blur pass.
  245. * Only useful if useKernelBlur = false
  246. */
  247. public get blurBoxOffset(): number {
  248. return this._blurBoxOffset;
  249. }
  250. /**
  251. * Sets the blur box offset: offset applied during the blur pass.
  252. * Only useful if useKernelBlur = false
  253. */
  254. public set blurBoxOffset(value: number) {
  255. if (this._blurBoxOffset === value) {
  256. return;
  257. }
  258. this._blurBoxOffset = value;
  259. this._disposeBlurPostProcesses();
  260. }
  261. private _blurScale = 2;
  262. /**
  263. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  264. * 2 means half of the size.
  265. */
  266. public get blurScale(): number {
  267. return this._blurScale;
  268. }
  269. /**
  270. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  271. * 2 means half of the size.
  272. */
  273. public set blurScale(value: number) {
  274. if (this._blurScale === value) {
  275. return;
  276. }
  277. this._blurScale = value;
  278. this._disposeBlurPostProcesses();
  279. }
  280. private _blurKernel = 1;
  281. /**
  282. * Gets the blur kernel: kernel size of the blur pass.
  283. * Only useful if useKernelBlur = true
  284. */
  285. public get blurKernel(): number {
  286. return this._blurKernel;
  287. }
  288. /**
  289. * Sets the blur kernel: kernel size of the blur pass.
  290. * Only useful if useKernelBlur = true
  291. */
  292. public set blurKernel(value: number) {
  293. if (this._blurKernel === value) {
  294. return;
  295. }
  296. this._blurKernel = value;
  297. this._disposeBlurPostProcesses();
  298. }
  299. private _useKernelBlur = false;
  300. /**
  301. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  302. * Only useful in filtered mode (useBlurExponentialShadowMap...)
  303. */
  304. public get useKernelBlur(): boolean {
  305. return this._useKernelBlur;
  306. }
  307. /**
  308. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  309. * Only useful in filtered mode (useBlurExponentialShadowMap...)
  310. */
  311. public set useKernelBlur(value: boolean) {
  312. if (this._useKernelBlur === value) {
  313. return;
  314. }
  315. this._useKernelBlur = value;
  316. this._disposeBlurPostProcesses();
  317. }
  318. private _depthScale: number;
  319. /**
  320. * Gets the depth scale used in ESM mode.
  321. */
  322. public get depthScale(): number {
  323. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  324. }
  325. /**
  326. * Sets the depth scale used in ESM mode.
  327. * This can override the scale stored on the light.
  328. */
  329. public set depthScale(value: number) {
  330. this._depthScale = value;
  331. }
  332. private _filter = ShadowGenerator.FILTER_NONE;
  333. /**
  334. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  335. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  336. */
  337. public get filter(): number {
  338. return this._filter;
  339. }
  340. /**
  341. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  342. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  343. */
  344. public set filter(value: number) {
  345. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  346. if (this._light.needCube()) {
  347. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  348. this.useExponentialShadowMap = true;
  349. return;
  350. }
  351. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  352. this.useCloseExponentialShadowMap = true;
  353. return;
  354. }
  355. // PCF on cubemap would also be expensive
  356. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  357. this.usePoissonSampling = true;
  358. return;
  359. }
  360. }
  361. // Weblg1 fallback for PCF.
  362. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  363. if (this._scene.getEngine().webGLVersion === 1) {
  364. this.usePoissonSampling = true;
  365. return;
  366. }
  367. }
  368. if (this._filter === value) {
  369. return;
  370. }
  371. this._filter = value;
  372. this._disposeBlurPostProcesses();
  373. this._applyFilterValues();
  374. this._light._markMeshesAsLightDirty();
  375. }
  376. /**
  377. * Gets if the current filter is set to Poisson Sampling.
  378. */
  379. public get usePoissonSampling(): boolean {
  380. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  381. }
  382. /**
  383. * Sets the current filter to Poisson Sampling.
  384. */
  385. public set usePoissonSampling(value: boolean) {
  386. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  387. return;
  388. }
  389. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  390. }
  391. /**
  392. * Gets if the current filter is set to ESM.
  393. */
  394. public get useExponentialShadowMap(): boolean {
  395. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  396. }
  397. /**
  398. * Sets the current filter is to ESM.
  399. */
  400. public set useExponentialShadowMap(value: boolean) {
  401. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  402. return;
  403. }
  404. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  405. }
  406. /**
  407. * Gets if the current filter is set to filtered ESM.
  408. */
  409. public get useBlurExponentialShadowMap(): boolean {
  410. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  411. }
  412. /**
  413. * Gets if the current filter is set to filtered ESM.
  414. */
  415. public set useBlurExponentialShadowMap(value: boolean) {
  416. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  417. return;
  418. }
  419. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  420. }
  421. /**
  422. * Gets if the current filter is set to "close ESM" (using the inverse of the
  423. * exponential to prevent steep falloff artifacts).
  424. */
  425. public get useCloseExponentialShadowMap(): boolean {
  426. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  427. }
  428. /**
  429. * Sets the current filter to "close ESM" (using the inverse of the
  430. * exponential to prevent steep falloff artifacts).
  431. */
  432. public set useCloseExponentialShadowMap(value: boolean) {
  433. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  434. return;
  435. }
  436. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  437. }
  438. /**
  439. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  440. * exponential to prevent steep falloff artifacts).
  441. */
  442. public get useBlurCloseExponentialShadowMap(): boolean {
  443. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  444. }
  445. /**
  446. * Sets the current filter to filtered "close ESM" (using the inverse of the
  447. * exponential to prevent steep falloff artifacts).
  448. */
  449. public set useBlurCloseExponentialShadowMap(value: boolean) {
  450. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  451. return;
  452. }
  453. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  454. }
  455. /**
  456. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  457. */
  458. public get usePercentageCloserFiltering(): boolean {
  459. return this.filter === ShadowGenerator.FILTER_PCF;
  460. }
  461. /**
  462. * Sets the current filter to "PCF" (percentage closer filtering).
  463. */
  464. public set usePercentageCloserFiltering(value: boolean) {
  465. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  466. return;
  467. }
  468. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  469. }
  470. private _filteringQuality = ShadowGenerator.QUALITY_HIGH;
  471. /**
  472. * Gets the PCF or PCSS Quality.
  473. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  474. */
  475. public get filteringQuality(): number {
  476. return this._filteringQuality;
  477. }
  478. /**
  479. * Sets the PCF or PCSS Quality.
  480. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  481. */
  482. public set filteringQuality(filteringQuality: number) {
  483. if (this._filteringQuality === filteringQuality) {
  484. return;
  485. }
  486. this._filteringQuality = filteringQuality;
  487. this._disposeBlurPostProcesses();
  488. this._applyFilterValues();
  489. this._light._markMeshesAsLightDirty();
  490. }
  491. /**
  492. * Gets if the current filter is set to "PCSS" (contact hardening).
  493. */
  494. public get useContactHardeningShadow(): boolean {
  495. return this.filter === ShadowGenerator.FILTER_PCSS;
  496. }
  497. /**
  498. * Sets the current filter to "PCSS" (contact hardening).
  499. */
  500. public set useContactHardeningShadow(value: boolean) {
  501. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  502. return;
  503. }
  504. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  505. }
  506. private _contactHardeningLightSizeUVRatio = 0.1;
  507. /**
  508. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  509. * Using a ratio helps keeping shape stability independently of the map size.
  510. *
  511. * It does not account for the light projection as it was having too much
  512. * instability during the light setup or during light position changes.
  513. *
  514. * Only valid if useContactHardeningShadow is true.
  515. */
  516. public get contactHardeningLightSizeUVRatio(): number {
  517. return this._contactHardeningLightSizeUVRatio;
  518. }
  519. /**
  520. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  521. * Using a ratio helps keeping shape stability independently of the map size.
  522. *
  523. * It does not account for the light projection as it was having too much
  524. * instability during the light setup or during light position changes.
  525. *
  526. * Only valid if useContactHardeningShadow is true.
  527. */
  528. public set contactHardeningLightSizeUVRatio(contactHardeningLightSizeUVRatio: number) {
  529. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  530. }
  531. private _darkness = 0;
  532. /** Gets or sets the actual darkness of a shadow */
  533. public get darkness() {
  534. return this._darkness;
  535. }
  536. public set darkness(value: number) {
  537. this.setDarkness(value);
  538. }
  539. /**
  540. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  541. * 0 means strongest and 1 would means no shadow.
  542. * @returns the darkness.
  543. */
  544. public getDarkness(): number {
  545. return this._darkness;
  546. }
  547. /**
  548. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  549. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  550. * @returns the shadow generator allowing fluent coding.
  551. */
  552. public setDarkness(darkness: number): ShadowGenerator {
  553. if (darkness >= 1.0) {
  554. this._darkness = 1.0;
  555. }
  556. else if (darkness <= 0.0) {
  557. this._darkness = 0.0;
  558. }
  559. else {
  560. this._darkness = darkness;
  561. }
  562. return this;
  563. }
  564. private _transparencyShadow = false;
  565. /** Gets or sets the ability to have transparent shadow */
  566. public get transparencyShadow() {
  567. return this._transparencyShadow;
  568. }
  569. public set transparencyShadow(value: boolean) {
  570. this.setTransparencyShadow(value);
  571. }
  572. /**
  573. * Sets the ability to have transparent shadow (boolean).
  574. * @param transparent True if transparent else False
  575. * @returns the shadow generator allowing fluent coding
  576. */
  577. public setTransparencyShadow(transparent: boolean): ShadowGenerator {
  578. this._transparencyShadow = transparent;
  579. return this;
  580. }
  581. private _shadowMap: Nullable<RenderTargetTexture>;
  582. private _shadowMap2: Nullable<RenderTargetTexture>;
  583. /**
  584. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  585. * @returns The render target texture if present otherwise, null
  586. */
  587. public getShadowMap(): Nullable<RenderTargetTexture> {
  588. return this._shadowMap;
  589. }
  590. /**
  591. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  592. * @returns The render target texture if the shadow map is present otherwise, null
  593. */
  594. public getShadowMapForRendering(): Nullable<RenderTargetTexture> {
  595. if (this._shadowMap2) {
  596. return this._shadowMap2;
  597. }
  598. return this._shadowMap;
  599. }
  600. /**
  601. * Gets the class name of that object
  602. * @returns "ShadowGenerator"
  603. */
  604. public getClassName(): string {
  605. return "ShadowGenerator";
  606. }
  607. /**
  608. * Helper function to add a mesh and its descendants to the list of shadow casters.
  609. * @param mesh Mesh to add
  610. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  611. * @returns the Shadow Generator itself
  612. */
  613. public addShadowCaster(mesh: AbstractMesh, includeDescendants = true): ShadowGenerator {
  614. if (!this._shadowMap) {
  615. return this;
  616. }
  617. if (!this._shadowMap.renderList) {
  618. this._shadowMap.renderList = [];
  619. }
  620. this._shadowMap.renderList.push(mesh);
  621. if (includeDescendants) {
  622. this._shadowMap.renderList.push(...mesh.getChildMeshes());
  623. }
  624. return this;
  625. }
  626. /**
  627. * Helper function to remove a mesh and its descendants from the list of shadow casters
  628. * @param mesh Mesh to remove
  629. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  630. * @returns the Shadow Generator itself
  631. */
  632. public removeShadowCaster(mesh: AbstractMesh, includeDescendants = true): ShadowGenerator {
  633. if (!this._shadowMap || !this._shadowMap.renderList) {
  634. return this;
  635. }
  636. var index = this._shadowMap.renderList.indexOf(mesh);
  637. if (index !== -1) {
  638. this._shadowMap.renderList.splice(index, 1);
  639. }
  640. if (includeDescendants) {
  641. for (var child of mesh.getChildren()) {
  642. this.removeShadowCaster(<any>child);
  643. }
  644. }
  645. return this;
  646. }
  647. /**
  648. * Controls the extent to which the shadows fade out at the edge of the frustum
  649. * Used only by directionals and spots
  650. */
  651. public frustumEdgeFalloff = 0;
  652. private _light: IShadowLight;
  653. /**
  654. * Returns the associated light object.
  655. * @returns the light generating the shadow
  656. */
  657. public getLight(): IShadowLight {
  658. return this._light;
  659. }
  660. /**
  661. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  662. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  663. * It might on the other hand introduce peter panning.
  664. */
  665. public forceBackFacesOnly = false;
  666. private _scene: Scene;
  667. private _lightDirection = Vector3.Zero();
  668. private _effect: Effect;
  669. private _viewMatrix = Matrix.Zero();
  670. private _projectionMatrix = Matrix.Zero();
  671. private _transformMatrix = Matrix.Zero();
  672. private _cachedPosition: Vector3 = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  673. private _cachedDirection: Vector3 = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  674. private _cachedDefines: string;
  675. private _currentRenderID: number;
  676. private _boxBlurPostprocess: Nullable<PostProcess>;
  677. private _kernelBlurXPostprocess: Nullable<PostProcess>;
  678. private _kernelBlurYPostprocess: Nullable<PostProcess>;
  679. private _blurPostProcesses: PostProcess[];
  680. private _mapSize: number;
  681. private _currentFaceIndex = 0;
  682. private _currentFaceIndexCache = 0;
  683. private _textureType: number;
  684. private _defaultTextureMatrix = Matrix.Identity();
  685. /** @hidden */
  686. public static _SceneComponentInitialization: (scene: Scene) => void = (_) => {
  687. throw _DevTools.WarnImport("ShadowGeneratorSceneComponent");
  688. }
  689. /**
  690. * Creates a ShadowGenerator object.
  691. * A ShadowGenerator is the required tool to use the shadows.
  692. * Each light casting shadows needs to use its own ShadowGenerator.
  693. * Documentation : https://doc.babylonjs.com/babylon101/shadows
  694. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  695. * @param light The light object generating the shadows.
  696. * @param usefulFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
  697. */
  698. constructor(mapSize: number, light: IShadowLight, usefulFloatFirst?: boolean) {
  699. this._mapSize = mapSize;
  700. this._light = light;
  701. this._scene = light.getScene();
  702. light._shadowGenerator = this;
  703. ShadowGenerator._SceneComponentInitialization(this._scene);
  704. // Texture type fallback from float to int if not supported.
  705. var caps = this._scene.getEngine().getCaps();
  706. if (!usefulFloatFirst) {
  707. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  708. this._textureType = Constants.TEXTURETYPE_HALF_FLOAT;
  709. }
  710. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  711. this._textureType = Constants.TEXTURETYPE_FLOAT;
  712. }
  713. else {
  714. this._textureType = Constants.TEXTURETYPE_UNSIGNED_INT;
  715. }
  716. } else {
  717. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  718. this._textureType = Constants.TEXTURETYPE_FLOAT;
  719. }
  720. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  721. this._textureType = Constants.TEXTURETYPE_HALF_FLOAT;
  722. }
  723. else {
  724. this._textureType = Constants.TEXTURETYPE_UNSIGNED_INT;
  725. }
  726. }
  727. this._initializeGenerator();
  728. this._applyFilterValues();
  729. }
  730. private _initializeGenerator(): void {
  731. this._light._markMeshesAsLightDirty();
  732. this._initializeShadowMap();
  733. }
  734. private _initializeShadowMap(): void {
  735. // Render target
  736. let engine = this._scene.getEngine();
  737. if (engine.webGLVersion > 1) {
  738. this._shadowMap = new RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  739. this._shadowMap.createDepthStencilTexture(Constants.LESS, true);
  740. }
  741. else {
  742. this._shadowMap = new RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  743. }
  744. this._shadowMap.wrapU = Texture.CLAMP_ADDRESSMODE;
  745. this._shadowMap.wrapV = Texture.CLAMP_ADDRESSMODE;
  746. this._shadowMap.anisotropicFilteringLevel = 1;
  747. this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
  748. this._shadowMap.renderParticles = false;
  749. this._shadowMap.ignoreCameraViewport = true;
  750. // Record Face Index before render.
  751. this._shadowMap.onBeforeRenderObservable.add((faceIndex: number) => {
  752. this._currentFaceIndex = faceIndex;
  753. if (this._filter === ShadowGenerator.FILTER_PCF) {
  754. engine.setColorWrite(false);
  755. }
  756. });
  757. // Custom render function.
  758. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  759. // Blur if required afer render.
  760. this._shadowMap.onAfterUnbindObservable.add(() => {
  761. if (this._filter === ShadowGenerator.FILTER_PCF) {
  762. engine.setColorWrite(true);
  763. }
  764. if (!this.useBlurExponentialShadowMap && !this.useBlurCloseExponentialShadowMap) {
  765. return;
  766. }
  767. let shadowMap = this.getShadowMapForRendering();
  768. if (shadowMap) {
  769. this._scene.postProcessManager.directRender(this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  770. }
  771. });
  772. // Clear according to the chosen filter.
  773. var clearZero = new Color4(0, 0, 0, 0);
  774. var clearOne = new Color4(1.0, 1.0, 1.0, 1.0);
  775. this._shadowMap.onClearObservable.add((engine) => {
  776. if (this._filter === ShadowGenerator.FILTER_PCF) {
  777. engine.clear(clearOne, false, true, false);
  778. }
  779. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  780. engine.clear(clearZero, true, true, false);
  781. }
  782. else {
  783. engine.clear(clearOne, true, true, false);
  784. }
  785. });
  786. }
  787. private _initializeBlurRTTAndPostProcesses(): void {
  788. var engine = this._scene.getEngine();
  789. var targetSize = this._mapSize / this.blurScale;
  790. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  791. this._shadowMap2 = new RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  792. this._shadowMap2.wrapU = Texture.CLAMP_ADDRESSMODE;
  793. this._shadowMap2.wrapV = Texture.CLAMP_ADDRESSMODE;
  794. this._shadowMap2.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
  795. }
  796. if (this.useKernelBlur) {
  797. this._kernelBlurXPostprocess = new BlurPostProcess(this._light.name + "KernelBlurX", new Vector2(1, 0), this.blurKernel, 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  798. this._kernelBlurXPostprocess.width = targetSize;
  799. this._kernelBlurXPostprocess.height = targetSize;
  800. this._kernelBlurXPostprocess.onApplyObservable.add((effect) => {
  801. effect.setTexture("textureSampler", this._shadowMap);
  802. });
  803. this._kernelBlurYPostprocess = new BlurPostProcess(this._light.name + "KernelBlurY", new Vector2(0, 1), this.blurKernel, 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  804. this._kernelBlurXPostprocess.autoClear = false;
  805. this._kernelBlurYPostprocess.autoClear = false;
  806. if (this._textureType === Constants.TEXTURETYPE_UNSIGNED_INT) {
  807. (<BlurPostProcess>this._kernelBlurXPostprocess).packedFloat = true;
  808. (<BlurPostProcess>this._kernelBlurYPostprocess).packedFloat = true;
  809. }
  810. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  811. }
  812. else {
  813. this._boxBlurPostprocess = new PostProcess(this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType);
  814. this._boxBlurPostprocess.onApplyObservable.add((effect) => {
  815. effect.setFloat2("screenSize", targetSize, targetSize);
  816. effect.setTexture("textureSampler", this._shadowMap);
  817. });
  818. this._boxBlurPostprocess.autoClear = false;
  819. this._blurPostProcesses = [this._boxBlurPostprocess];
  820. }
  821. }
  822. private _renderForShadowMap(opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>, depthOnlySubMeshes: SmartArray<SubMesh>): void {
  823. var index: number;
  824. let engine = this._scene.getEngine();
  825. if (depthOnlySubMeshes.length) {
  826. engine.setColorWrite(false);
  827. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  828. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  829. }
  830. engine.setColorWrite(true);
  831. }
  832. for (index = 0; index < opaqueSubMeshes.length; index++) {
  833. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  834. }
  835. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  836. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  837. }
  838. if (this._transparencyShadow) {
  839. for (index = 0; index < transparentSubMeshes.length; index++) {
  840. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  841. }
  842. }
  843. }
  844. private _renderSubMeshForShadowMap(subMesh: SubMesh): void {
  845. var mesh = subMesh.getRenderingMesh();
  846. var scene = this._scene;
  847. var engine = scene.getEngine();
  848. let material = subMesh.getMaterial();
  849. mesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;
  850. if (!material || subMesh.verticesCount === 0) {
  851. return;
  852. }
  853. // Culling
  854. engine.setState(material.backFaceCulling);
  855. // Managing instances
  856. var batch = mesh._getInstancesRenderList(subMesh._id);
  857. if (batch.mustReturn) {
  858. return;
  859. }
  860. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  861. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  862. engine.enableEffect(this._effect);
  863. mesh._bind(subMesh, this._effect, Material.TriangleFillMode);
  864. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  865. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  866. if (this.getLight().getTypeID() === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  867. this._effect.setVector3("lightData", this._cachedDirection);
  868. }
  869. else {
  870. this._effect.setVector3("lightData", this._cachedPosition);
  871. }
  872. if (scene.activeCamera) {
  873. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  874. }
  875. // Alpha test
  876. if (material && material.needAlphaTesting()) {
  877. var alphaTexture = material.getAlphaTestTexture();
  878. if (alphaTexture) {
  879. this._effect.setTexture("diffuseSampler", alphaTexture);
  880. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  881. }
  882. }
  883. // Bones
  884. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  885. const skeleton = mesh.skeleton;
  886. if (skeleton.isUsingTextureForMatrices) {
  887. const boneTexture = skeleton.getTransformMatrixTexture();
  888. if (!boneTexture) {
  889. return;
  890. }
  891. this._effect.setTexture("boneSampler", boneTexture);
  892. this._effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
  893. } else {
  894. this._effect.setMatrices("mBones", skeleton.getTransformMatrices((mesh)));
  895. }
  896. }
  897. // Morph targets
  898. MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  899. if (this.forceBackFacesOnly) {
  900. engine.setState(true, 0, false, true);
  901. }
  902. // Observables
  903. this.onBeforeShadowMapRenderMeshObservable.notifyObservers(mesh);
  904. this.onBeforeShadowMapRenderObservable.notifyObservers(this._effect);
  905. // Draw
  906. mesh._processRendering(subMesh, this._effect, Material.TriangleFillMode, batch, hardwareInstancedRendering,
  907. (isInstance, world) => this._effect.setMatrix("world", world));
  908. if (this.forceBackFacesOnly) {
  909. engine.setState(true, 0, false, false);
  910. }
  911. // Observables
  912. this.onAfterShadowMapRenderObservable.notifyObservers(this._effect);
  913. this.onAfterShadowMapRenderMeshObservable.notifyObservers(mesh);
  914. } else {
  915. // Need to reset refresh rate of the shadowMap
  916. if (this._shadowMap) {
  917. this._shadowMap.resetRefreshCounter();
  918. }
  919. }
  920. }
  921. private _applyFilterValues(): void {
  922. if (!this._shadowMap) {
  923. return;
  924. }
  925. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  926. this._shadowMap.updateSamplingMode(Texture.NEAREST_SAMPLINGMODE);
  927. } else {
  928. this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
  929. }
  930. }
  931. /**
  932. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  933. * @param onCompiled Callback triggered at the and of the effects compilation
  934. * @param options Sets of optional options forcing the compilation with different modes
  935. */
  936. public forceCompilation(onCompiled?: (generator: ShadowGenerator) => void, options?: Partial<{ useInstances: boolean }>): void {
  937. let localOptions = {
  938. useInstances: false,
  939. ...options
  940. };
  941. let shadowMap = this.getShadowMap();
  942. if (!shadowMap) {
  943. if (onCompiled) {
  944. onCompiled(this);
  945. }
  946. return;
  947. }
  948. let renderList = shadowMap.renderList;
  949. if (!renderList) {
  950. if (onCompiled) {
  951. onCompiled(this);
  952. }
  953. return;
  954. }
  955. var subMeshes = new Array<SubMesh>();
  956. for (var mesh of renderList) {
  957. subMeshes.push(...mesh.subMeshes);
  958. }
  959. if (subMeshes.length === 0) {
  960. if (onCompiled) {
  961. onCompiled(this);
  962. }
  963. return;
  964. }
  965. var currentIndex = 0;
  966. var checkReady = () => {
  967. if (!this._scene || !this._scene.getEngine()) {
  968. return;
  969. }
  970. while (this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  971. currentIndex++;
  972. if (currentIndex >= subMeshes.length) {
  973. if (onCompiled) {
  974. onCompiled(this);
  975. }
  976. return;
  977. }
  978. }
  979. setTimeout(checkReady, 16);
  980. };
  981. checkReady();
  982. }
  983. /**
  984. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  985. * @param options Sets of optional options forcing the compilation with different modes
  986. * @returns A promise that resolves when the compilation completes
  987. */
  988. public forceCompilationAsync(options?: Partial<{ useInstances: boolean }>): Promise<void> {
  989. return new Promise((resolve) => {
  990. this.forceCompilation(() => {
  991. resolve();
  992. }, options);
  993. });
  994. }
  995. /**
  996. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  997. * @param subMesh The submesh we want to render in the shadow map
  998. * @param useInstances Defines wether will draw in the map using instances
  999. * @returns true if ready otherwise, false
  1000. */
  1001. public isReady(subMesh: SubMesh, useInstances: boolean): boolean {
  1002. var defines = [];
  1003. if (this._textureType !== Constants.TEXTURETYPE_UNSIGNED_INT) {
  1004. defines.push("#define FLOAT");
  1005. }
  1006. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  1007. defines.push("#define ESM");
  1008. }
  1009. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  1010. defines.push("#define DEPTHTEXTURE");
  1011. }
  1012. var attribs = [VertexBuffer.PositionKind];
  1013. var mesh = subMesh.getMesh();
  1014. var material = subMesh.getMaterial();
  1015. // Normal bias.
  1016. if (this.normalBias && mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  1017. attribs.push(VertexBuffer.NormalKind);
  1018. defines.push("#define NORMAL");
  1019. if (mesh.nonUniformScaling) {
  1020. defines.push("#define NONUNIFORMSCALING");
  1021. }
  1022. if (this.getLight().getTypeID() === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  1023. defines.push("#define DIRECTIONINLIGHTDATA");
  1024. }
  1025. }
  1026. // Alpha test
  1027. if (material && material.needAlphaTesting()) {
  1028. var alphaTexture = material.getAlphaTestTexture();
  1029. if (alphaTexture) {
  1030. defines.push("#define ALPHATEST");
  1031. if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  1032. attribs.push(VertexBuffer.UVKind);
  1033. defines.push("#define UV1");
  1034. }
  1035. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
  1036. if (alphaTexture.coordinatesIndex === 1) {
  1037. attribs.push(VertexBuffer.UV2Kind);
  1038. defines.push("#define UV2");
  1039. }
  1040. }
  1041. }
  1042. }
  1043. // Bones
  1044. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  1045. attribs.push(VertexBuffer.MatricesIndicesKind);
  1046. attribs.push(VertexBuffer.MatricesWeightsKind);
  1047. if (mesh.numBoneInfluencers > 4) {
  1048. attribs.push(VertexBuffer.MatricesIndicesExtraKind);
  1049. attribs.push(VertexBuffer.MatricesWeightsExtraKind);
  1050. }
  1051. const skeleton = mesh.skeleton;
  1052. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  1053. if (skeleton.isUsingTextureForMatrices) {
  1054. defines.push("#define BONETEXTURE");
  1055. } else {
  1056. defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1));
  1057. }
  1058. } else {
  1059. defines.push("#define NUM_BONE_INFLUENCERS 0");
  1060. }
  1061. // Morph targets
  1062. var manager = (<Mesh>mesh).morphTargetManager;
  1063. let morphInfluencers = 0;
  1064. if (manager) {
  1065. if (manager.numInfluencers > 0) {
  1066. defines.push("#define MORPHTARGETS");
  1067. morphInfluencers = manager.numInfluencers;
  1068. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  1069. MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  1070. }
  1071. }
  1072. // Instances
  1073. if (useInstances) {
  1074. defines.push("#define INSTANCES");
  1075. attribs.push("world0");
  1076. attribs.push("world1");
  1077. attribs.push("world2");
  1078. attribs.push("world3");
  1079. }
  1080. if (this.customShaderOptions) {
  1081. if (this.customShaderOptions.defines) {
  1082. for (var define of this.customShaderOptions.defines) {
  1083. if (defines.indexOf(define) === -1) {
  1084. defines.push(define);
  1085. }
  1086. }
  1087. }
  1088. }
  1089. // Get correct effect
  1090. var join = defines.join("\n");
  1091. if (this._cachedDefines !== join) {
  1092. this._cachedDefines = join;
  1093. let shaderName = "shadowMap";
  1094. let uniforms = ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences", "boneTextureWidth"];
  1095. let samplers = ["diffuseSampler", "boneSampler"];
  1096. // Custom shader?
  1097. if (this.customShaderOptions) {
  1098. shaderName = this.customShaderOptions.shaderName;
  1099. if (this.customShaderOptions.attributes) {
  1100. for (var attrib of this.customShaderOptions.attributes) {
  1101. if (attribs.indexOf(attrib) === -1) {
  1102. attribs.push(attrib);
  1103. }
  1104. }
  1105. }
  1106. if (this.customShaderOptions.uniforms) {
  1107. for (var uniform of this.customShaderOptions.uniforms) {
  1108. if (uniforms.indexOf(uniform) === -1) {
  1109. uniforms.push(uniform);
  1110. }
  1111. }
  1112. }
  1113. if (this.customShaderOptions.samplers) {
  1114. for (var sampler of this.customShaderOptions.samplers) {
  1115. if (samplers.indexOf(sampler) === -1) {
  1116. samplers.push(sampler);
  1117. }
  1118. }
  1119. }
  1120. }
  1121. this._effect = this._scene.getEngine().createEffect(shaderName,
  1122. attribs, uniforms,
  1123. samplers, join,
  1124. undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  1125. }
  1126. if (!this._effect.isReady()) {
  1127. return false;
  1128. }
  1129. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  1130. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  1131. this._initializeBlurRTTAndPostProcesses();
  1132. }
  1133. }
  1134. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  1135. return false;
  1136. }
  1137. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  1138. return false;
  1139. }
  1140. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  1141. return false;
  1142. }
  1143. return true;
  1144. }
  1145. /**
  1146. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  1147. * @param defines Defines of the material we want to update
  1148. * @param lightIndex Index of the light in the enabled light list of the material
  1149. */
  1150. public prepareDefines(defines: any, lightIndex: number): void {
  1151. var scene = this._scene;
  1152. var light = this._light;
  1153. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  1154. return;
  1155. }
  1156. defines["SHADOW" + lightIndex] = true;
  1157. if (this.useContactHardeningShadow) {
  1158. defines["SHADOWPCSS" + lightIndex] = true;
  1159. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  1160. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  1161. }
  1162. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  1163. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  1164. }
  1165. // else default to high.
  1166. }
  1167. if (this.usePercentageCloserFiltering) {
  1168. defines["SHADOWPCF" + lightIndex] = true;
  1169. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  1170. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  1171. }
  1172. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  1173. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  1174. }
  1175. // else default to high.
  1176. }
  1177. else if (this.usePoissonSampling) {
  1178. defines["SHADOWPOISSON" + lightIndex] = true;
  1179. }
  1180. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  1181. defines["SHADOWESM" + lightIndex] = true;
  1182. }
  1183. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  1184. defines["SHADOWCLOSEESM" + lightIndex] = true;
  1185. }
  1186. if (light.needCube()) {
  1187. defines["SHADOWCUBE" + lightIndex] = true;
  1188. }
  1189. }
  1190. /**
  1191. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  1192. * defined in the generator but impacting the effect).
  1193. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  1194. * @param effect The effect we are binfing the information for
  1195. */
  1196. public bindShadowLight(lightIndex: string, effect: Effect): void {
  1197. var light = this._light;
  1198. var scene = this._scene;
  1199. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  1200. return;
  1201. }
  1202. let camera = scene.activeCamera;
  1203. if (!camera) {
  1204. return;
  1205. }
  1206. let shadowMap = this.getShadowMap();
  1207. if (!shadowMap) {
  1208. return;
  1209. }
  1210. if (!light.needCube()) {
  1211. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  1212. }
  1213. // Only PCF uses depth stencil texture.
  1214. if (this._filter === ShadowGenerator.FILTER_PCF) {
  1215. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  1216. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  1217. }
  1218. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  1219. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  1220. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  1221. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  1222. }
  1223. else {
  1224. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  1225. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  1226. }
  1227. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  1228. }
  1229. /**
  1230. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  1231. * (eq to shadow prjection matrix * light transform matrix)
  1232. * @returns The transform matrix used to create the shadow map
  1233. */
  1234. public getTransformMatrix(): Matrix {
  1235. var scene = this._scene;
  1236. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  1237. return this._transformMatrix;
  1238. }
  1239. this._currentRenderID = scene.getRenderId();
  1240. this._currentFaceIndexCache = this._currentFaceIndex;
  1241. var lightPosition = this._light.position;
  1242. if (this._light.computeTransformedInformation()) {
  1243. lightPosition = this._light.transformedPosition;
  1244. }
  1245. Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  1246. if (Math.abs(Vector3.Dot(this._lightDirection, Vector3.Up())) === 1.0) {
  1247. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  1248. }
  1249. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  1250. this._cachedPosition.copyFrom(lightPosition);
  1251. this._cachedDirection.copyFrom(this._lightDirection);
  1252. Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), Vector3.Up(), this._viewMatrix);
  1253. let shadowMap = this.getShadowMap();
  1254. if (shadowMap) {
  1255. let renderList = shadowMap.renderList;
  1256. if (renderList) {
  1257. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  1258. }
  1259. }
  1260. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  1261. }
  1262. return this._transformMatrix;
  1263. }
  1264. /**
  1265. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  1266. * Cube and 2D textures for instance.
  1267. */
  1268. public recreateShadowMap(): void {
  1269. let shadowMap = this._shadowMap;
  1270. if (!shadowMap) {
  1271. return;
  1272. }
  1273. // Track render list.
  1274. var renderList = shadowMap.renderList;
  1275. // Clean up existing data.
  1276. this._disposeRTTandPostProcesses();
  1277. // Reinitializes.
  1278. this._initializeGenerator();
  1279. // Reaffect the filter to ensure a correct fallback if necessary.
  1280. this.filter = this.filter;
  1281. // Reaffect the filter.
  1282. this._applyFilterValues();
  1283. // Reaffect Render List.
  1284. this._shadowMap!.renderList = renderList;
  1285. }
  1286. private _disposeBlurPostProcesses(): void {
  1287. if (this._shadowMap2) {
  1288. this._shadowMap2.dispose();
  1289. this._shadowMap2 = null;
  1290. }
  1291. if (this._boxBlurPostprocess) {
  1292. this._boxBlurPostprocess.dispose();
  1293. this._boxBlurPostprocess = null;
  1294. }
  1295. if (this._kernelBlurXPostprocess) {
  1296. this._kernelBlurXPostprocess.dispose();
  1297. this._kernelBlurXPostprocess = null;
  1298. }
  1299. if (this._kernelBlurYPostprocess) {
  1300. this._kernelBlurYPostprocess.dispose();
  1301. this._kernelBlurYPostprocess = null;
  1302. }
  1303. this._blurPostProcesses = [];
  1304. }
  1305. private _disposeRTTandPostProcesses(): void {
  1306. if (this._shadowMap) {
  1307. this._shadowMap.dispose();
  1308. this._shadowMap = null;
  1309. }
  1310. this._disposeBlurPostProcesses();
  1311. }
  1312. /**
  1313. * Disposes the ShadowGenerator.
  1314. * Returns nothing.
  1315. */
  1316. public dispose(): void {
  1317. this._disposeRTTandPostProcesses();
  1318. if (this._light) {
  1319. this._light._shadowGenerator = null;
  1320. this._light._markMeshesAsLightDirty();
  1321. }
  1322. this.onBeforeShadowMapRenderMeshObservable.clear();
  1323. this.onBeforeShadowMapRenderObservable.clear();
  1324. this.onAfterShadowMapRenderMeshObservable.clear();
  1325. this.onAfterShadowMapRenderObservable.clear();
  1326. }
  1327. /**
  1328. * Serializes the shadow generator setup to a json object.
  1329. * @returns The serialized JSON object
  1330. */
  1331. public serialize(): any {
  1332. var serializationObject: any = {};
  1333. var shadowMap = this.getShadowMap();
  1334. if (!shadowMap) {
  1335. return serializationObject;
  1336. }
  1337. serializationObject.lightId = this._light.id;
  1338. serializationObject.mapSize = shadowMap.getRenderSize();
  1339. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  1340. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  1341. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  1342. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  1343. serializationObject.usePoissonSampling = this.usePoissonSampling;
  1344. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  1345. serializationObject.depthScale = this.depthScale;
  1346. serializationObject.darkness = this.getDarkness();
  1347. serializationObject.blurBoxOffset = this.blurBoxOffset;
  1348. serializationObject.blurKernel = this.blurKernel;
  1349. serializationObject.blurScale = this.blurScale;
  1350. serializationObject.useKernelBlur = this.useKernelBlur;
  1351. serializationObject.transparencyShadow = this._transparencyShadow;
  1352. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  1353. serializationObject.bias = this.bias;
  1354. serializationObject.normalBias = this.normalBias;
  1355. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  1356. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  1357. serializationObject.filteringQuality = this.filteringQuality;
  1358. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  1359. serializationObject.renderList = [];
  1360. if (shadowMap.renderList) {
  1361. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  1362. var mesh = shadowMap.renderList[meshIndex];
  1363. serializationObject.renderList.push(mesh.id);
  1364. }
  1365. }
  1366. return serializationObject;
  1367. }
  1368. /**
  1369. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  1370. * @param parsedShadowGenerator The JSON object to parse
  1371. * @param scene The scene to create the shadow map for
  1372. * @returns The parsed shadow generator
  1373. */
  1374. public static Parse(parsedShadowGenerator: any, scene: Scene): ShadowGenerator {
  1375. var light = <IShadowLight>scene.getLightByID(parsedShadowGenerator.lightId);
  1376. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  1377. var shadowMap = shadowGenerator.getShadowMap();
  1378. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  1379. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  1380. meshes.forEach(function(mesh) {
  1381. if (!shadowMap) {
  1382. return;
  1383. }
  1384. if (!shadowMap.renderList) {
  1385. shadowMap.renderList = [];
  1386. }
  1387. shadowMap.renderList.push(mesh);
  1388. });
  1389. }
  1390. if (parsedShadowGenerator.usePoissonSampling) {
  1391. shadowGenerator.usePoissonSampling = true;
  1392. }
  1393. else if (parsedShadowGenerator.useExponentialShadowMap) {
  1394. shadowGenerator.useExponentialShadowMap = true;
  1395. }
  1396. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  1397. shadowGenerator.useBlurExponentialShadowMap = true;
  1398. }
  1399. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  1400. shadowGenerator.useCloseExponentialShadowMap = true;
  1401. }
  1402. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  1403. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  1404. }
  1405. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  1406. shadowGenerator.usePercentageCloserFiltering = true;
  1407. }
  1408. else if (parsedShadowGenerator.useContactHardeningShadow) {
  1409. shadowGenerator.useContactHardeningShadow = true;
  1410. }
  1411. if (parsedShadowGenerator.filteringQuality) {
  1412. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  1413. }
  1414. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  1415. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  1416. }
  1417. // Backward compat
  1418. else if (parsedShadowGenerator.useVarianceShadowMap) {
  1419. shadowGenerator.useExponentialShadowMap = true;
  1420. }
  1421. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  1422. shadowGenerator.useBlurExponentialShadowMap = true;
  1423. }
  1424. if (parsedShadowGenerator.depthScale) {
  1425. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  1426. }
  1427. if (parsedShadowGenerator.blurScale) {
  1428. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  1429. }
  1430. if (parsedShadowGenerator.blurBoxOffset) {
  1431. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  1432. }
  1433. if (parsedShadowGenerator.useKernelBlur) {
  1434. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  1435. }
  1436. if (parsedShadowGenerator.blurKernel) {
  1437. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  1438. }
  1439. if (parsedShadowGenerator.bias !== undefined) {
  1440. shadowGenerator.bias = parsedShadowGenerator.bias;
  1441. }
  1442. if (parsedShadowGenerator.normalBias !== undefined) {
  1443. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  1444. }
  1445. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  1446. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  1447. }
  1448. if (parsedShadowGenerator.darkness) {
  1449. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  1450. }
  1451. if (parsedShadowGenerator.transparencyShadow) {
  1452. shadowGenerator.setTransparencyShadow(true);
  1453. }
  1454. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  1455. return shadowGenerator;
  1456. }
  1457. }