boundingBoxRenderer.ts 12 KB

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