depthRenderer.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. import { Nullable } from "../types";
  2. import { Color4 } from "../Maths/math";
  3. import { Mesh } from "../Meshes/mesh";
  4. import { SubMesh } from "../Meshes/subMesh";
  5. import { VertexBuffer } from "../Meshes/buffer";
  6. import { SmartArray } from "../Misc/smartArray";
  7. import { Scene } from "../scene";
  8. import { Texture } from "../Materials/Textures/texture";
  9. import { RenderTargetTexture } from "../Materials/Textures/renderTargetTexture";
  10. import { Effect } from "../Materials/effect";
  11. import { Material } from "../Materials/material";
  12. import { MaterialHelper } from "../Materials/materialHelper";
  13. import { Camera } from "../Cameras/camera";
  14. import { Constants } from "../Engines/constants";
  15. import "../Shaders/depth.fragment";
  16. import "../Shaders/depth.vertex";
  17. import { _DevTools } from '../Misc/devTools';
  18. /**
  19. * This represents a depth renderer in Babylon.
  20. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  21. */
  22. export class DepthRenderer {
  23. private _scene: Scene;
  24. private _depthMap: RenderTargetTexture;
  25. private _effect: Effect;
  26. private readonly _storeNonLinearDepth: boolean;
  27. private readonly _clearColor: Color4;
  28. /** Get if the depth renderer is using packed depth or not */
  29. public readonly isPacked: boolean;
  30. private _cachedDefines: string;
  31. private _camera: Nullable<Camera>;
  32. /**
  33. * Specifiess that the depth renderer will only be used within
  34. * the camera it is created for.
  35. * This can help forcing its rendering during the camera processing.
  36. */
  37. public useOnlyInActiveCamera: boolean = false;
  38. /** @hidden */
  39. public static _SceneComponentInitialization: (scene: Scene) => void = (_) => {
  40. throw _DevTools.WarnImport("DepthRendererSceneComponent");
  41. }
  42. /**
  43. * Instantiates a depth renderer
  44. * @param scene The scene the renderer belongs to
  45. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  46. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  47. * @param storeNonLinearDepth Defines whether the depth is stored linearly like in Babylon Shadows or directly like glFragCoord.z
  48. */
  49. constructor(scene: Scene, type: number = Constants.TEXTURETYPE_FLOAT, camera: Nullable<Camera> = null, storeNonLinearDepth = false) {
  50. this._scene = scene;
  51. this._storeNonLinearDepth = storeNonLinearDepth;
  52. this.isPacked = type === Constants.TEXTURETYPE_UNSIGNED_BYTE;
  53. if (this.isPacked) {
  54. this._clearColor = new Color4(1.0, 1.0, 1.0, 1.0);
  55. }
  56. else {
  57. this._clearColor = new Color4(1.0, 0.0, 0.0, 1.0);
  58. }
  59. DepthRenderer._SceneComponentInitialization(this._scene);
  60. this._camera = camera;
  61. var engine = scene.getEngine();
  62. // Render target
  63. var format = (this.isPacked || engine.webGLVersion === 1) ? Constants.TEXTUREFORMAT_RGBA : Constants.TEXTUREFORMAT_R;
  64. this._depthMap = new RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type,
  65. false, undefined, undefined, undefined, undefined,
  66. format);
  67. this._depthMap.wrapU = Texture.CLAMP_ADDRESSMODE;
  68. this._depthMap.wrapV = Texture.CLAMP_ADDRESSMODE;
  69. this._depthMap.refreshRate = 1;
  70. this._depthMap.renderParticles = false;
  71. this._depthMap.renderList = null;
  72. // Camera to get depth map from to support multiple concurrent cameras
  73. this._depthMap.activeCamera = this._camera;
  74. this._depthMap.ignoreCameraViewport = true;
  75. this._depthMap.useCameraPostProcesses = false;
  76. // set default depth value to 1.0 (far away)
  77. this._depthMap.onClearObservable.add((engine) => {
  78. engine.clear(this._clearColor, true, true, true);
  79. });
  80. // Custom render function
  81. var renderSubMesh = (subMesh: SubMesh): void => {
  82. var mesh = subMesh.getRenderingMesh();
  83. var scene = this._scene;
  84. var engine = scene.getEngine();
  85. let material = subMesh.getMaterial();
  86. if (!material) {
  87. return;
  88. }
  89. // Culling and reverse (right handed system)
  90. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  91. // Managing instances
  92. var batch = mesh._getInstancesRenderList(subMesh._id);
  93. if (batch.mustReturn) {
  94. return;
  95. }
  96. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  97. var camera = this._camera || scene.activeCamera;
  98. if (this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  99. engine.enableEffect(this._effect);
  100. mesh._bind(subMesh, this._effect, Material.TriangleFillMode);
  101. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  102. this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  103. // Alpha test
  104. if (material && material.needAlphaTesting()) {
  105. var alphaTexture = material.getAlphaTestTexture();
  106. if (alphaTexture) {
  107. this._effect.setTexture("diffuseSampler", alphaTexture);
  108. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  109. }
  110. }
  111. // Bones
  112. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  113. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  114. }
  115. // Morph targets
  116. MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  117. // Draw
  118. mesh._processRendering(subMesh, this._effect, Material.TriangleFillMode, batch, hardwareInstancedRendering,
  119. (isInstance, world) => this._effect.setMatrix("world", world));
  120. }
  121. };
  122. this._depthMap.customRenderFunction = (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>, depthOnlySubMeshes: SmartArray<SubMesh>): void => {
  123. var index;
  124. if (depthOnlySubMeshes.length) {
  125. engine.setColorWrite(false);
  126. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  127. renderSubMesh(depthOnlySubMeshes.data[index]);
  128. }
  129. engine.setColorWrite(true);
  130. }
  131. for (index = 0; index < opaqueSubMeshes.length; index++) {
  132. renderSubMesh(opaqueSubMeshes.data[index]);
  133. }
  134. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  135. renderSubMesh(alphaTestSubMeshes.data[index]);
  136. }
  137. };
  138. }
  139. /**
  140. * Creates the depth rendering effect and checks if the effect is ready.
  141. * @param subMesh The submesh to be used to render the depth map of
  142. * @param useInstances If multiple world instances should be used
  143. * @returns if the depth renderer is ready to render the depth map
  144. */
  145. public isReady(subMesh: SubMesh, useInstances: boolean): boolean {
  146. var material: any = subMesh.getMaterial();
  147. if (material.disableDepthWrite) {
  148. return false;
  149. }
  150. var defines = [];
  151. var attribs = [VertexBuffer.PositionKind];
  152. var mesh = subMesh.getMesh();
  153. // Alpha test
  154. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  155. defines.push("#define ALPHATEST");
  156. if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  157. attribs.push(VertexBuffer.UVKind);
  158. defines.push("#define UV1");
  159. }
  160. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
  161. attribs.push(VertexBuffer.UV2Kind);
  162. defines.push("#define UV2");
  163. }
  164. }
  165. // Bones
  166. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  167. attribs.push(VertexBuffer.MatricesIndicesKind);
  168. attribs.push(VertexBuffer.MatricesWeightsKind);
  169. if (mesh.numBoneInfluencers > 4) {
  170. attribs.push(VertexBuffer.MatricesIndicesExtraKind);
  171. attribs.push(VertexBuffer.MatricesWeightsExtraKind);
  172. }
  173. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  174. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  175. } else {
  176. defines.push("#define NUM_BONE_INFLUENCERS 0");
  177. }
  178. // Morph targets
  179. const morphTargetManager = (mesh as Mesh).morphTargetManager;
  180. let numMorphInfluencers = 0;
  181. if (morphTargetManager) {
  182. if (morphTargetManager.numInfluencers > 0) {
  183. numMorphInfluencers = morphTargetManager.numInfluencers;
  184. defines.push("#define MORPHTARGETS");
  185. defines.push("#define NUM_MORPH_INFLUENCERS " + numMorphInfluencers);
  186. MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, numMorphInfluencers);
  187. }
  188. }
  189. // Instances
  190. if (useInstances) {
  191. defines.push("#define INSTANCES");
  192. MaterialHelper.PushAttributesForInstances(attribs);
  193. }
  194. // None linear depth
  195. if (this._storeNonLinearDepth) {
  196. defines.push("#define NONLINEARDEPTH");
  197. }
  198. // Float Mode
  199. if (this.isPacked) {
  200. defines.push("#define PACKED");
  201. }
  202. // Get correct effect
  203. var join = defines.join("\n");
  204. if (this._cachedDefines !== join) {
  205. this._cachedDefines = join;
  206. this._effect = this._scene.getEngine().createEffect("depth",
  207. attribs,
  208. ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues", "morphTargetInfluences"],
  209. ["diffuseSampler"], join,
  210. undefined, undefined, undefined, { maxSimultaneousMorphTargets: numMorphInfluencers });
  211. }
  212. return this._effect.isReady();
  213. }
  214. /**
  215. * Gets the texture which the depth map will be written to.
  216. * @returns The depth map texture
  217. */
  218. public getDepthMap(): RenderTargetTexture {
  219. return this._depthMap;
  220. }
  221. /**
  222. * Disposes of the depth renderer.
  223. */
  224. public dispose(): void {
  225. this._depthMap.dispose();
  226. }
  227. }