shadowGenerator.ts 65 KB

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