subMesh.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. import { Tools } from "../Misc/tools";
  2. import { Nullable, IndicesArray, DeepImmutable } from "../types";
  3. import { Matrix, Vector3, Plane } from "../Maths/math";
  4. import { Engine } from "../Engines/engine";
  5. import { VertexBuffer } from "./buffer";
  6. import { IntersectionInfo } from "../Collisions/intersectionInfo";
  7. import { ICullable, BoundingInfo } from "../Culling/boundingInfo";
  8. import { Effect } from "../Materials/effect";
  9. import { Constants } from "../Engines/constants";
  10. declare type Collider = import("../Collisions/collider").Collider;
  11. declare type Material = import("../Materials/material").Material;
  12. declare type MaterialDefines = import("../Materials/materialDefines").MaterialDefines;
  13. declare type MultiMaterial = import("../Materials/multiMaterial").MultiMaterial;
  14. declare type AbstractMesh = import("./abstractMesh").AbstractMesh;
  15. declare type Mesh = import("./mesh").Mesh;
  16. declare type Ray = import("../Culling/ray").Ray;
  17. declare type TrianglePickingPredicate = import("../Culling/ray").TrianglePickingPredicate;
  18. /**
  19. * Base class for submeshes
  20. */
  21. export class BaseSubMesh {
  22. /** @hidden */
  23. public _materialDefines: Nullable<MaterialDefines> = null;
  24. /** @hidden */
  25. public _materialEffect: Nullable<Effect> = null;
  26. /**
  27. * Gets associated effect
  28. */
  29. public get effect(): Nullable<Effect> {
  30. return this._materialEffect;
  31. }
  32. /**
  33. * Sets associated effect (effect used to render this submesh)
  34. * @param effect defines the effect to associate with
  35. * @param defines defines the set of defines used to compile this effect
  36. */
  37. public setEffect(effect: Nullable<Effect>, defines: Nullable<MaterialDefines> = null) {
  38. if (this._materialEffect === effect) {
  39. if (!effect) {
  40. this._materialDefines = null;
  41. }
  42. return;
  43. }
  44. this._materialDefines = defines;
  45. this._materialEffect = effect;
  46. }
  47. }
  48. /**
  49. * Defines a subdivision inside a mesh
  50. */
  51. export class SubMesh extends BaseSubMesh implements ICullable {
  52. /** @hidden */
  53. public _linesIndexCount: number = 0;
  54. private _mesh: AbstractMesh;
  55. private _renderingMesh: Mesh;
  56. private _boundingInfo: BoundingInfo;
  57. private _linesIndexBuffer: Nullable<WebGLBuffer> = null;
  58. /** @hidden */
  59. public _lastColliderWorldVertices: Nullable<Vector3[]> = null;
  60. /** @hidden */
  61. public _trianglePlanes: Plane[];
  62. /** @hidden */
  63. public _lastColliderTransformMatrix: Nullable<Matrix> = null;
  64. /** @hidden */
  65. public _renderId = 0;
  66. /** @hidden */
  67. public _alphaIndex: number = 0;
  68. /** @hidden */
  69. public _distanceToCamera: number = 0;
  70. /** @hidden */
  71. public _id: number;
  72. private _currentMaterial: Nullable<Material> = null;
  73. /**
  74. * Add a new submesh to a mesh
  75. * @param materialIndex defines the material index to use
  76. * @param verticesStart defines vertex index start
  77. * @param verticesCount defines vertices count
  78. * @param indexStart defines index start
  79. * @param indexCount defines indices count
  80. * @param mesh defines the parent mesh
  81. * @param renderingMesh defines an optional rendering mesh
  82. * @param createBoundingBox defines if bounding box should be created for this submesh
  83. * @returns the new submesh
  84. */
  85. public static AddToMesh(materialIndex: number, verticesStart: number, verticesCount: number, indexStart: number, indexCount: number, mesh: AbstractMesh, renderingMesh?: Mesh, createBoundingBox: boolean = true): SubMesh {
  86. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  87. }
  88. /**
  89. * Creates a new submesh
  90. * @param materialIndex defines the material index to use
  91. * @param verticesStart defines vertex index start
  92. * @param verticesCount defines vertices count
  93. * @param indexStart defines index start
  94. * @param indexCount defines indices count
  95. * @param mesh defines the parent mesh
  96. * @param renderingMesh defines an optional rendering mesh
  97. * @param createBoundingBox defines if bounding box should be created for this submesh
  98. */
  99. constructor(
  100. /** the material index to use */
  101. public materialIndex: number,
  102. /** vertex index start */
  103. public verticesStart: number,
  104. /** vertices count */
  105. public verticesCount: number,
  106. /** index start */
  107. public indexStart: number,
  108. /** indices count */
  109. public indexCount: number, mesh: AbstractMesh, renderingMesh?: Mesh, createBoundingBox: boolean = true) {
  110. super();
  111. this._mesh = mesh;
  112. this._renderingMesh = renderingMesh || <Mesh>mesh;
  113. mesh.subMeshes.push(this);
  114. this._trianglePlanes = [];
  115. this._id = mesh.subMeshes.length - 1;
  116. if (createBoundingBox) {
  117. this.refreshBoundingInfo();
  118. mesh.computeWorldMatrix(true);
  119. }
  120. }
  121. /**
  122. * Returns true if this submesh covers the entire parent mesh
  123. * @ignorenaming
  124. */
  125. public get IsGlobal(): boolean {
  126. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  127. }
  128. /**
  129. * Returns the submesh BoudingInfo object
  130. * @returns current bounding info (or mesh's one if the submesh is global)
  131. */
  132. public getBoundingInfo(): BoundingInfo {
  133. if (this.IsGlobal) {
  134. return this._mesh.getBoundingInfo();
  135. }
  136. return this._boundingInfo;
  137. }
  138. /**
  139. * Sets the submesh BoundingInfo
  140. * @param boundingInfo defines the new bounding info to use
  141. * @returns the SubMesh
  142. */
  143. public setBoundingInfo(boundingInfo: BoundingInfo): SubMesh {
  144. this._boundingInfo = boundingInfo;
  145. return this;
  146. }
  147. /**
  148. * Returns the mesh of the current submesh
  149. * @return the parent mesh
  150. */
  151. public getMesh(): AbstractMesh {
  152. return this._mesh;
  153. }
  154. /**
  155. * Returns the rendering mesh of the submesh
  156. * @returns the rendering mesh (could be different from parent mesh)
  157. */
  158. public getRenderingMesh(): Mesh {
  159. return this._renderingMesh;
  160. }
  161. /**
  162. * Returns the submesh material
  163. * @returns null or the current material
  164. */
  165. public getMaterial(): Nullable<Material> {
  166. var rootMaterial = this._renderingMesh.material;
  167. if (rootMaterial === null || rootMaterial === undefined) {
  168. return this._mesh.getScene().defaultMaterial;
  169. } else if ((<MultiMaterial>rootMaterial).getSubMaterial) {
  170. var multiMaterial = <MultiMaterial>rootMaterial;
  171. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  172. if (this._currentMaterial !== effectiveMaterial) {
  173. this._currentMaterial = effectiveMaterial;
  174. this._materialDefines = null;
  175. }
  176. return effectiveMaterial;
  177. }
  178. return rootMaterial;
  179. }
  180. // Methods
  181. /**
  182. * Sets a new updated BoundingInfo object to the submesh
  183. * @returns the SubMesh
  184. */
  185. public refreshBoundingInfo(): SubMesh {
  186. this._lastColliderWorldVertices = null;
  187. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  188. return this;
  189. }
  190. var data = this._renderingMesh.getVerticesData(VertexBuffer.PositionKind);
  191. if (!data) {
  192. this._boundingInfo = this._mesh.getBoundingInfo();
  193. return this;
  194. }
  195. var indices = <IndicesArray>this._renderingMesh.getIndices();
  196. var extend: { minimum: Vector3, maximum: Vector3 };
  197. //is this the only submesh?
  198. if (this.indexStart === 0 && this.indexCount === indices.length) {
  199. let boundingInfo = this._renderingMesh.getBoundingInfo();
  200. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  201. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  202. } else {
  203. extend = Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  204. }
  205. if (this._boundingInfo) {
  206. this._boundingInfo.reConstruct(extend.minimum, extend.maximum);
  207. }
  208. else {
  209. this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);
  210. }
  211. return this;
  212. }
  213. /** @hidden */
  214. public _checkCollision(collider: Collider): boolean {
  215. let boundingInfo = this.getBoundingInfo();
  216. return boundingInfo._checkCollision(collider);
  217. }
  218. /**
  219. * Updates the submesh BoundingInfo
  220. * @param world defines the world matrix to use to update the bounding info
  221. * @returns the submesh
  222. */
  223. public updateBoundingInfo(world: DeepImmutable<Matrix>): SubMesh {
  224. let boundingInfo = this.getBoundingInfo();
  225. if (!boundingInfo) {
  226. this.refreshBoundingInfo();
  227. boundingInfo = this.getBoundingInfo();
  228. }
  229. (<BoundingInfo>boundingInfo).update(world);
  230. return this;
  231. }
  232. /**
  233. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  234. * @param frustumPlanes defines the frustum planes
  235. * @returns true if the submesh is intersecting with the frustum
  236. */
  237. public isInFrustum(frustumPlanes: Plane[]): boolean {
  238. let boundingInfo = this.getBoundingInfo();
  239. if (!boundingInfo) {
  240. return false;
  241. }
  242. return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy);
  243. }
  244. /**
  245. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
  246. * @param frustumPlanes defines the frustum planes
  247. * @returns true if the submesh is inside the frustum
  248. */
  249. public isCompletelyInFrustum(frustumPlanes: Plane[]): boolean {
  250. let boundingInfo = this.getBoundingInfo();
  251. if (!boundingInfo) {
  252. return false;
  253. }
  254. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  255. }
  256. /**
  257. * Renders the submesh
  258. * @param enableAlphaMode defines if alpha needs to be used
  259. * @returns the submesh
  260. */
  261. public render(enableAlphaMode: boolean): SubMesh {
  262. this._renderingMesh.render(this, enableAlphaMode);
  263. return this;
  264. }
  265. /**
  266. * @hidden
  267. */
  268. public _getLinesIndexBuffer(indices: IndicesArray, engine: Engine): WebGLBuffer {
  269. if (!this._linesIndexBuffer) {
  270. var linesIndices = [];
  271. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  272. linesIndices.push(indices[index], indices[index + 1],
  273. indices[index + 1], indices[index + 2],
  274. indices[index + 2], indices[index]);
  275. }
  276. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  277. this._linesIndexCount = linesIndices.length;
  278. }
  279. return this._linesIndexBuffer;
  280. }
  281. /**
  282. * Checks if the submesh intersects with a ray
  283. * @param ray defines the ray to test
  284. * @returns true is the passed ray intersects the submesh bounding box
  285. */
  286. public canIntersects(ray: Ray): boolean {
  287. let boundingInfo = this.getBoundingInfo();
  288. if (!boundingInfo) {
  289. return false;
  290. }
  291. return ray.intersectsBox(boundingInfo.boundingBox);
  292. }
  293. /**
  294. * Intersects current submesh with a ray
  295. * @param ray defines the ray to test
  296. * @param positions defines mesh's positions array
  297. * @param indices defines mesh's indices array
  298. * @param fastCheck defines if only bounding info should be used
  299. * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected
  300. * @returns intersection info or null if no intersection
  301. */
  302. public intersects(ray: Ray, positions: Vector3[], indices: IndicesArray,
  303. fastCheck?: boolean, trianglePredicate?: TrianglePickingPredicate): Nullable<IntersectionInfo> {
  304. const material = this.getMaterial();
  305. if (!material) {
  306. return null;
  307. }
  308. switch (material.fillMode) {
  309. case Constants.MATERIAL_PointListDrawMode:
  310. case Constants.MATERIAL_LineListDrawMode:
  311. case Constants.MATERIAL_LineLoopDrawMode:
  312. case Constants.MATERIAL_LineStripDrawMode:
  313. case Constants.MATERIAL_TriangleFanDrawMode:
  314. case Constants.MATERIAL_TriangleStripDrawMode:
  315. return null;
  316. }
  317. // LineMesh first as it's also a Mesh...
  318. if (this._mesh.getClassName() === "InstancedLinesMesh" || this._mesh.getClassName() === "LinesMesh") {
  319. return this._intersectLines(ray, positions, indices, (this._mesh as any).intersectionThreshold, fastCheck);
  320. }
  321. return this._intersectTriangles(ray, positions, indices, fastCheck, trianglePredicate);
  322. }
  323. /** @hidden */
  324. private _intersectLines(ray: Ray, positions: Vector3[], indices: IndicesArray, intersectionThreshold: number, fastCheck?: boolean): Nullable<IntersectionInfo> {
  325. var intersectInfo: Nullable<IntersectionInfo> = null;
  326. // Line test
  327. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  328. var p0 = positions[indices[index]];
  329. var p1 = positions[indices[index + 1]];
  330. var length = ray.intersectionSegment(p0, p1, intersectionThreshold);
  331. if (length < 0) {
  332. continue;
  333. }
  334. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  335. intersectInfo = new IntersectionInfo(null, null, length);
  336. intersectInfo.faceId = index / 2;
  337. if (fastCheck) {
  338. break;
  339. }
  340. }
  341. }
  342. return intersectInfo;
  343. }
  344. /** @hidden */
  345. private _intersectTriangles(ray: Ray, positions: Vector3[], indices: IndicesArray,
  346. fastCheck?: boolean, trianglePredicate?: TrianglePickingPredicate): Nullable<IntersectionInfo> {
  347. var intersectInfo: Nullable<IntersectionInfo> = null;
  348. // Triangles test
  349. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  350. var p0 = positions[indices[index]];
  351. var p1 = positions[indices[index + 1]];
  352. var p2 = positions[indices[index + 2]];
  353. if (trianglePredicate && !trianglePredicate(p0, p1, p2, ray)) {
  354. continue;
  355. }
  356. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  357. if (currentIntersectInfo) {
  358. if (currentIntersectInfo.distance < 0) {
  359. continue;
  360. }
  361. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  362. intersectInfo = currentIntersectInfo;
  363. intersectInfo.faceId = index / 3;
  364. if (fastCheck) {
  365. break;
  366. }
  367. }
  368. }
  369. }
  370. return intersectInfo;
  371. }
  372. /** @hidden */
  373. public _rebuild(): void {
  374. if (this._linesIndexBuffer) {
  375. this._linesIndexBuffer = null;
  376. }
  377. }
  378. // Clone
  379. /**
  380. * Creates a new submesh from the passed mesh
  381. * @param newMesh defines the new hosting mesh
  382. * @param newRenderingMesh defines an optional rendering mesh
  383. * @returns the new submesh
  384. */
  385. public clone(newMesh: AbstractMesh, newRenderingMesh?: Mesh): SubMesh {
  386. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  387. if (!this.IsGlobal) {
  388. let boundingInfo = this.getBoundingInfo();
  389. if (!boundingInfo) {
  390. return result;
  391. }
  392. result._boundingInfo = new BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  393. }
  394. return result;
  395. }
  396. // Dispose
  397. /**
  398. * Release associated resources
  399. */
  400. public dispose(): void {
  401. if (this._linesIndexBuffer) {
  402. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  403. this._linesIndexBuffer = null;
  404. }
  405. // Remove from mesh
  406. var index = this._mesh.subMeshes.indexOf(this);
  407. this._mesh.subMeshes.splice(index, 1);
  408. }
  409. /**
  410. * Gets the class name
  411. * @returns the string "SubMesh".
  412. */
  413. public getClassName(): string {
  414. return "SubMesh";
  415. }
  416. // Statics
  417. /**
  418. * Creates a new submesh from indices data
  419. * @param materialIndex the index of the main mesh material
  420. * @param startIndex the index where to start the copy in the mesh indices array
  421. * @param indexCount the number of indices to copy then from the startIndex
  422. * @param mesh the main mesh to create the submesh from
  423. * @param renderingMesh the optional rendering mesh
  424. * @returns a new submesh
  425. */
  426. public static CreateFromIndices(materialIndex: number, startIndex: number, indexCount: number, mesh: AbstractMesh, renderingMesh?: Mesh): SubMesh {
  427. var minVertexIndex = Number.MAX_VALUE;
  428. var maxVertexIndex = -Number.MAX_VALUE;
  429. const whatWillRender = (renderingMesh || mesh);
  430. var indices = whatWillRender!.getIndices()!;
  431. for (var index = startIndex; index < startIndex + indexCount; index++) {
  432. var vertexIndex = indices[index];
  433. if (vertexIndex < minVertexIndex) {
  434. minVertexIndex = vertexIndex;
  435. }
  436. if (vertexIndex > maxVertexIndex) {
  437. maxVertexIndex = vertexIndex;
  438. }
  439. }
  440. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  441. }
  442. }