outlineRenderer.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. import { VertexBuffer } from "../Buffers/buffer.js";
  2. import { Mesh } from "../Meshes/mesh.js";
  3. import { Scene } from "../scene.js";
  4. import { SceneComponentConstants } from "../sceneComponent.js";
  5. import { DrawWrapper } from "../Materials/drawWrapper.js";
  6. import "../Shaders/outline.fragment.js";
  7. import "../Shaders/outline.vertex.js";
  8. import { addClipPlaneUniforms, bindClipPlane, prepareStringDefinesForClipPlanes } from "../Materials/clipPlaneMaterialHelper.js";
  9. import { BindMorphTargetParameters, PrepareAttributesForMorphTargetsInfluencers, PushAttributesForInstances } from "../Materials/materialHelper.functions.js";
  10. /**
  11. * Gets the outline renderer associated with the scene
  12. * @returns a OutlineRenderer
  13. */
  14. Scene.prototype.getOutlineRenderer = function () {
  15. if (!this._outlineRenderer) {
  16. this._outlineRenderer = new OutlineRenderer(this);
  17. }
  18. return this._outlineRenderer;
  19. };
  20. Object.defineProperty(Mesh.prototype, "renderOutline", {
  21. get: function () {
  22. return this._renderOutline;
  23. },
  24. set: function (value) {
  25. if (value) {
  26. // Lazy Load the component.
  27. this.getScene().getOutlineRenderer();
  28. }
  29. this._renderOutline = value;
  30. },
  31. enumerable: true,
  32. configurable: true,
  33. });
  34. Object.defineProperty(Mesh.prototype, "renderOverlay", {
  35. get: function () {
  36. return this._renderOverlay;
  37. },
  38. set: function (value) {
  39. if (value) {
  40. // Lazy Load the component.
  41. this.getScene().getOutlineRenderer();
  42. }
  43. this._renderOverlay = value;
  44. },
  45. enumerable: true,
  46. configurable: true,
  47. });
  48. /**
  49. * This class is responsible to draw the outline/overlay of meshes.
  50. * It should not be used directly but through the available method on mesh.
  51. */
  52. export class OutlineRenderer {
  53. /**
  54. * Instantiates a new outline renderer. (There could be only one per scene).
  55. * @param scene Defines the scene it belongs to
  56. */
  57. constructor(scene) {
  58. /**
  59. * The name of the component. Each component must have a unique name.
  60. */
  61. this.name = SceneComponentConstants.NAME_OUTLINERENDERER;
  62. /**
  63. * Defines a zOffset default Factor to prevent zFighting between the overlay and the mesh.
  64. */
  65. this.zOffset = 1;
  66. /**
  67. * Defines a zOffset default Unit to prevent zFighting between the overlay and the mesh.
  68. */
  69. this.zOffsetUnits = 4; // 4 to account for projection a bit by default
  70. this.scene = scene;
  71. this._engine = scene.getEngine();
  72. this.scene._addComponent(this);
  73. this._passIdForDrawWrapper = [];
  74. for (let i = 0; i < 4; ++i) {
  75. this._passIdForDrawWrapper[i] = this._engine.createRenderPassId(`Outline Renderer (${i})`);
  76. }
  77. }
  78. /**
  79. * Register the component to one instance of a scene.
  80. */
  81. register() {
  82. this.scene._beforeRenderingMeshStage.registerStep(SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  83. this.scene._afterRenderingMeshStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  84. }
  85. /**
  86. * Rebuilds the elements related to this component in case of
  87. * context lost for instance.
  88. */
  89. rebuild() {
  90. // Nothing to do here.
  91. }
  92. /**
  93. * Disposes the component and the associated resources.
  94. */
  95. dispose() {
  96. for (let i = 0; i < this._passIdForDrawWrapper.length; ++i) {
  97. this._engine.releaseRenderPassId(this._passIdForDrawWrapper[i]);
  98. }
  99. }
  100. /**
  101. * Renders the outline in the canvas.
  102. * @param subMesh Defines the sumesh to render
  103. * @param batch Defines the batch of meshes in case of instances
  104. * @param useOverlay Defines if the rendering is for the overlay or the outline
  105. * @param renderPassId Render pass id to use to render the mesh
  106. */
  107. render(subMesh, batch, useOverlay = false, renderPassId) {
  108. renderPassId = renderPassId ?? this._passIdForDrawWrapper[0];
  109. const scene = this.scene;
  110. const engine = scene.getEngine();
  111. const hardwareInstancedRendering = engine.getCaps().instancedArrays &&
  112. ((batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined) || subMesh.getRenderingMesh().hasThinInstances);
  113. if (!this.isReady(subMesh, hardwareInstancedRendering, renderPassId)) {
  114. return;
  115. }
  116. const ownerMesh = subMesh.getMesh();
  117. const replacementMesh = ownerMesh._internalAbstractMeshDataInfo._actAsRegularMesh ? ownerMesh : null;
  118. const renderingMesh = subMesh.getRenderingMesh();
  119. const effectiveMesh = replacementMesh ? replacementMesh : renderingMesh;
  120. const material = subMesh.getMaterial();
  121. if (!material || !scene.activeCamera) {
  122. return;
  123. }
  124. const drawWrapper = subMesh._getDrawWrapper(renderPassId);
  125. const effect = DrawWrapper.GetEffect(drawWrapper);
  126. engine.enableEffect(drawWrapper);
  127. // Logarithmic depth
  128. if (material.useLogarithmicDepth) {
  129. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  130. }
  131. effect.setFloat("offset", useOverlay ? 0 : renderingMesh.outlineWidth);
  132. effect.setColor4("color", useOverlay ? renderingMesh.overlayColor : renderingMesh.outlineColor, useOverlay ? renderingMesh.overlayAlpha : material.alpha);
  133. effect.setMatrix("viewProjection", scene.getTransformMatrix());
  134. effect.setMatrix("world", effectiveMesh.getWorldMatrix());
  135. // Bones
  136. if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {
  137. effect.setMatrices("mBones", renderingMesh.skeleton.getTransformMatrices(renderingMesh));
  138. }
  139. if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) {
  140. renderingMesh.morphTargetManager._bind(effect);
  141. }
  142. // Morph targets
  143. BindMorphTargetParameters(renderingMesh, effect);
  144. if (!hardwareInstancedRendering) {
  145. renderingMesh._bind(subMesh, effect, material.fillMode);
  146. }
  147. // Alpha test
  148. if (material && material.needAlphaTesting()) {
  149. const alphaTexture = material.getAlphaTestTexture();
  150. if (alphaTexture) {
  151. effect.setTexture("diffuseSampler", alphaTexture);
  152. effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  153. }
  154. }
  155. // Clip plane
  156. bindClipPlane(effect, material, scene);
  157. engine.setZOffset(-this.zOffset);
  158. engine.setZOffsetUnits(-this.zOffsetUnits);
  159. renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, world) => {
  160. effect.setMatrix("world", world);
  161. });
  162. engine.setZOffset(0);
  163. engine.setZOffsetUnits(0);
  164. }
  165. /**
  166. * Returns whether or not the outline renderer is ready for a given submesh.
  167. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  168. * @param subMesh Defines the submesh to check readiness for
  169. * @param useInstances Defines whether wee are trying to render instances or not
  170. * @param renderPassId Render pass id to use to render the mesh
  171. * @returns true if ready otherwise false
  172. */
  173. isReady(subMesh, useInstances, renderPassId) {
  174. renderPassId = renderPassId ?? this._passIdForDrawWrapper[0];
  175. const defines = [];
  176. const attribs = [VertexBuffer.PositionKind, VertexBuffer.NormalKind];
  177. const mesh = subMesh.getMesh();
  178. const material = subMesh.getMaterial();
  179. if (!material) {
  180. return false;
  181. }
  182. const scene = mesh.getScene();
  183. // Alpha test
  184. if (material.needAlphaTesting()) {
  185. defines.push("#define ALPHATEST");
  186. if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  187. attribs.push(VertexBuffer.UVKind);
  188. defines.push("#define UV1");
  189. }
  190. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
  191. attribs.push(VertexBuffer.UV2Kind);
  192. defines.push("#define UV2");
  193. }
  194. }
  195. //Logarithmic depth
  196. if (material.useLogarithmicDepth) {
  197. defines.push("#define LOGARITHMICDEPTH");
  198. }
  199. // Clip planes
  200. prepareStringDefinesForClipPlanes(material, scene, defines);
  201. // Bones
  202. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  203. attribs.push(VertexBuffer.MatricesIndicesKind);
  204. attribs.push(VertexBuffer.MatricesWeightsKind);
  205. if (mesh.numBoneInfluencers > 4) {
  206. attribs.push(VertexBuffer.MatricesIndicesExtraKind);
  207. attribs.push(VertexBuffer.MatricesWeightsExtraKind);
  208. }
  209. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  210. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  211. }
  212. else {
  213. defines.push("#define NUM_BONE_INFLUENCERS 0");
  214. }
  215. // Morph targets
  216. const morphTargetManager = mesh.morphTargetManager;
  217. let numMorphInfluencers = 0;
  218. if (morphTargetManager) {
  219. numMorphInfluencers = morphTargetManager.numMaxInfluencers || morphTargetManager.numInfluencers;
  220. if (numMorphInfluencers > 0) {
  221. defines.push("#define MORPHTARGETS");
  222. defines.push("#define NUM_MORPH_INFLUENCERS " + numMorphInfluencers);
  223. if (morphTargetManager.isUsingTextureForTargets) {
  224. defines.push("#define MORPHTARGETS_TEXTURE");
  225. }
  226. PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, numMorphInfluencers);
  227. }
  228. }
  229. // Instances
  230. if (useInstances) {
  231. defines.push("#define INSTANCES");
  232. PushAttributesForInstances(attribs);
  233. if (subMesh.getRenderingMesh().hasThinInstances) {
  234. defines.push("#define THIN_INSTANCES");
  235. }
  236. }
  237. // Get correct effect
  238. const drawWrapper = subMesh._getDrawWrapper(renderPassId, true);
  239. const cachedDefines = drawWrapper.defines;
  240. const join = defines.join("\n");
  241. if (cachedDefines !== join) {
  242. const uniforms = [
  243. "world",
  244. "mBones",
  245. "viewProjection",
  246. "diffuseMatrix",
  247. "offset",
  248. "color",
  249. "logarithmicDepthConstant",
  250. "morphTargetInfluences",
  251. "morphTargetCount",
  252. "morphTargetTextureInfo",
  253. "morphTargetTextureIndices",
  254. ];
  255. addClipPlaneUniforms(uniforms);
  256. drawWrapper.setEffect(this.scene.getEngine().createEffect("outline", attribs, uniforms, ["diffuseSampler", "morphTargets"], join, undefined, undefined, undefined, {
  257. maxSimultaneousMorphTargets: numMorphInfluencers,
  258. }), join);
  259. }
  260. return drawWrapper.effect.isReady();
  261. }
  262. _beforeRenderingMesh(mesh, subMesh, batch) {
  263. // Outline - step 1
  264. this._savedDepthWrite = this._engine.getDepthWrite();
  265. if (mesh.renderOutline) {
  266. const material = subMesh.getMaterial();
  267. if (material && material.needAlphaBlendingForMesh(mesh)) {
  268. this._engine.cacheStencilState();
  269. // Draw only to stencil buffer for the original mesh
  270. // The resulting stencil buffer will be used so the outline is not visible inside the mesh when the mesh is transparent
  271. this._engine.setDepthWrite(false);
  272. this._engine.setColorWrite(false);
  273. this._engine.setStencilBuffer(true);
  274. this._engine.setStencilOperationPass(7681);
  275. this._engine.setStencilFunction(519);
  276. this._engine.setStencilMask(OutlineRenderer._StencilReference);
  277. this._engine.setStencilFunctionReference(OutlineRenderer._StencilReference);
  278. this._engine.stencilStateComposer.useStencilGlobalOnly = true;
  279. this.render(subMesh, batch, /* This sets offset to 0 */ true, this._passIdForDrawWrapper[1]);
  280. this._engine.setColorWrite(true);
  281. this._engine.setStencilFunction(517);
  282. }
  283. // Draw the outline using the above stencil if needed to avoid drawing within the mesh
  284. this._engine.setDepthWrite(false);
  285. this.render(subMesh, batch, false, this._passIdForDrawWrapper[0]);
  286. this._engine.setDepthWrite(this._savedDepthWrite);
  287. if (material && material.needAlphaBlendingForMesh(mesh)) {
  288. this._engine.stencilStateComposer.useStencilGlobalOnly = false;
  289. this._engine.restoreStencilState();
  290. }
  291. }
  292. }
  293. _afterRenderingMesh(mesh, subMesh, batch) {
  294. // Overlay
  295. if (mesh.renderOverlay) {
  296. const currentMode = this._engine.getAlphaMode();
  297. const alphaBlendState = this._engine.alphaState.alphaBlend;
  298. this._engine.setAlphaMode(2);
  299. this.render(subMesh, batch, true, this._passIdForDrawWrapper[3]);
  300. this._engine.setAlphaMode(currentMode);
  301. this._engine.setDepthWrite(this._savedDepthWrite);
  302. this._engine.alphaState.alphaBlend = alphaBlendState;
  303. }
  304. // Outline - step 2
  305. if (mesh.renderOutline && this._savedDepthWrite) {
  306. this._engine.setDepthWrite(true);
  307. this._engine.setColorWrite(false);
  308. this.render(subMesh, batch, false, this._passIdForDrawWrapper[2]);
  309. this._engine.setColorWrite(true);
  310. }
  311. }
  312. }
  313. /**
  314. * Stencil value used to avoid outline being seen within the mesh when the mesh is transparent
  315. */
  316. OutlineRenderer._StencilReference = 0x04;
  317. //# sourceMappingURL=outlineRenderer.js.map