subMesh.ts 19 KB

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