babylon.shadowGenerator.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. module BABYLON {
  2. export class ShadowGenerator {
  3. private static _FILTER_NONE = 0;
  4. private static _FILTER_VARIANCESHADOWMAP = 1;
  5. private static _FILTER_POISSONSAMPLING = 2;
  6. private static _FILTER_BLURVARIANCESHADOWMAP = 3;
  7. // Static
  8. public static get FILTER_NONE(): number {
  9. return ShadowGenerator._FILTER_NONE;
  10. }
  11. public static get FILTER_VARIANCESHADOWMAP(): number {
  12. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  13. }
  14. public static get FILTER_POISSONSAMPLING(): number {
  15. return ShadowGenerator._FILTER_POISSONSAMPLING;
  16. }
  17. public static get FILTER_BLURVARIANCESHADOWMAP(): number {
  18. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  19. }
  20. // Members
  21. private _filter = ShadowGenerator.FILTER_NONE;
  22. public blurScale = 2;
  23. private _blurBoxOffset = 0;
  24. private _bias = 0.00005;
  25. private _lightDirection = Vector3.Zero();
  26. public forceBackFacesOnly = false;
  27. public get bias(): number {
  28. return this._bias;
  29. }
  30. public set bias(bias: number) {
  31. this._bias = bias;
  32. }
  33. public get blurBoxOffset(): number {
  34. return this._blurBoxOffset;
  35. }
  36. public set blurBoxOffset(value: number) {
  37. if (this._blurBoxOffset === value) {
  38. return;
  39. }
  40. this._blurBoxOffset = value;
  41. if (this._boxBlurPostprocess) {
  42. this._boxBlurPostprocess.dispose();
  43. }
  44. this._boxBlurPostprocess = new PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  45. this._boxBlurPostprocess.onApply = effect => {
  46. effect.setFloat2("screenSize", this._mapSize / this.blurScale, this._mapSize / this.blurScale);
  47. };
  48. }
  49. public get filter(): number {
  50. return this._filter;
  51. }
  52. public set filter(value: number) {
  53. if (this._filter === value) {
  54. return;
  55. }
  56. this._filter = value;
  57. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  58. this._shadowMap.anisotropicFilteringLevel = 16;
  59. this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
  60. } else {
  61. this._shadowMap.anisotropicFilteringLevel = 1;
  62. this._shadowMap.updateSamplingMode(Texture.NEAREST_SAMPLINGMODE);
  63. }
  64. }
  65. public get useVarianceShadowMap(): boolean {
  66. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  67. }
  68. public set useVarianceShadowMap(value: boolean) {
  69. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  70. }
  71. public get usePoissonSampling(): boolean {
  72. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  73. (!this._light.supportsVSM() && (
  74. this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  75. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP
  76. ));
  77. }
  78. public set usePoissonSampling(value: boolean) {
  79. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  80. }
  81. public get useBlurVarianceShadowMap(): boolean {
  82. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  83. }
  84. public set useBlurVarianceShadowMap(value: boolean) {
  85. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  86. }
  87. private _light: IShadowLight;
  88. private _scene: Scene;
  89. private _shadowMap: RenderTargetTexture;
  90. private _shadowMap2: RenderTargetTexture;
  91. private _darkness = 0;
  92. private _transparencyShadow = false;
  93. private _effect: Effect;
  94. private _viewMatrix = Matrix.Zero();
  95. private _projectionMatrix = Matrix.Zero();
  96. private _transformMatrix = Matrix.Zero();
  97. private _worldViewProjection = Matrix.Zero();
  98. private _cachedPosition: Vector3;
  99. private _cachedDirection: Vector3;
  100. private _cachedDefines: string;
  101. private _currentRenderID: number;
  102. private _downSamplePostprocess: PassPostProcess;
  103. private _boxBlurPostprocess: PostProcess;
  104. private _mapSize: number;
  105. private _currentFaceIndex = 0;
  106. private _currentFaceIndexCache = 0;
  107. constructor(mapSize: number, light: IShadowLight) {
  108. this._light = light;
  109. this._scene = light.getScene();
  110. this._mapSize = mapSize;
  111. light._shadowGenerator = this;
  112. // Render target
  113. this._shadowMap = new RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  114. this._shadowMap.wrapU = Texture.CLAMP_ADDRESSMODE;
  115. this._shadowMap.wrapV = Texture.CLAMP_ADDRESSMODE;
  116. this._shadowMap.anisotropicFilteringLevel = 1;
  117. this._shadowMap.updateSamplingMode(Texture.NEAREST_SAMPLINGMODE);
  118. this._shadowMap.renderParticles = false;
  119. this._shadowMap.onBeforeRender = (faceIndex: number) => {
  120. this._currentFaceIndex = faceIndex;
  121. }
  122. this._shadowMap.onAfterUnbind = () => {
  123. if (!this.useBlurVarianceShadowMap) {
  124. return;
  125. }
  126. if (!this._shadowMap2) {
  127. this._shadowMap2 = new RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  128. this._shadowMap2.wrapU = Texture.CLAMP_ADDRESSMODE;
  129. this._shadowMap2.wrapV = Texture.CLAMP_ADDRESSMODE;
  130. this._shadowMap2.updateSamplingMode(Texture.TRILINEAR_SAMPLINGMODE);
  131. this._downSamplePostprocess = new PassPostProcess("downScale", 1.0 / this.blurScale, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  132. this._downSamplePostprocess.onApply = effect => {
  133. effect.setTexture("textureSampler", this._shadowMap);
  134. };
  135. this.blurBoxOffset = 1;
  136. }
  137. this._scene.postProcessManager.directRender([this._downSamplePostprocess, this._boxBlurPostprocess], this._shadowMap2.getInternalTexture());
  138. }
  139. // Custom render function
  140. var renderSubMesh = (subMesh: SubMesh): void => {
  141. var mesh = subMesh.getRenderingMesh();
  142. var scene = this._scene;
  143. var engine = scene.getEngine();
  144. // Culling
  145. engine.setState(subMesh.getMaterial().backFaceCulling);
  146. // Managing instances
  147. var batch = mesh._getInstancesRenderList(subMesh._id);
  148. if (batch.mustReturn) {
  149. return;
  150. }
  151. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  152. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  153. engine.enableEffect(this._effect);
  154. mesh._bind(subMesh, this._effect, Material.TriangleFillMode);
  155. var material = subMesh.getMaterial();
  156. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  157. this._effect.setVector3("lightPosition", this.getLight().position);
  158. if (this.getLight().needCube()) {
  159. this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  160. }
  161. // Alpha test
  162. if (material && material.needAlphaTesting()) {
  163. var alphaTexture = material.getAlphaTestTexture();
  164. this._effect.setTexture("diffuseSampler", alphaTexture);
  165. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  166. }
  167. // Bones
  168. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  169. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  170. }
  171. if (this.forceBackFacesOnly) {
  172. engine.setState(true, 0, false, true);
  173. }
  174. // Draw
  175. mesh._processRendering(subMesh, this._effect, Material.TriangleFillMode, batch, hardwareInstancedRendering,
  176. (isInstance, world) => this._effect.setMatrix("world", world));
  177. if (this.forceBackFacesOnly) {
  178. engine.setState(true, 0, false, false);
  179. }
  180. } else {
  181. // Need to reset refresh rate of the shadowMap
  182. this._shadowMap.resetRefreshCounter();
  183. }
  184. };
  185. this._shadowMap.customRenderFunction = (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>): void => {
  186. var index: number;
  187. for (index = 0; index < opaqueSubMeshes.length; index++) {
  188. renderSubMesh(opaqueSubMeshes.data[index]);
  189. }
  190. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  191. renderSubMesh(alphaTestSubMeshes.data[index]);
  192. }
  193. if (this._transparencyShadow) {
  194. for (index = 0; index < transparentSubMeshes.length; index++) {
  195. renderSubMesh(transparentSubMeshes.data[index]);
  196. }
  197. }
  198. };
  199. this._shadowMap.onClear = (engine: Engine) => {
  200. if (this.useBlurVarianceShadowMap || this.useVarianceShadowMap) {
  201. engine.clear(new Color4(0, 0, 0, 0), true, true);
  202. } else {
  203. engine.clear(new Color4(1.0, 1.0, 1.0, 1.0), true, true);
  204. }
  205. }
  206. }
  207. public isReady(subMesh: SubMesh, useInstances: boolean): boolean {
  208. var defines = [];
  209. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  210. defines.push("#define VSM");
  211. }
  212. if (this.getLight().needCube()) {
  213. defines.push("#define CUBEMAP");
  214. }
  215. var attribs = [VertexBuffer.PositionKind];
  216. var mesh = subMesh.getMesh();
  217. var material = subMesh.getMaterial();
  218. // Alpha test
  219. if (material && material.needAlphaTesting()) {
  220. defines.push("#define ALPHATEST");
  221. if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  222. attribs.push(VertexBuffer.UVKind);
  223. defines.push("#define UV1");
  224. }
  225. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
  226. attribs.push(VertexBuffer.UV2Kind);
  227. defines.push("#define UV2");
  228. }
  229. }
  230. // Bones
  231. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  232. attribs.push(VertexBuffer.MatricesIndicesKind);
  233. attribs.push(VertexBuffer.MatricesWeightsKind);
  234. if (mesh.numBoneInfluencers > 4) {
  235. attribs.push(VertexBuffer.MatricesIndicesExtraKind);
  236. attribs.push(VertexBuffer.MatricesWeightsExtraKind);
  237. }
  238. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  239. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  240. } else {
  241. defines.push("#define NUM_BONE_INFLUENCERS 0");
  242. }
  243. // Instances
  244. if (useInstances) {
  245. defines.push("#define INSTANCES");
  246. attribs.push("world0");
  247. attribs.push("world1");
  248. attribs.push("world2");
  249. attribs.push("world3");
  250. }
  251. // Get correct effect
  252. var join = defines.join("\n");
  253. if (this._cachedDefines !== join) {
  254. this._cachedDefines = join;
  255. this._effect = this._scene.getEngine().createEffect("shadowMap",
  256. attribs,
  257. ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"],
  258. ["diffuseSampler"], join);
  259. }
  260. return this._effect.isReady();
  261. }
  262. public getShadowMap(): RenderTargetTexture {
  263. return this._shadowMap;
  264. }
  265. public getShadowMapForRendering(): RenderTargetTexture {
  266. if (this._shadowMap2) {
  267. return this._shadowMap2;
  268. }
  269. return this._shadowMap;
  270. }
  271. public getLight(): IShadowLight {
  272. return this._light;
  273. }
  274. // Methods
  275. public getTransformMatrix(): Matrix {
  276. var scene = this._scene;
  277. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  278. return this._transformMatrix;
  279. }
  280. this._currentRenderID = scene.getRenderId();
  281. this._currentFaceIndexCache = this._currentFaceIndex;
  282. var lightPosition = this._light.position;
  283. Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  284. if (Math.abs(Vector3.Dot(this._lightDirection, Vector3.Up())) === 1.0) {
  285. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  286. }
  287. if (this._light.computeTransformedPosition()) {
  288. lightPosition = this._light.transformedPosition;
  289. }
  290. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  291. this._cachedPosition = lightPosition.clone();
  292. this._cachedDirection = this._lightDirection.clone();
  293. Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), Vector3.Up(), this._viewMatrix);
  294. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  295. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  296. }
  297. return this._transformMatrix;
  298. }
  299. public getDarkness(): number {
  300. return this._darkness;
  301. }
  302. public setDarkness(darkness: number): void {
  303. if (darkness >= 1.0)
  304. this._darkness = 1.0;
  305. else if (darkness <= 0.0)
  306. this._darkness = 0.0;
  307. else
  308. this._darkness = darkness;
  309. }
  310. public setTransparencyShadow(hasShadow: boolean): void {
  311. this._transparencyShadow = hasShadow;
  312. }
  313. private _packHalf(depth: number): Vector2 {
  314. var scale = depth * 255.0;
  315. var fract = scale - Math.floor(scale);
  316. return new Vector2(depth - fract / 255.0, fract);
  317. }
  318. public dispose(): void {
  319. this._shadowMap.dispose();
  320. if (this._shadowMap2) {
  321. this._shadowMap2.dispose();
  322. }
  323. if (this._downSamplePostprocess) {
  324. this._downSamplePostprocess.dispose();
  325. }
  326. if (this._boxBlurPostprocess) {
  327. this._boxBlurPostprocess.dispose();
  328. }
  329. }
  330. public serialize(): any {
  331. var serializationObject: any = {};
  332. serializationObject.lightId = this._light.id;
  333. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  334. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  335. serializationObject.usePoissonSampling = this.usePoissonSampling;
  336. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  337. serializationObject.renderList = [];
  338. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  339. var mesh = this.getShadowMap().renderList[meshIndex];
  340. serializationObject.renderList.push(mesh.id);
  341. }
  342. return serializationObject;
  343. }
  344. public static Parse(parsedShadowGenerator: any, scene: Scene): ShadowGenerator {
  345. //casting to point light, as light is missing the position attr and typescript complains.
  346. var light = <PointLight>scene.getLightByID(parsedShadowGenerator.lightId);
  347. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  348. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  349. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  350. shadowGenerator.getShadowMap().renderList.push(mesh);
  351. }
  352. if (parsedShadowGenerator.usePoissonSampling) {
  353. shadowGenerator.usePoissonSampling = true;
  354. } else if (parsedShadowGenerator.useVarianceShadowMap) {
  355. shadowGenerator.useVarianceShadowMap = true;
  356. } else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  357. shadowGenerator.useBlurVarianceShadowMap = true;
  358. if (parsedShadowGenerator.blurScale) {
  359. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  360. }
  361. if (parsedShadowGenerator.blurBoxOffset) {
  362. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  363. }
  364. }
  365. if (parsedShadowGenerator.bias !== undefined) {
  366. shadowGenerator.bias = parsedShadowGenerator.bias;
  367. }
  368. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  369. return shadowGenerator;
  370. }
  371. }
  372. }