babylon.shadowGenerator.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. public filter = ShadowGenerator.FILTER_NONE;
  22. public blurScale = 2;
  23. private _blurBoxOffset = 0;
  24. public get blurBoxOffset(): number {
  25. return this._blurBoxOffset;
  26. }
  27. public set blurBoxOffset(value:number) {
  28. if (this._blurBoxOffset === value) {
  29. return;
  30. }
  31. this._blurBoxOffset = value;
  32. if (this._boxBlurPostprocess) {
  33. this._boxBlurPostprocess.dispose();
  34. }
  35. this._boxBlurPostprocess = new PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  36. this._boxBlurPostprocess.onApply = effect => {
  37. effect.setFloat2("screenSize", this._mapSize / this.blurScale, this._mapSize / this.blurScale);
  38. };
  39. }
  40. public get useVarianceShadowMap(): boolean {
  41. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  42. }
  43. public set useVarianceShadowMap(value: boolean) {
  44. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  45. }
  46. public get usePoissonSampling(): boolean {
  47. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  48. (!this._light.supportsVSM() && (
  49. this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  50. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP
  51. ));
  52. }
  53. public set usePoissonSampling(value: boolean) {
  54. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  55. }
  56. public get useBlurVarianceShadowMap(): boolean {
  57. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  58. }
  59. public set useBlurVarianceShadowMap(value: boolean) {
  60. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  61. }
  62. private _light: IShadowLight;
  63. private _scene: Scene;
  64. private _shadowMap: RenderTargetTexture;
  65. private _shadowMap2: RenderTargetTexture;
  66. private _darkness = 0;
  67. private _bias = 0.00005;
  68. private _transparencyShadow = false;
  69. private _effect: Effect;
  70. private _viewMatrix = Matrix.Zero();
  71. private _projectionMatrix = Matrix.Zero();
  72. private _transformMatrix = Matrix.Zero();
  73. private _worldViewProjection = Matrix.Zero();
  74. private _cachedPosition: Vector3;
  75. private _cachedDirection: Vector3;
  76. private _cachedDefines: string;
  77. private _currentRenderID: number;
  78. private _downSamplePostprocess: PassPostProcess;
  79. private _boxBlurPostprocess: PostProcess;
  80. private _mapSize: number;
  81. constructor(mapSize: number, light: IShadowLight) {
  82. this._light = light;
  83. this._scene = light.getScene();
  84. this._mapSize = mapSize;
  85. light._shadowGenerator = this;
  86. // Render target
  87. this._shadowMap = new RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  88. this._shadowMap.wrapU = Texture.CLAMP_ADDRESSMODE;
  89. this._shadowMap.wrapV = Texture.CLAMP_ADDRESSMODE;
  90. this._shadowMap.renderParticles = false;
  91. this._shadowMap.onAfterUnbind = () => {
  92. if (!this.useBlurVarianceShadowMap) {
  93. return;
  94. }
  95. if (!this._shadowMap2) {
  96. this._shadowMap2 = new RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  97. this._shadowMap2.wrapU = Texture.CLAMP_ADDRESSMODE;
  98. this._shadowMap2.wrapV = Texture.CLAMP_ADDRESSMODE;
  99. this._downSamplePostprocess = new PassPostProcess("downScale", 1.0 / this.blurScale, null, Texture.NEAREST_SAMPLINGMODE, this._scene.getEngine());
  100. this._downSamplePostprocess.onApply = effect => {
  101. effect.setTexture("textureSampler", this._shadowMap);
  102. };
  103. this.blurBoxOffset = 1;
  104. }
  105. this._scene.postProcessManager.directRender([this._downSamplePostprocess, this._boxBlurPostprocess], this._shadowMap2.getInternalTexture());
  106. }
  107. // Custom render function
  108. var renderSubMesh = (subMesh: SubMesh): void => {
  109. var mesh = subMesh.getRenderingMesh();
  110. var scene = this._scene;
  111. var engine = scene.getEngine();
  112. // Culling
  113. engine.setState(subMesh.getMaterial().backFaceCulling);
  114. // Managing instances
  115. var batch = mesh._getInstancesRenderList(subMesh._id);
  116. if (batch.mustReturn) {
  117. return;
  118. }
  119. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  120. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  121. engine.enableEffect(this._effect);
  122. mesh._bind(subMesh, this._effect, Material.TriangleFillMode);
  123. var material = subMesh.getMaterial();
  124. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  125. // Alpha test
  126. if (material && material.needAlphaTesting()) {
  127. var alphaTexture = material.getAlphaTestTexture();
  128. this._effect.setTexture("diffuseSampler", alphaTexture);
  129. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  130. }
  131. // Bones
  132. if (mesh.useBones) {
  133. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  134. }
  135. // Draw
  136. mesh._processRendering(subMesh, this._effect, Material.TriangleFillMode, batch, hardwareInstancedRendering,
  137. (isInstance, world) => this._effect.setMatrix("world", world));
  138. } else {
  139. // Need to reset refresh rate of the shadowMap
  140. this._shadowMap.resetRefreshCounter();
  141. }
  142. };
  143. this._shadowMap.customRenderFunction = (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>): void => {
  144. var index: number;
  145. for (index = 0; index < opaqueSubMeshes.length; index++) {
  146. renderSubMesh(opaqueSubMeshes.data[index]);
  147. }
  148. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  149. renderSubMesh(alphaTestSubMeshes.data[index]);
  150. }
  151. if (this._transparencyShadow) {
  152. for (index = 0; index < transparentSubMeshes.length; index++) {
  153. renderSubMesh(transparentSubMeshes.data[index]);
  154. }
  155. }
  156. };
  157. this._shadowMap.onClear = (engine: Engine) => {
  158. if (this.useBlurVarianceShadowMap || this.useVarianceShadowMap) {
  159. engine.clear(new Color4(0, 0, 0, 0), true, true);
  160. } else {
  161. engine.clear(new Color4(1.0, 1.0, 1.0, 1.0), true, true);
  162. }
  163. }
  164. }
  165. public isReady(subMesh: SubMesh, useInstances: boolean): boolean {
  166. var defines = [];
  167. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  168. defines.push("#define VSM");
  169. }
  170. var attribs = [VertexBuffer.PositionKind];
  171. var mesh = subMesh.getMesh();
  172. var material = subMesh.getMaterial();
  173. // Alpha test
  174. if (material && material.needAlphaTesting()) {
  175. defines.push("#define ALPHATEST");
  176. if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  177. attribs.push(VertexBuffer.UVKind);
  178. defines.push("#define UV1");
  179. }
  180. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
  181. attribs.push(VertexBuffer.UV2Kind);
  182. defines.push("#define UV2");
  183. }
  184. }
  185. // Bones
  186. if (mesh.useBones) {
  187. attribs.push(VertexBuffer.MatricesIndicesKind);
  188. attribs.push(VertexBuffer.MatricesWeightsKind);
  189. defines.push("#define BONES");
  190. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  191. }
  192. // Instances
  193. if (useInstances) {
  194. defines.push("#define INSTANCES");
  195. attribs.push("world0");
  196. attribs.push("world1");
  197. attribs.push("world2");
  198. attribs.push("world3");
  199. }
  200. // Get correct effect
  201. var join = defines.join("\n");
  202. if (this._cachedDefines !== join) {
  203. this._cachedDefines = join;
  204. this._effect = this._scene.getEngine().createEffect("shadowMap",
  205. attribs,
  206. ["world", "mBones", "viewProjection", "diffuseMatrix"],
  207. ["diffuseSampler"], join);
  208. }
  209. return this._effect.isReady();
  210. }
  211. public getShadowMap(): RenderTargetTexture {
  212. return this._shadowMap;
  213. }
  214. public getShadowMapForRendering(): RenderTargetTexture {
  215. if (this._shadowMap2) {
  216. return this._shadowMap2;
  217. }
  218. return this._shadowMap;
  219. }
  220. public getLight(): IShadowLight {
  221. return this._light;
  222. }
  223. // Methods
  224. public getTransformMatrix(): Matrix {
  225. var scene = this._scene;
  226. if (this._currentRenderID === scene.getRenderId()) {
  227. return this._transformMatrix;
  228. }
  229. this._currentRenderID = scene.getRenderId();
  230. var lightPosition = this._light.position;
  231. var lightDirection = this._light.direction;
  232. if (this._light.computeTransformedPosition()) {
  233. lightPosition = this._light.transformedPosition;
  234. }
  235. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  236. this._cachedPosition = lightPosition.clone();
  237. this._cachedDirection = lightDirection.clone();
  238. Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), Vector3.Up(), this._viewMatrix);
  239. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  240. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  241. }
  242. return this._transformMatrix;
  243. }
  244. public getDarkness(): number {
  245. return this._darkness;
  246. }
  247. public setDarkness(darkness: number): void {
  248. if (darkness >= 1.0)
  249. this._darkness = 1.0;
  250. else if (darkness <= 0.0)
  251. this._darkness = 0.0;
  252. else
  253. this._darkness = darkness;
  254. }
  255. public getBias(): number {
  256. return this._bias;
  257. }
  258. public setBias(bias: number): void {
  259. this._bias = bias;
  260. }
  261. public setTransparencyShadow(hasShadow: boolean): void {
  262. this._transparencyShadow = hasShadow;
  263. }
  264. private _packHalf(depth: number): Vector2 {
  265. var scale = depth * 255.0;
  266. var fract = scale - Math.floor(scale);
  267. return new Vector2(depth - fract / 255.0, fract);
  268. }
  269. public dispose(): void {
  270. this._shadowMap.dispose();
  271. if (this._shadowMap2) {
  272. this._shadowMap2.dispose();
  273. }
  274. if (this._downSamplePostprocess) {
  275. this._downSamplePostprocess.dispose();
  276. }
  277. if (this._boxBlurPostprocess) {
  278. this._boxBlurPostprocess.dispose();
  279. }
  280. }
  281. }
  282. }