boundingBoxRenderer.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. import { Scene } from "../scene";
  2. import { VertexBuffer } from "../Meshes/buffer";
  3. import { SubMesh } from "../Meshes/subMesh";
  4. import { AbstractMesh } from "../Meshes/abstractMesh";
  5. import { VertexData } from "../Meshes/mesh.vertexData";
  6. import { Matrix } from "../Maths/math.vector";
  7. import { SmartArray } from "../Misc/smartArray";
  8. import { Nullable, FloatArray, IndicesArray } from "../types";
  9. import { ISceneComponent, SceneComponentConstants } from "../sceneComponent";
  10. import { BoundingBox } from "../Culling/boundingBox";
  11. import { Effect } from "../Materials/effect";
  12. import { Material } from "../Materials/material";
  13. import { ShaderMaterial } from "../Materials/shaderMaterial";
  14. import "../Meshes/Builders/boxBuilder";
  15. import "../Shaders/color.fragment";
  16. import "../Shaders/color.vertex";
  17. import { DataBuffer } from '../Meshes/dataBuffer';
  18. import { Color3 } from '../Maths/math.color';
  19. declare module "../scene" {
  20. export interface Scene {
  21. /** @hidden (Backing field) */
  22. _boundingBoxRenderer: BoundingBoxRenderer;
  23. /** @hidden (Backing field) */
  24. _forceShowBoundingBoxes: boolean;
  25. /**
  26. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  27. */
  28. forceShowBoundingBoxes: boolean;
  29. /**
  30. * Gets the bounding box renderer associated with the scene
  31. * @returns a BoundingBoxRenderer
  32. */
  33. getBoundingBoxRenderer(): BoundingBoxRenderer;
  34. }
  35. }
  36. Object.defineProperty(Scene.prototype, "forceShowBoundingBoxes", {
  37. get: function(this: Scene) {
  38. return this._forceShowBoundingBoxes || false;
  39. },
  40. set: function(this: Scene, value: boolean) {
  41. this._forceShowBoundingBoxes = value;
  42. // Lazyly creates a BB renderer if needed.
  43. if (value) {
  44. this.getBoundingBoxRenderer();
  45. }
  46. },
  47. enumerable: true,
  48. configurable: true
  49. });
  50. Scene.prototype.getBoundingBoxRenderer = function(): BoundingBoxRenderer {
  51. if (!this._boundingBoxRenderer) {
  52. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  53. }
  54. return this._boundingBoxRenderer;
  55. };
  56. declare module "../Meshes/abstractMesh" {
  57. export interface AbstractMesh {
  58. /** @hidden (Backing field) */
  59. _showBoundingBox: boolean;
  60. /**
  61. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  62. */
  63. showBoundingBox: boolean;
  64. }
  65. }
  66. Object.defineProperty(AbstractMesh.prototype, "showBoundingBox", {
  67. get: function(this: AbstractMesh) {
  68. return this._showBoundingBox || false;
  69. },
  70. set: function(this: AbstractMesh, value: boolean) {
  71. this._showBoundingBox = value;
  72. // Lazyly creates a BB renderer if needed.
  73. if (value) {
  74. this.getScene().getBoundingBoxRenderer();
  75. }
  76. },
  77. enumerable: true,
  78. configurable: true
  79. });
  80. /**
  81. * Component responsible of rendering the bounding box of the meshes in a scene.
  82. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  83. */
  84. export class BoundingBoxRenderer implements ISceneComponent {
  85. /**
  86. * The component name helpfull to identify the component in the list of scene components.
  87. */
  88. public readonly name = SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  89. /**
  90. * The scene the component belongs to.
  91. */
  92. public scene: Scene;
  93. /**
  94. * Color of the bounding box lines placed in front of an object
  95. */
  96. public frontColor = new Color3(1, 1, 1);
  97. /**
  98. * Color of the bounding box lines placed behind an object
  99. */
  100. public backColor = new Color3(0.1, 0.1, 0.1);
  101. /**
  102. * Defines if the renderer should show the back lines or not
  103. */
  104. public showBackLines = true;
  105. /**
  106. * @hidden
  107. */
  108. public renderList = new SmartArray<BoundingBox>(32);
  109. private _colorShader: ShaderMaterial;
  110. private _vertexBuffers: { [key: string]: Nullable<VertexBuffer> } = {};
  111. private _indexBuffer: DataBuffer;
  112. private _fillIndexBuffer: Nullable<DataBuffer> = null;
  113. private _fillIndexData: Nullable<IndicesArray> = null;
  114. /**
  115. * Instantiates a new bounding box renderer in a scene.
  116. * @param scene the scene the renderer renders in
  117. */
  118. constructor(scene: Scene) {
  119. this.scene = scene;
  120. scene._addComponent(this);
  121. }
  122. /**
  123. * Registers the component in a given scene
  124. */
  125. public register(): void {
  126. this.scene._beforeEvaluateActiveMeshStage.registerStep(SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  127. this.scene._activeMeshStage.registerStep(SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  128. this.scene._evaluateSubMeshStage.registerStep(SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  129. this.scene._afterRenderingGroupDrawStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  130. }
  131. private _evaluateSubMesh(mesh: AbstractMesh, subMesh: SubMesh): void {
  132. if (mesh.showSubMeshesBoundingBox) {
  133. const boundingInfo = subMesh.getBoundingInfo();
  134. if (boundingInfo !== null && boundingInfo !== undefined) {
  135. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  136. this.renderList.push(boundingInfo.boundingBox);
  137. }
  138. }
  139. }
  140. private _activeMesh(sourceMesh: AbstractMesh, mesh: AbstractMesh): void {
  141. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  142. let boundingInfo = sourceMesh.getBoundingInfo();
  143. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  144. this.renderList.push(boundingInfo.boundingBox);
  145. }
  146. }
  147. private _prepareRessources(): void {
  148. if (this._colorShader) {
  149. return;
  150. }
  151. this._colorShader = new ShaderMaterial("colorShader", this.scene, "color",
  152. {
  153. attributes: [VertexBuffer.PositionKind],
  154. uniforms: ["world", "viewProjection", "color"]
  155. });
  156. var engine = this.scene.getEngine();
  157. var boxdata = VertexData.CreateBox({ size: 1.0 });
  158. this._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(engine, <FloatArray>boxdata.positions, VertexBuffer.PositionKind, false);
  159. this._createIndexBuffer();
  160. this._fillIndexData = boxdata.indices;
  161. }
  162. private _createIndexBuffer(): void {
  163. var engine = this.scene.getEngine();
  164. this._indexBuffer = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);
  165. }
  166. /**
  167. * Rebuilds the elements related to this component in case of
  168. * context lost for instance.
  169. */
  170. public rebuild(): void {
  171. let vb = this._vertexBuffers[VertexBuffer.PositionKind];
  172. if (vb) {
  173. vb._rebuild();
  174. }
  175. this._createIndexBuffer();
  176. }
  177. /**
  178. * @hidden
  179. */
  180. public reset(): void {
  181. this.renderList.reset();
  182. }
  183. /**
  184. * Render the bounding boxes of a specific rendering group
  185. * @param renderingGroupId defines the rendering group to render
  186. */
  187. public render(renderingGroupId: number): void {
  188. if (this.renderList.length === 0) {
  189. return;
  190. }
  191. this._prepareRessources();
  192. if (!this._colorShader.isReady()) {
  193. return;
  194. }
  195. var engine = this.scene.getEngine();
  196. engine.setDepthWrite(false);
  197. this._colorShader._preBind();
  198. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  199. var boundingBox = this.renderList.data[boundingBoxIndex];
  200. if (boundingBox._tag !== renderingGroupId) {
  201. continue;
  202. }
  203. var min = boundingBox.minimum;
  204. var max = boundingBox.maximum;
  205. var diff = max.subtract(min);
  206. var median = min.add(diff.scale(0.5));
  207. var worldMatrix = Matrix.Scaling(diff.x, diff.y, diff.z)
  208. .multiply(Matrix.Translation(median.x, median.y, median.z))
  209. .multiply(boundingBox.getWorldMatrix());
  210. // VBOs
  211. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, <Effect>this._colorShader.getEffect());
  212. if (this.showBackLines) {
  213. // Back
  214. engine.setDepthFunctionToGreaterOrEqual();
  215. this.scene.resetCachedMaterial();
  216. this._colorShader.setColor4("color", this.backColor.toColor4());
  217. this._colorShader.bind(worldMatrix);
  218. // Draw order
  219. engine.drawElementsType(Material.LineListDrawMode, 0, 24);
  220. }
  221. // Front
  222. engine.setDepthFunctionToLess();
  223. this.scene.resetCachedMaterial();
  224. this._colorShader.setColor4("color", this.frontColor.toColor4());
  225. this._colorShader.bind(worldMatrix);
  226. // Draw order
  227. engine.drawElementsType(Material.LineListDrawMode, 0, 24);
  228. }
  229. this._colorShader.unbind();
  230. engine.setDepthFunctionToLessOrEqual();
  231. engine.setDepthWrite(true);
  232. }
  233. /**
  234. * In case of occlusion queries, we can render the occlusion bounding box through this method
  235. * @param mesh Define the mesh to render the occlusion bounding box for
  236. */
  237. public renderOcclusionBoundingBox(mesh: AbstractMesh): void {
  238. this._prepareRessources();
  239. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  240. return;
  241. }
  242. var engine = this.scene.getEngine();
  243. if (!this._fillIndexBuffer) {
  244. this._fillIndexBuffer = engine.createIndexBuffer(this._fillIndexData!);
  245. }
  246. engine.setDepthWrite(false);
  247. engine.setColorWrite(false);
  248. this._colorShader._preBind();
  249. var boundingBox = mesh._boundingInfo.boundingBox;
  250. var min = boundingBox.minimum;
  251. var max = boundingBox.maximum;
  252. var diff = max.subtract(min);
  253. var median = min.add(diff.scale(0.5));
  254. var worldMatrix = Matrix.Scaling(diff.x, diff.y, diff.z)
  255. .multiply(Matrix.Translation(median.x, median.y, median.z))
  256. .multiply(boundingBox.getWorldMatrix());
  257. engine.bindBuffers(this._vertexBuffers, this._fillIndexBuffer, <Effect>this._colorShader.getEffect());
  258. engine.setDepthFunctionToLess();
  259. this.scene.resetCachedMaterial();
  260. this._colorShader.bind(worldMatrix);
  261. engine.drawElementsType(Material.TriangleFillMode, 0, 36);
  262. this._colorShader.unbind();
  263. engine.setDepthFunctionToLessOrEqual();
  264. engine.setDepthWrite(true);
  265. engine.setColorWrite(true);
  266. }
  267. /**
  268. * Dispose and release the resources attached to this renderer.
  269. */
  270. public dispose(): void {
  271. if (!this._colorShader) {
  272. return;
  273. }
  274. this.renderList.dispose();
  275. this._colorShader.dispose();
  276. var buffer = this._vertexBuffers[VertexBuffer.PositionKind];
  277. if (buffer) {
  278. buffer.dispose();
  279. this._vertexBuffers[VertexBuffer.PositionKind] = null;
  280. }
  281. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  282. if (this._fillIndexBuffer) {
  283. this.scene.getEngine()._releaseBuffer(this._fillIndexBuffer);
  284. this._fillIndexBuffer = null;
  285. }
  286. }
  287. }