mesh.ts 168 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946
  1. import { Observer, Observable } from "../Misc/observable";
  2. import { Tools, IAnimatable, AsyncLoop } from "../Misc/tools";
  3. import { DeepCopier } from "../Misc/deepCopier";
  4. import { Tags } from "../Misc/tags";
  5. import { Nullable, FloatArray, IndicesArray } from "../types";
  6. import { Camera } from "../Cameras/camera";
  7. import { Scene } from "../scene";
  8. import { Quaternion, Matrix, Vector3, Vector2, Color3, Color4, Plane, Vector4, Path3D } from "../Maths/math";
  9. import { Engine } from "../Engines/engine";
  10. import { Node } from "../node";
  11. import { VertexBuffer } from "./buffer";
  12. import { VertexData, IGetSetVerticesData } from "./mesh.vertexData";
  13. import { Buffer } from "./buffer";
  14. import { Geometry } from "./geometry";
  15. import { AbstractMesh } from "./abstractMesh";
  16. import { SubMesh } from "./subMesh";
  17. import { BoundingInfo } from "../Culling/boundingInfo";
  18. import { BoundingSphere } from "../Culling/boundingSphere";
  19. import { Effect } from "../Materials/effect";
  20. import { Material } from "../Materials/material";
  21. import { MultiMaterial } from "../Materials/multiMaterial";
  22. import { SceneLoaderFlags } from "../Loading/sceneLoaderFlags";
  23. import { Skeleton } from "../Bones/skeleton";
  24. import { MorphTargetManager } from "../Morph/morphTargetManager";
  25. import { Constants } from "../Engines/constants";
  26. import { SerializationHelper } from "../Misc/decorators";
  27. import { Logger } from "../Misc/logger";
  28. import { _TypeStore } from '../Misc/typeStore';
  29. import { _DevTools } from '../Misc/devTools';
  30. declare type LinesMesh = import("./linesMesh").LinesMesh;
  31. declare type InstancedMesh = import("./instancedMesh").InstancedMesh;
  32. declare type GroundMesh = import("./groundMesh").GroundMesh;
  33. declare type IPhysicsEnabledObject = import("../Physics/physicsImpostor").IPhysicsEnabledObject;
  34. declare type PhysicsImpostor = import("../Physics/physicsImpostor").PhysicsImpostor;
  35. declare var earcut: any;
  36. /**
  37. * Class used to represent a specific level of detail of a mesh
  38. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  39. */
  40. export class MeshLODLevel {
  41. /**
  42. * Creates a new LOD level
  43. * @param distance defines the distance where this level should star being displayed
  44. * @param mesh defines the mesh to use to render this level
  45. */
  46. constructor(
  47. /** Defines the distance where this level should star being displayed */
  48. public distance: number,
  49. /** Defines the mesh to use to render this level */
  50. public mesh: Nullable<Mesh>) {
  51. }
  52. }
  53. /**
  54. * @hidden
  55. **/
  56. export class _CreationDataStorage {
  57. public closePath?: boolean;
  58. public closeArray?: boolean;
  59. public idx: number[];
  60. public dashSize: number;
  61. public gapSize: number;
  62. public path3D: Path3D;
  63. public pathArray: Vector3[][];
  64. public arc: number;
  65. public radius: number;
  66. public cap: number;
  67. public tessellation: number;
  68. }
  69. /**
  70. * @hidden
  71. **/
  72. class _InstanceDataStorage {
  73. public visibleInstances: any = {};
  74. public batchCache = new _InstancesBatch();
  75. public instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  76. public instancesBuffer: Nullable<Buffer>;
  77. public instancesData: Float32Array;
  78. public overridenInstanceCount: number;
  79. public isFrozen: boolean;
  80. public _previousBatch: _InstancesBatch;
  81. public hardwareInstancedRendering: boolean;
  82. }
  83. /**
  84. * @hidden
  85. **/
  86. export class _InstancesBatch {
  87. public mustReturn = false;
  88. public visibleInstances = new Array<Nullable<Array<InstancedMesh>>>();
  89. public renderSelf = new Array<boolean>();
  90. public hardwareInstancedRendering = new Array<boolean>();
  91. }
  92. /**
  93. * Class used to represent renderable models
  94. */
  95. export class Mesh extends AbstractMesh implements IGetSetVerticesData {
  96. // Consts
  97. /**
  98. * Mesh side orientation : usually the external or front surface
  99. */
  100. public static readonly FRONTSIDE = VertexData.FRONTSIDE;
  101. /**
  102. * Mesh side orientation : usually the internal or back surface
  103. */
  104. public static readonly BACKSIDE = VertexData.BACKSIDE;
  105. /**
  106. * Mesh side orientation : both internal and external or front and back surfaces
  107. */
  108. public static readonly DOUBLESIDE = VertexData.DOUBLESIDE;
  109. /**
  110. * Mesh side orientation : by default, `FRONTSIDE`
  111. */
  112. public static readonly DEFAULTSIDE = VertexData.DEFAULTSIDE;
  113. /**
  114. * Mesh cap setting : no cap
  115. */
  116. public static readonly NO_CAP = 0;
  117. /**
  118. * Mesh cap setting : one cap at the beginning of the mesh
  119. */
  120. public static readonly CAP_START = 1;
  121. /**
  122. * Mesh cap setting : one cap at the end of the mesh
  123. */
  124. public static readonly CAP_END = 2;
  125. /**
  126. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  127. */
  128. public static readonly CAP_ALL = 3;
  129. /**
  130. * Gets the default side orientation.
  131. * @param orientation the orientation to value to attempt to get
  132. * @returns the default orientation
  133. * @hidden
  134. */
  135. public static _GetDefaultSideOrientation(orientation?: number): number {
  136. return orientation || Mesh.FRONTSIDE; // works as Mesh.FRONTSIDE is 0
  137. }
  138. // Events
  139. private _onBeforeRenderObservable: Nullable<Observable<Mesh>>;
  140. private _onBeforeBindObservable: Nullable<Observable<Mesh>>;
  141. private _onAfterRenderObservable: Nullable<Observable<Mesh>>;
  142. private _onBeforeDrawObservable: Nullable<Observable<Mesh>>;
  143. /**
  144. * An event triggered before rendering the mesh
  145. */
  146. public get onBeforeRenderObservable(): Observable<Mesh> {
  147. if (!this._onBeforeRenderObservable) {
  148. this._onBeforeRenderObservable = new Observable<Mesh>();
  149. }
  150. return this._onBeforeRenderObservable;
  151. }
  152. /**
  153. * An event triggered before binding the mesh
  154. */
  155. public get onBeforeBindObservable(): Observable<Mesh> {
  156. if (!this._onBeforeBindObservable) {
  157. this._onBeforeBindObservable = new Observable<Mesh>();
  158. }
  159. return this._onBeforeBindObservable;
  160. }
  161. /**
  162. * An event triggered after rendering the mesh
  163. */
  164. public get onAfterRenderObservable(): Observable<Mesh> {
  165. if (!this._onAfterRenderObservable) {
  166. this._onAfterRenderObservable = new Observable<Mesh>();
  167. }
  168. return this._onAfterRenderObservable;
  169. }
  170. /**
  171. * An event triggered before drawing the mesh
  172. */
  173. public get onBeforeDrawObservable(): Observable<Mesh> {
  174. if (!this._onBeforeDrawObservable) {
  175. this._onBeforeDrawObservable = new Observable<Mesh>();
  176. }
  177. return this._onBeforeDrawObservable;
  178. }
  179. private _onBeforeDrawObserver: Nullable<Observer<Mesh>>;
  180. /**
  181. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  182. */
  183. public set onBeforeDraw(callback: () => void) {
  184. if (this._onBeforeDrawObserver) {
  185. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  186. }
  187. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  188. }
  189. // Members
  190. /**
  191. * Gets the delay loading state of the mesh (when delay loading is turned on)
  192. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  193. */
  194. public delayLoadState = Constants.DELAYLOADSTATE_NONE;
  195. /**
  196. * Gets the list of instances created from this mesh
  197. * it is not supposed to be modified manually.
  198. * Note also that the order of the InstancedMesh wihin the array is not significant and might change.
  199. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  200. */
  201. public instances = new Array<InstancedMesh>();
  202. /**
  203. * Gets the file containing delay loading data for this mesh
  204. */
  205. public delayLoadingFile: string;
  206. /** @hidden */
  207. public _binaryInfo: any;
  208. private _LODLevels = new Array<MeshLODLevel>();
  209. /**
  210. * User defined function used to change how LOD level selection is done
  211. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  212. */
  213. public onLODLevelSelection: (distance: number, mesh: Mesh, selectedLevel: Nullable<Mesh>) => void;
  214. // Morph
  215. private _morphTargetManager: Nullable<MorphTargetManager>;
  216. /**
  217. * Gets or sets the morph target manager
  218. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  219. */
  220. public get morphTargetManager(): Nullable<MorphTargetManager> {
  221. return this._morphTargetManager;
  222. }
  223. public set morphTargetManager(value: Nullable<MorphTargetManager>) {
  224. if (this._morphTargetManager === value) {
  225. return;
  226. }
  227. this._morphTargetManager = value;
  228. this._syncGeometryWithMorphTargetManager();
  229. }
  230. // Private
  231. /** @hidden */
  232. public _creationDataStorage: Nullable<_CreationDataStorage>;
  233. /** @hidden */
  234. public _geometry: Nullable<Geometry>;
  235. /** @hidden */
  236. public _delayInfo: Array<string>;
  237. /** @hidden */
  238. public _delayLoadingFunction: (any: any, mesh: Mesh) => void;
  239. /** @hidden */
  240. public _instanceDataStorage = new _InstanceDataStorage();
  241. private _effectiveMaterial: Material;
  242. /** @hidden */
  243. public _shouldGenerateFlatShading: boolean;
  244. private _preActivateId: number;
  245. // Use by builder only to know what orientation were the mesh build in.
  246. /** @hidden */
  247. public _originalBuilderSideOrientation: number = Mesh.DEFAULTSIDE;
  248. /**
  249. * Use this property to change the original side orientation defined at construction time
  250. */
  251. public overrideMaterialSideOrientation: Nullable<number> = null;
  252. private _areNormalsFrozen: boolean = false; // Will be used by ribbons mainly
  253. private _sourcePositions: Float32Array; // Will be used to save original positions when using software skinning
  254. private _sourceNormals: Float32Array; // Will be used to save original normals when using software skinning
  255. // Will be used to save a source mesh reference, If any
  256. private _source: Nullable<Mesh> = null;
  257. // Will be used to for fast cloned mesh lookup
  258. private meshMap: Nullable<{ [id: string]: Mesh | undefined }>;
  259. /**
  260. * Gets the source mesh (the one used to clone this one from)
  261. */
  262. public get source(): Nullable<Mesh> {
  263. return this._source;
  264. }
  265. /**
  266. * Gets or sets a boolean indicating that this mesh does not use index buffer
  267. */
  268. public get isUnIndexed(): boolean {
  269. return this._unIndexed;
  270. }
  271. public set isUnIndexed(value: boolean) {
  272. if (this._unIndexed !== value) {
  273. this._unIndexed = value;
  274. this._markSubMeshesAsAttributesDirty();
  275. }
  276. }
  277. /**
  278. * @constructor
  279. * @param name The value used by scene.getMeshByName() to do a lookup.
  280. * @param scene The scene to add this mesh to.
  281. * @param parent The parent of this mesh, if it has one
  282. * @param source An optional Mesh from which geometry is shared, cloned.
  283. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  284. * When false, achieved by calling a clone(), also passing False.
  285. * This will make creation of children, recursive.
  286. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  287. */
  288. constructor(name: string, scene: Nullable<Scene> = null, parent: Nullable<Node> = null, source: Nullable<Mesh> = null, doNotCloneChildren?: boolean, clonePhysicsImpostor: boolean = true) {
  289. super(name, scene);
  290. scene = this.getScene();
  291. if (source) {
  292. // Geometry
  293. if (source._geometry) {
  294. source._geometry.applyToMesh(this);
  295. }
  296. // Deep copy
  297. DeepCopier.DeepCopy(source, this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  298. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  299. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw",
  300. "onAfterWorldMatrixUpdateObservable", "onCollideObservable", "onCollisionPositionChangeObservable", "onRebuildObservable",
  301. "onDisposeObservable"
  302. ],
  303. ["_poseMatrix"]);
  304. // Source mesh
  305. this._source = source;
  306. if (scene.useClonedMeshhMap) {
  307. if (!source.meshMap) {
  308. source.meshMap = {};
  309. }
  310. source.meshMap[this.uniqueId] = this;
  311. }
  312. // Construction Params
  313. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  314. this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  315. this._creationDataStorage = source._creationDataStorage;
  316. // Animation ranges
  317. if (this._source._ranges) {
  318. const ranges = this._source._ranges;
  319. for (var name in ranges) {
  320. if (!ranges.hasOwnProperty(name)) {
  321. continue;
  322. }
  323. if (!ranges[name]) {
  324. continue;
  325. }
  326. this.createAnimationRange(name, ranges[name]!.from, ranges[name]!.to);
  327. }
  328. }
  329. // Metadata
  330. if (source.metadata && source.metadata.clone) {
  331. this.metadata = source.metadata.clone();
  332. } else {
  333. this.metadata = source.metadata;
  334. }
  335. // Tags
  336. if (Tags && Tags.HasTags(source)) {
  337. Tags.AddTagsTo(this, Tags.GetTags(source, true));
  338. }
  339. // Parent
  340. this.parent = source.parent;
  341. // Pivot
  342. this.setPivotMatrix(source.getPivotMatrix());
  343. this.id = name + "." + source.id;
  344. // Material
  345. this.material = source.material;
  346. var index: number;
  347. if (!doNotCloneChildren) {
  348. // Children
  349. let directDescendants = source.getDescendants(true);
  350. for (let index = 0; index < directDescendants.length; index++) {
  351. var child = directDescendants[index];
  352. if ((<any>child).clone) {
  353. (<any>child).clone(name + "." + child.name, this);
  354. }
  355. }
  356. }
  357. // Physics clone
  358. var physicsEngine = this.getScene().getPhysicsEngine();
  359. if (clonePhysicsImpostor && physicsEngine) {
  360. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  361. if (impostor) {
  362. this.physicsImpostor = impostor.clone(this);
  363. }
  364. }
  365. // Particles
  366. for (index = 0; index < scene.particleSystems.length; index++) {
  367. var system = scene.particleSystems[index];
  368. if (system.emitter === source) {
  369. system.clone(system.name, this);
  370. }
  371. }
  372. this.refreshBoundingInfo();
  373. this.computeWorldMatrix(true);
  374. }
  375. // Parent
  376. if (parent !== null) {
  377. this.parent = parent;
  378. }
  379. this._instanceDataStorage.hardwareInstancedRendering = this.getEngine().getCaps().instancedArrays;
  380. }
  381. // Methods
  382. /**
  383. * Gets the class name
  384. * @returns the string "Mesh".
  385. */
  386. public getClassName(): string {
  387. return "Mesh";
  388. }
  389. /** @hidden */
  390. public readonly _isMesh = true;
  391. /**
  392. * Returns a description of this mesh
  393. * @param fullDetails define if full details about this mesh must be used
  394. * @returns a descriptive string representing this mesh
  395. */
  396. public toString(fullDetails?: boolean): string {
  397. var ret = super.toString(fullDetails);
  398. ret += ", n vertices: " + this.getTotalVertices();
  399. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  400. if (this.animations) {
  401. for (var i = 0; i < this.animations.length; i++) {
  402. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  403. }
  404. }
  405. if (fullDetails) {
  406. if (this._geometry) {
  407. let ib = this.getIndices();
  408. let vb = this.getVerticesData(VertexBuffer.PositionKind);
  409. if (vb && ib) {
  410. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  411. }
  412. } else {
  413. ret += ", flat shading: UNKNOWN";
  414. }
  415. }
  416. return ret;
  417. }
  418. /** @hidden */
  419. public _unBindEffect() {
  420. super._unBindEffect();
  421. for (var instance of this.instances) {
  422. instance._unBindEffect();
  423. }
  424. }
  425. /**
  426. * Gets a boolean indicating if this mesh has LOD
  427. */
  428. public get hasLODLevels(): boolean {
  429. return this._LODLevels.length > 0;
  430. }
  431. /**
  432. * Gets the list of MeshLODLevel associated with the current mesh
  433. * @returns an array of MeshLODLevel
  434. */
  435. public getLODLevels(): MeshLODLevel[] {
  436. return this._LODLevels;
  437. }
  438. private _sortLODLevels(): void {
  439. this._LODLevels.sort((a, b) => {
  440. if (a.distance < b.distance) {
  441. return 1;
  442. }
  443. if (a.distance > b.distance) {
  444. return -1;
  445. }
  446. return 0;
  447. });
  448. }
  449. /**
  450. * Add a mesh as LOD level triggered at the given distance.
  451. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  452. * @param distance The distance from the center of the object to show this level
  453. * @param mesh The mesh to be added as LOD level (can be null)
  454. * @return This mesh (for chaining)
  455. */
  456. public addLODLevel(distance: number, mesh: Nullable<Mesh>): Mesh {
  457. if (mesh && mesh._masterMesh) {
  458. Logger.Warn("You cannot use a mesh as LOD level twice");
  459. return this;
  460. }
  461. var level = new MeshLODLevel(distance, mesh);
  462. this._LODLevels.push(level);
  463. if (mesh) {
  464. mesh._masterMesh = this;
  465. }
  466. this._sortLODLevels();
  467. return this;
  468. }
  469. /**
  470. * Returns the LOD level mesh at the passed distance or null if not found.
  471. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  472. * @param distance The distance from the center of the object to show this level
  473. * @returns a Mesh or `null`
  474. */
  475. public getLODLevelAtDistance(distance: number): Nullable<Mesh> {
  476. for (var index = 0; index < this._LODLevels.length; index++) {
  477. var level = this._LODLevels[index];
  478. if (level.distance === distance) {
  479. return level.mesh;
  480. }
  481. }
  482. return null;
  483. }
  484. /**
  485. * Remove a mesh from the LOD array
  486. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  487. * @param mesh defines the mesh to be removed
  488. * @return This mesh (for chaining)
  489. */
  490. public removeLODLevel(mesh: Mesh): Mesh {
  491. for (var index = 0; index < this._LODLevels.length; index++) {
  492. if (this._LODLevels[index].mesh === mesh) {
  493. this._LODLevels.splice(index, 1);
  494. if (mesh) {
  495. mesh._masterMesh = null;
  496. }
  497. }
  498. }
  499. this._sortLODLevels();
  500. return this;
  501. }
  502. /**
  503. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  504. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  505. * @param camera defines the camera to use to compute distance
  506. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  507. * @return This mesh (for chaining)
  508. */
  509. public getLOD(camera: Camera, boundingSphere?: BoundingSphere): Nullable<AbstractMesh> {
  510. if (!this._LODLevels || this._LODLevels.length === 0) {
  511. return this;
  512. }
  513. let bSphere: BoundingSphere;
  514. if (boundingSphere) {
  515. bSphere = boundingSphere;
  516. } else {
  517. let boundingInfo = this.getBoundingInfo();
  518. bSphere = boundingInfo.boundingSphere;
  519. }
  520. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  521. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  522. if (this.onLODLevelSelection) {
  523. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  524. }
  525. return this;
  526. }
  527. for (var index = 0; index < this._LODLevels.length; index++) {
  528. var level = this._LODLevels[index];
  529. if (level.distance < distanceToCamera) {
  530. if (level.mesh) {
  531. level.mesh._preActivate();
  532. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  533. }
  534. if (this.onLODLevelSelection) {
  535. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  536. }
  537. return level.mesh;
  538. }
  539. }
  540. if (this.onLODLevelSelection) {
  541. this.onLODLevelSelection(distanceToCamera, this, this);
  542. }
  543. return this;
  544. }
  545. /**
  546. * Gets the mesh internal Geometry object
  547. */
  548. public get geometry(): Nullable<Geometry> {
  549. return this._geometry;
  550. }
  551. /**
  552. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  553. * @returns the total number of vertices
  554. */
  555. public getTotalVertices(): number {
  556. if (this._geometry === null || this._geometry === undefined) {
  557. return 0;
  558. }
  559. return this._geometry.getTotalVertices();
  560. }
  561. /**
  562. * Returns the content of an associated vertex buffer
  563. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  564. * - VertexBuffer.PositionKind
  565. * - VertexBuffer.UVKind
  566. * - VertexBuffer.UV2Kind
  567. * - VertexBuffer.UV3Kind
  568. * - VertexBuffer.UV4Kind
  569. * - VertexBuffer.UV5Kind
  570. * - VertexBuffer.UV6Kind
  571. * - VertexBuffer.ColorKind
  572. * - VertexBuffer.MatricesIndicesKind
  573. * - VertexBuffer.MatricesIndicesExtraKind
  574. * - VertexBuffer.MatricesWeightsKind
  575. * - VertexBuffer.MatricesWeightsExtraKind
  576. * @param copyWhenShared defines a boolean indicating that if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one
  577. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  578. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  579. */
  580. public getVerticesData(kind: string, copyWhenShared?: boolean, forceCopy?: boolean): Nullable<FloatArray> {
  581. if (!this._geometry) {
  582. return null;
  583. }
  584. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  585. }
  586. /**
  587. * Returns the mesh VertexBuffer object from the requested `kind`
  588. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  589. * - VertexBuffer.PositionKind
  590. * - VertexBuffer.UVKind
  591. * - VertexBuffer.UV2Kind
  592. * - VertexBuffer.UV3Kind
  593. * - VertexBuffer.UV4Kind
  594. * - VertexBuffer.UV5Kind
  595. * - VertexBuffer.UV6Kind
  596. * - VertexBuffer.ColorKind
  597. * - VertexBuffer.MatricesIndicesKind
  598. * - VertexBuffer.MatricesIndicesExtraKind
  599. * - VertexBuffer.MatricesWeightsKind
  600. * - VertexBuffer.MatricesWeightsExtraKind
  601. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  602. */
  603. public getVertexBuffer(kind: string): Nullable<VertexBuffer> {
  604. if (!this._geometry) {
  605. return null;
  606. }
  607. return this._geometry.getVertexBuffer(kind);
  608. }
  609. /**
  610. * Tests if a specific vertex buffer is associated with this mesh
  611. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  612. * - VertexBuffer.PositionKind
  613. * - VertexBuffer.UVKind
  614. * - VertexBuffer.UV2Kind
  615. * - VertexBuffer.UV3Kind
  616. * - VertexBuffer.UV4Kind
  617. * - VertexBuffer.UV5Kind
  618. * - VertexBuffer.UV6Kind
  619. * - VertexBuffer.ColorKind
  620. * - VertexBuffer.MatricesIndicesKind
  621. * - VertexBuffer.MatricesIndicesExtraKind
  622. * - VertexBuffer.MatricesWeightsKind
  623. * - VertexBuffer.MatricesWeightsExtraKind
  624. * @returns a boolean
  625. */
  626. public isVerticesDataPresent(kind: string): boolean {
  627. if (!this._geometry) {
  628. if (this._delayInfo) {
  629. return this._delayInfo.indexOf(kind) !== -1;
  630. }
  631. return false;
  632. }
  633. return this._geometry.isVerticesDataPresent(kind);
  634. }
  635. /**
  636. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  637. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  638. * - VertexBuffer.PositionKind
  639. * - VertexBuffer.UVKind
  640. * - VertexBuffer.UV2Kind
  641. * - VertexBuffer.UV3Kind
  642. * - VertexBuffer.UV4Kind
  643. * - VertexBuffer.UV5Kind
  644. * - VertexBuffer.UV6Kind
  645. * - VertexBuffer.ColorKind
  646. * - VertexBuffer.MatricesIndicesKind
  647. * - VertexBuffer.MatricesIndicesExtraKind
  648. * - VertexBuffer.MatricesWeightsKind
  649. * - VertexBuffer.MatricesWeightsExtraKind
  650. * @returns a boolean
  651. */
  652. public isVertexBufferUpdatable(kind: string): boolean {
  653. if (!this._geometry) {
  654. if (this._delayInfo) {
  655. return this._delayInfo.indexOf(kind) !== -1;
  656. }
  657. return false;
  658. }
  659. return this._geometry.isVertexBufferUpdatable(kind);
  660. }
  661. /**
  662. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  663. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  664. * - VertexBuffer.PositionKind
  665. * - VertexBuffer.UVKind
  666. * - VertexBuffer.UV2Kind
  667. * - VertexBuffer.UV3Kind
  668. * - VertexBuffer.UV4Kind
  669. * - VertexBuffer.UV5Kind
  670. * - VertexBuffer.UV6Kind
  671. * - VertexBuffer.ColorKind
  672. * - VertexBuffer.MatricesIndicesKind
  673. * - VertexBuffer.MatricesIndicesExtraKind
  674. * - VertexBuffer.MatricesWeightsKind
  675. * - VertexBuffer.MatricesWeightsExtraKind
  676. * @returns an array of strings
  677. */
  678. public getVerticesDataKinds(): string[] {
  679. if (!this._geometry) {
  680. var result = new Array<string>();
  681. if (this._delayInfo) {
  682. this._delayInfo.forEach(function(kind) {
  683. result.push(kind);
  684. });
  685. }
  686. return result;
  687. }
  688. return this._geometry.getVerticesDataKinds();
  689. }
  690. /**
  691. * Returns a positive integer : the total number of indices in this mesh geometry.
  692. * @returns the numner of indices or zero if the mesh has no geometry.
  693. */
  694. public getTotalIndices(): number {
  695. if (!this._geometry) {
  696. return 0;
  697. }
  698. return this._geometry.getTotalIndices();
  699. }
  700. /**
  701. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  702. * @param copyWhenShared If true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  703. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  704. * @returns the indices array or an empty array if the mesh has no geometry
  705. */
  706. public getIndices(copyWhenShared?: boolean, forceCopy?: boolean): Nullable<IndicesArray> {
  707. if (!this._geometry) {
  708. return [];
  709. }
  710. return this._geometry.getIndices(copyWhenShared, forceCopy);
  711. }
  712. public get isBlocked(): boolean {
  713. return this._masterMesh !== null && this._masterMesh !== undefined;
  714. }
  715. /**
  716. * Determine if the current mesh is ready to be rendered
  717. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  718. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  719. * @returns true if all associated assets are ready (material, textures, shaders)
  720. */
  721. public isReady(completeCheck = false, forceInstanceSupport = false): boolean {
  722. if (this.delayLoadState === Constants.DELAYLOADSTATE_LOADING) {
  723. return false;
  724. }
  725. if (!super.isReady(completeCheck)) {
  726. return false;
  727. }
  728. if (!this.subMeshes || this.subMeshes.length === 0) {
  729. return true;
  730. }
  731. if (!completeCheck) {
  732. return true;
  733. }
  734. let engine = this.getEngine();
  735. let scene = this.getScene();
  736. let hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  737. this.computeWorldMatrix();
  738. let mat = this.material || scene.defaultMaterial;
  739. if (mat) {
  740. if (mat._storeEffectOnSubMeshes) {
  741. for (var subMesh of this.subMeshes) {
  742. let effectiveMaterial = subMesh.getMaterial();
  743. if (effectiveMaterial) {
  744. if (effectiveMaterial._storeEffectOnSubMeshes) {
  745. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  746. return false;
  747. }
  748. }
  749. else {
  750. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  751. return false;
  752. }
  753. }
  754. }
  755. }
  756. } else {
  757. if (!mat.isReady(this, hardwareInstancedRendering)) {
  758. return false;
  759. }
  760. }
  761. }
  762. // Shadows
  763. for (var light of this._lightSources) {
  764. let generator = light.getShadowGenerator();
  765. if (generator) {
  766. for (var subMesh of this.subMeshes) {
  767. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  768. return false;
  769. }
  770. }
  771. }
  772. }
  773. // LOD
  774. for (var lod of this._LODLevels) {
  775. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  776. return false;
  777. }
  778. }
  779. return true;
  780. }
  781. /**
  782. * Gets a boolean indicating if the normals aren't to be recomputed on next mesh `positions` array update. This property is pertinent only for updatable parametric shapes.
  783. */
  784. public get areNormalsFrozen(): boolean {
  785. return this._areNormalsFrozen;
  786. }
  787. /**
  788. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It prevents the mesh normals from being recomputed on next `positions` array update.
  789. * @returns the current mesh
  790. */
  791. public freezeNormals(): Mesh {
  792. this._areNormalsFrozen = true;
  793. return this;
  794. }
  795. /**
  796. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It reactivates the mesh normals computation if it was previously frozen
  797. * @returns the current mesh
  798. */
  799. public unfreezeNormals(): Mesh {
  800. this._areNormalsFrozen = false;
  801. return this;
  802. }
  803. /**
  804. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  805. */
  806. public set overridenInstanceCount(count: number) {
  807. this._instanceDataStorage.overridenInstanceCount = count;
  808. }
  809. // Methods
  810. /** @hidden */
  811. public _preActivate(): Mesh {
  812. var sceneRenderId = this.getScene().getRenderId();
  813. if (this._preActivateId === sceneRenderId) {
  814. return this;
  815. }
  816. this._preActivateId = sceneRenderId;
  817. this._instanceDataStorage.visibleInstances = null;
  818. return this;
  819. }
  820. /** @hidden */
  821. public _preActivateForIntermediateRendering(renderId: number): Mesh {
  822. if (this._instanceDataStorage.visibleInstances) {
  823. this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
  824. }
  825. return this;
  826. }
  827. /** @hidden */
  828. public _registerInstanceForRenderId(instance: InstancedMesh, renderId: number): Mesh {
  829. if (!this._instanceDataStorage.visibleInstances) {
  830. this._instanceDataStorage.visibleInstances = {
  831. defaultRenderId: renderId,
  832. selfDefaultRenderId: this._renderId
  833. };
  834. }
  835. if (!this._instanceDataStorage.visibleInstances[renderId]) {
  836. this._instanceDataStorage.visibleInstances[renderId] = new Array<InstancedMesh>();
  837. }
  838. this._instanceDataStorage.visibleInstances[renderId].push(instance);
  839. return this;
  840. }
  841. /**
  842. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  843. * This means the mesh underlying bounding box and sphere are recomputed.
  844. * @param applySkeleton defines whether to apply the skeleton before computing the bounding info
  845. * @returns the current mesh
  846. */
  847. public refreshBoundingInfo(applySkeleton: boolean = false): Mesh {
  848. if (this._boundingInfo && this._boundingInfo.isLocked) {
  849. return this;
  850. }
  851. const bias = this.geometry ? this.geometry.boundingBias : null;
  852. this._refreshBoundingInfo(this._getPositionData(applySkeleton), bias);
  853. return this;
  854. }
  855. /** @hidden */
  856. public _createGlobalSubMesh(force: boolean): Nullable<SubMesh> {
  857. var totalVertices = this.getTotalVertices();
  858. if (!totalVertices || !this.getIndices()) {
  859. return null;
  860. }
  861. // Check if we need to recreate the submeshes
  862. if (this.subMeshes && this.subMeshes.length > 0) {
  863. let ib = this.getIndices();
  864. if (!ib) {
  865. return null;
  866. }
  867. var totalIndices = ib.length;
  868. let needToRecreate = false;
  869. if (force) {
  870. needToRecreate = true;
  871. } else {
  872. for (var submesh of this.subMeshes) {
  873. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  874. needToRecreate = true;
  875. break;
  876. }
  877. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  878. needToRecreate = true;
  879. break;
  880. }
  881. }
  882. }
  883. if (!needToRecreate) {
  884. return this.subMeshes[0];
  885. }
  886. }
  887. this.releaseSubMeshes();
  888. return new SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  889. }
  890. /**
  891. * This function will subdivide the mesh into multiple submeshes
  892. * @param count defines the expected number of submeshes
  893. */
  894. public subdivide(count: number): void {
  895. if (count < 1) {
  896. return;
  897. }
  898. var totalIndices = this.getTotalIndices();
  899. var subdivisionSize = (totalIndices / count) | 0;
  900. var offset = 0;
  901. // Ensure that subdivisionSize is a multiple of 3
  902. while (subdivisionSize % 3 !== 0) {
  903. subdivisionSize++;
  904. }
  905. this.releaseSubMeshes();
  906. for (var index = 0; index < count; index++) {
  907. if (offset >= totalIndices) {
  908. break;
  909. }
  910. SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  911. offset += subdivisionSize;
  912. }
  913. this.synchronizeInstances();
  914. }
  915. /**
  916. * Copy a FloatArray into a specific associated vertex buffer
  917. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  918. * - VertexBuffer.PositionKind
  919. * - VertexBuffer.UVKind
  920. * - VertexBuffer.UV2Kind
  921. * - VertexBuffer.UV3Kind
  922. * - VertexBuffer.UV4Kind
  923. * - VertexBuffer.UV5Kind
  924. * - VertexBuffer.UV6Kind
  925. * - VertexBuffer.ColorKind
  926. * - VertexBuffer.MatricesIndicesKind
  927. * - VertexBuffer.MatricesIndicesExtraKind
  928. * - VertexBuffer.MatricesWeightsKind
  929. * - VertexBuffer.MatricesWeightsExtraKind
  930. * @param data defines the data source
  931. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  932. * @param stride defines the data stride size (can be null)
  933. * @returns the current mesh
  934. */
  935. public setVerticesData(kind: string, data: FloatArray, updatable: boolean = false, stride?: number): Mesh {
  936. if (!this._geometry) {
  937. var vertexData = new VertexData();
  938. vertexData.set(data, kind);
  939. var scene = this.getScene();
  940. new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
  941. }
  942. else {
  943. this._geometry.setVerticesData(kind, data, updatable, stride);
  944. }
  945. return this;
  946. }
  947. /**
  948. * Flags an associated vertex buffer as updatable
  949. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  950. * - VertexBuffer.PositionKind
  951. * - VertexBuffer.UVKind
  952. * - VertexBuffer.UV2Kind
  953. * - VertexBuffer.UV3Kind
  954. * - VertexBuffer.UV4Kind
  955. * - VertexBuffer.UV5Kind
  956. * - VertexBuffer.UV6Kind
  957. * - VertexBuffer.ColorKind
  958. * - VertexBuffer.MatricesIndicesKind
  959. * - VertexBuffer.MatricesIndicesExtraKind
  960. * - VertexBuffer.MatricesWeightsKind
  961. * - VertexBuffer.MatricesWeightsExtraKind
  962. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  963. */
  964. public markVerticesDataAsUpdatable(kind: string, updatable = true) {
  965. let vb = this.getVertexBuffer(kind);
  966. if (!vb || vb.isUpdatable() === updatable) {
  967. return;
  968. }
  969. this.setVerticesData(kind, (<FloatArray>this.getVerticesData(kind)), updatable);
  970. }
  971. /**
  972. * Sets the mesh global Vertex Buffer
  973. * @param buffer defines the buffer to use
  974. * @returns the current mesh
  975. */
  976. public setVerticesBuffer(buffer: VertexBuffer): Mesh {
  977. if (!this._geometry) {
  978. this._geometry = Geometry.CreateGeometryForMesh(this);
  979. }
  980. this._geometry.setVerticesBuffer(buffer);
  981. return this;
  982. }
  983. /**
  984. * Update a specific associated vertex buffer
  985. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  986. * - VertexBuffer.PositionKind
  987. * - VertexBuffer.UVKind
  988. * - VertexBuffer.UV2Kind
  989. * - VertexBuffer.UV3Kind
  990. * - VertexBuffer.UV4Kind
  991. * - VertexBuffer.UV5Kind
  992. * - VertexBuffer.UV6Kind
  993. * - VertexBuffer.ColorKind
  994. * - VertexBuffer.MatricesIndicesKind
  995. * - VertexBuffer.MatricesIndicesExtraKind
  996. * - VertexBuffer.MatricesWeightsKind
  997. * - VertexBuffer.MatricesWeightsExtraKind
  998. * @param data defines the data source
  999. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  1000. * @param makeItUnique defines if the geometry associated with the mesh must be cloned to make the change only for this mesh (and not all meshes associated with the same geometry)
  1001. * @returns the current mesh
  1002. */
  1003. public updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean, makeItUnique?: boolean): Mesh {
  1004. if (!this._geometry) {
  1005. return this;
  1006. }
  1007. if (!makeItUnique) {
  1008. this._geometry.updateVerticesData(kind, data, updateExtends);
  1009. }
  1010. else {
  1011. this.makeGeometryUnique();
  1012. this.updateVerticesData(kind, data, updateExtends, false);
  1013. }
  1014. return this;
  1015. }
  1016. /**
  1017. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  1018. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  1019. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  1020. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  1021. * @returns the current mesh
  1022. */
  1023. public updateMeshPositions(positionFunction: (data: FloatArray) => void, computeNormals: boolean = true): Mesh {
  1024. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  1025. if (!positions) {
  1026. return this;
  1027. }
  1028. positionFunction(positions);
  1029. this.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);
  1030. if (computeNormals) {
  1031. var indices = this.getIndices();
  1032. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  1033. if (!normals) {
  1034. return this;
  1035. }
  1036. VertexData.ComputeNormals(positions, indices, normals);
  1037. this.updateVerticesData(VertexBuffer.NormalKind, normals, false, false);
  1038. }
  1039. return this;
  1040. }
  1041. /**
  1042. * Creates a un-shared specific occurence of the geometry for the mesh.
  1043. * @returns the current mesh
  1044. */
  1045. public makeGeometryUnique(): Mesh {
  1046. if (!this._geometry) {
  1047. return this;
  1048. }
  1049. var oldGeometry = this._geometry;
  1050. var geometry = this._geometry.copy(Geometry.RandomId());
  1051. oldGeometry.releaseForMesh(this, true);
  1052. geometry.applyToMesh(this);
  1053. return this;
  1054. }
  1055. /**
  1056. * Set the index buffer of this mesh
  1057. * @param indices defines the source data
  1058. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  1059. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  1060. * @returns the current mesh
  1061. */
  1062. public setIndices(indices: IndicesArray, totalVertices: Nullable<number> = null, updatable: boolean = false): Mesh {
  1063. if (!this._geometry) {
  1064. var vertexData = new VertexData();
  1065. vertexData.indices = indices;
  1066. var scene = this.getScene();
  1067. new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
  1068. }
  1069. else {
  1070. this._geometry.setIndices(indices, totalVertices, updatable);
  1071. }
  1072. return this;
  1073. }
  1074. /**
  1075. * Update the current index buffer
  1076. * @param indices defines the source data
  1077. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  1078. * @param gpuMemoryOnly defines a boolean indicating that only the GPU memory must be updated leaving the CPU version of the indices unchanged (false by default)
  1079. * @returns the current mesh
  1080. */
  1081. public updateIndices(indices: IndicesArray, offset?: number, gpuMemoryOnly = false): Mesh {
  1082. if (!this._geometry) {
  1083. return this;
  1084. }
  1085. this._geometry.updateIndices(indices, offset, gpuMemoryOnly);
  1086. return this;
  1087. }
  1088. /**
  1089. * Invert the geometry to move from a right handed system to a left handed one.
  1090. * @returns the current mesh
  1091. */
  1092. public toLeftHanded(): Mesh {
  1093. if (!this._geometry) {
  1094. return this;
  1095. }
  1096. this._geometry.toLeftHanded();
  1097. return this;
  1098. }
  1099. /** @hidden */
  1100. public _bind(subMesh: SubMesh, effect: Effect, fillMode: number): Mesh {
  1101. if (!this._geometry) {
  1102. return this;
  1103. }
  1104. var engine = this.getScene().getEngine();
  1105. // Wireframe
  1106. var indexToBind;
  1107. if (this._unIndexed) {
  1108. indexToBind = null;
  1109. } else {
  1110. switch (fillMode) {
  1111. case Material.PointFillMode:
  1112. indexToBind = null;
  1113. break;
  1114. case Material.WireFrameFillMode:
  1115. indexToBind = subMesh._getLinesIndexBuffer(<IndicesArray>this.getIndices(), engine);
  1116. break;
  1117. default:
  1118. case Material.TriangleFillMode:
  1119. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  1120. break;
  1121. }
  1122. }
  1123. // VBOs
  1124. this._geometry._bind(effect, indexToBind);
  1125. return this;
  1126. }
  1127. /** @hidden */
  1128. public _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): Mesh {
  1129. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  1130. return this;
  1131. }
  1132. if (this._onBeforeDrawObservable) {
  1133. this._onBeforeDrawObservable.notifyObservers(this);
  1134. }
  1135. let scene = this.getScene();
  1136. let engine = scene.getEngine();
  1137. if (this._unIndexed || fillMode == Material.PointFillMode) {
  1138. // or triangles as points
  1139. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  1140. } else if (fillMode == Material.WireFrameFillMode) {
  1141. // Triangles as wireframe
  1142. engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
  1143. } else {
  1144. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  1145. }
  1146. return this;
  1147. }
  1148. /**
  1149. * Registers for this mesh a javascript function called just before the rendering process
  1150. * @param func defines the function to call before rendering this mesh
  1151. * @returns the current mesh
  1152. */
  1153. public registerBeforeRender(func: (mesh: AbstractMesh) => void): Mesh {
  1154. this.onBeforeRenderObservable.add(func);
  1155. return this;
  1156. }
  1157. /**
  1158. * Disposes a previously registered javascript function called before the rendering
  1159. * @param func defines the function to remove
  1160. * @returns the current mesh
  1161. */
  1162. public unregisterBeforeRender(func: (mesh: AbstractMesh) => void): Mesh {
  1163. this.onBeforeRenderObservable.removeCallback(func);
  1164. return this;
  1165. }
  1166. /**
  1167. * Registers for this mesh a javascript function called just after the rendering is complete
  1168. * @param func defines the function to call after rendering this mesh
  1169. * @returns the current mesh
  1170. */
  1171. public registerAfterRender(func: (mesh: AbstractMesh) => void): Mesh {
  1172. this.onAfterRenderObservable.add(func);
  1173. return this;
  1174. }
  1175. /**
  1176. * Disposes a previously registered javascript function called after the rendering.
  1177. * @param func defines the function to remove
  1178. * @returns the current mesh
  1179. */
  1180. public unregisterAfterRender(func: (mesh: AbstractMesh) => void): Mesh {
  1181. this.onAfterRenderObservable.removeCallback(func);
  1182. return this;
  1183. }
  1184. /** @hidden */
  1185. public _getInstancesRenderList(subMeshId: number): _InstancesBatch {
  1186. if (this._instanceDataStorage.isFrozen && this._instanceDataStorage._previousBatch) {
  1187. return this._instanceDataStorage._previousBatch;
  1188. }
  1189. var scene = this.getScene();
  1190. let batchCache = this._instanceDataStorage.batchCache;
  1191. batchCache.mustReturn = false;
  1192. batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  1193. batchCache.visibleInstances[subMeshId] = null;
  1194. if (this._instanceDataStorage.visibleInstances) {
  1195. let visibleInstances = this._instanceDataStorage.visibleInstances;
  1196. var currentRenderId = scene.getRenderId();
  1197. var defaultRenderId = (scene._isInIntermediateRendering() ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId);
  1198. batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
  1199. if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  1200. batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
  1201. }
  1202. }
  1203. batchCache.hardwareInstancedRendering[subMeshId] = this._instanceDataStorage.hardwareInstancedRendering && (batchCache.visibleInstances[subMeshId] !== null) && (batchCache.visibleInstances[subMeshId] !== undefined);
  1204. this._instanceDataStorage._previousBatch = batchCache;
  1205. return batchCache;
  1206. }
  1207. /** @hidden */
  1208. public _renderWithInstances(subMesh: SubMesh, fillMode: number, batch: _InstancesBatch, effect: Effect, engine: Engine): Mesh {
  1209. var visibleInstances = batch.visibleInstances[subMesh._id];
  1210. if (!visibleInstances) {
  1211. return this;
  1212. }
  1213. var matricesCount = visibleInstances.length + 1;
  1214. var bufferSize = matricesCount * 16 * 4;
  1215. let instanceStorage = this._instanceDataStorage;
  1216. var currentInstancesBufferSize = instanceStorage.instancesBufferSize;
  1217. var instancesBuffer = instanceStorage.instancesBuffer;
  1218. while (instanceStorage.instancesBufferSize < bufferSize) {
  1219. instanceStorage.instancesBufferSize *= 2;
  1220. }
  1221. if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  1222. instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
  1223. }
  1224. var offset = 0;
  1225. var instancesCount = 0;
  1226. var world = this._effectiveMesh.getWorldMatrix();
  1227. if (batch.renderSelf[subMesh._id]) {
  1228. world.copyToArray(instanceStorage.instancesData, offset);
  1229. offset += 16;
  1230. instancesCount++;
  1231. }
  1232. if (visibleInstances) {
  1233. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  1234. var instance = visibleInstances[instanceIndex];
  1235. instance.getWorldMatrix().copyToArray(instanceStorage.instancesData, offset);
  1236. offset += 16;
  1237. instancesCount++;
  1238. }
  1239. }
  1240. if (!instancesBuffer || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  1241. if (instancesBuffer) {
  1242. instancesBuffer.dispose();
  1243. }
  1244. instancesBuffer = new Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
  1245. instanceStorage.instancesBuffer = instancesBuffer;
  1246. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  1247. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  1248. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  1249. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  1250. } else {
  1251. instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
  1252. }
  1253. this._bind(subMesh, effect, fillMode);
  1254. this._draw(subMesh, fillMode, instancesCount);
  1255. engine.unbindInstanceAttributes();
  1256. return this;
  1257. }
  1258. /** @hidden */
  1259. public _processRendering(subMesh: SubMesh, effect: Effect, fillMode: number, batch: _InstancesBatch, hardwareInstancedRendering: boolean,
  1260. onBeforeDraw: (isInstance: boolean, world: Matrix, effectiveMaterial?: Material) => void, effectiveMaterial?: Material): Mesh {
  1261. var scene = this.getScene();
  1262. var engine = scene.getEngine();
  1263. if (hardwareInstancedRendering) {
  1264. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  1265. } else {
  1266. if (batch.renderSelf[subMesh._id]) {
  1267. // Draw
  1268. if (onBeforeDraw) {
  1269. onBeforeDraw(false, this._effectiveMesh.getWorldMatrix(), effectiveMaterial);
  1270. }
  1271. this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
  1272. }
  1273. let visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  1274. if (visibleInstancesForSubMesh) {
  1275. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  1276. var instance = visibleInstancesForSubMesh[instanceIndex];
  1277. // World
  1278. var world = instance.getWorldMatrix();
  1279. if (onBeforeDraw) {
  1280. onBeforeDraw(true, world, effectiveMaterial);
  1281. }
  1282. // Draw
  1283. this._draw(subMesh, fillMode);
  1284. }
  1285. }
  1286. }
  1287. return this;
  1288. }
  1289. /** @hidden */
  1290. public _freeze() {
  1291. this._instanceDataStorage.isFrozen = true;
  1292. if (!this.subMeshes) {
  1293. return;
  1294. }
  1295. // Prepare batches
  1296. for (var index = 0; index < this.subMeshes.length; index++) {
  1297. this._getInstancesRenderList(index);
  1298. }
  1299. }
  1300. /** @hidden */
  1301. public _unFreeze() {
  1302. this._instanceDataStorage.isFrozen = false;
  1303. }
  1304. /**
  1305. * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager
  1306. * @param subMesh defines the subMesh to render
  1307. * @param enableAlphaMode defines if alpha mode can be changed
  1308. * @returns the current mesh
  1309. */
  1310. public render(subMesh: SubMesh, enableAlphaMode: boolean): Mesh {
  1311. if (this._checkOcclusionQuery()) {
  1312. return this;
  1313. }
  1314. var scene = this.getScene();
  1315. // Managing instances
  1316. var batch = this._getInstancesRenderList(subMesh._id);
  1317. if (batch.mustReturn) {
  1318. return this;
  1319. }
  1320. // Checking geometry state
  1321. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  1322. return this;
  1323. }
  1324. if (this._onBeforeRenderObservable) {
  1325. this._onBeforeRenderObservable.notifyObservers(this);
  1326. }
  1327. var engine = scene.getEngine();
  1328. var hardwareInstancedRendering = batch.hardwareInstancedRendering[subMesh._id];
  1329. // Material
  1330. let material = subMesh.getMaterial();
  1331. if (!material) {
  1332. return this;
  1333. }
  1334. this._effectiveMaterial = material;
  1335. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  1336. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  1337. return this;
  1338. }
  1339. } else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  1340. return this;
  1341. }
  1342. // Alpha mode
  1343. if (enableAlphaMode) {
  1344. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  1345. }
  1346. for (let step of scene._beforeRenderingMeshStage) {
  1347. step.action(this, subMesh, batch);
  1348. }
  1349. var effect: Nullable<Effect>;
  1350. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  1351. effect = subMesh.effect;
  1352. } else {
  1353. effect = this._effectiveMaterial.getEffect();
  1354. }
  1355. if (!effect) {
  1356. return this;
  1357. }
  1358. const effectiveMesh = this._effectiveMesh;
  1359. var sideOrientation = this.overrideMaterialSideOrientation;
  1360. if (sideOrientation == null) {
  1361. sideOrientation = this._effectiveMaterial.sideOrientation;
  1362. if (effectiveMesh._getWorldMatrixDeterminant() < 0) {
  1363. sideOrientation = (sideOrientation === Material.ClockWiseSideOrientation ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation);
  1364. }
  1365. }
  1366. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  1367. if (this._effectiveMaterial.forceDepthWrite) {
  1368. engine.setDepthWrite(true);
  1369. }
  1370. // Bind
  1371. var fillMode = scene.forcePointsCloud ? Material.PointFillMode : (scene.forceWireframe ? Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  1372. if (this._onBeforeBindObservable) {
  1373. this._onBeforeBindObservable.notifyObservers(this);
  1374. }
  1375. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  1376. this._bind(subMesh, effect, fillMode);
  1377. }
  1378. var world = effectiveMesh.getWorldMatrix();
  1379. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  1380. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  1381. } else {
  1382. this._effectiveMaterial.bind(world, this);
  1383. }
  1384. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  1385. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  1386. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  1387. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  1388. }
  1389. // Draw
  1390. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  1391. // Unbind
  1392. this._effectiveMaterial.unbind();
  1393. for (let step of scene._afterRenderingMeshStage) {
  1394. step.action(this, subMesh, batch);
  1395. }
  1396. if (this._onAfterRenderObservable) {
  1397. this._onAfterRenderObservable.notifyObservers(this);
  1398. }
  1399. return this;
  1400. }
  1401. private _onBeforeDraw(isInstance: boolean, world: Matrix, effectiveMaterial?: Material): void {
  1402. if (isInstance && effectiveMaterial) {
  1403. effectiveMaterial.bindOnlyWorldMatrix(world);
  1404. }
  1405. }
  1406. /**
  1407. * Renormalize the mesh and patch it up if there are no weights
  1408. * Similar to normalization by adding the weights compute the reciprocal and multiply all elements, this wil ensure that everything adds to 1.
  1409. * However in the case of zero weights then we set just a single influence to 1.
  1410. * We check in the function for extra's present and if so we use the normalizeSkinWeightsWithExtras rather than the FourWeights version.
  1411. */
  1412. public cleanMatrixWeights(): void {
  1413. if (this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
  1414. if (this.isVerticesDataPresent(VertexBuffer.MatricesWeightsExtraKind)) {
  1415. this.normalizeSkinWeightsAndExtra();
  1416. }
  1417. else {
  1418. this.normalizeSkinFourWeights();
  1419. }
  1420. }
  1421. }
  1422. // faster 4 weight version.
  1423. private normalizeSkinFourWeights(): void {
  1424. let matricesWeights = (<FloatArray>this.getVerticesData(VertexBuffer.MatricesWeightsKind));
  1425. let numWeights = matricesWeights.length;
  1426. for (var a = 0; a < numWeights; a += 4) {
  1427. // accumulate weights
  1428. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  1429. // check for invalid weight and just set it to 1.
  1430. if (t === 0) { matricesWeights[a] = 1; }
  1431. else {
  1432. // renormalize so everything adds to 1 use reciprical
  1433. let recip = 1 / t;
  1434. matricesWeights[a] *= recip;
  1435. matricesWeights[a + 1] *= recip;
  1436. matricesWeights[a + 2] *= recip;
  1437. matricesWeights[a + 3] *= recip;
  1438. }
  1439. }
  1440. this.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeights);
  1441. }
  1442. // handle special case of extra verts. (in theory gltf can handle 12 influences)
  1443. private normalizeSkinWeightsAndExtra(): void {
  1444. let matricesWeightsExtra = (<FloatArray>this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind));
  1445. let matricesWeights = (<FloatArray>this.getVerticesData(VertexBuffer.MatricesWeightsKind));
  1446. let numWeights = matricesWeights.length;
  1447. for (var a = 0; a < numWeights; a += 4) {
  1448. // accumulate weights
  1449. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  1450. t += matricesWeightsExtra[a] + matricesWeightsExtra[a + 1] + matricesWeightsExtra[a + 2] + matricesWeightsExtra[a + 3];
  1451. // check for invalid weight and just set it to 1.
  1452. if (t === 0) { matricesWeights[a] = 1; }
  1453. else {
  1454. // renormalize so everything adds to 1 use reciprical
  1455. let recip = 1 / t;
  1456. matricesWeights[a] *= recip;
  1457. matricesWeights[a + 1] *= recip;
  1458. matricesWeights[a + 2] *= recip;
  1459. matricesWeights[a + 3] *= recip;
  1460. // same goes for extras
  1461. matricesWeightsExtra[a] *= recip;
  1462. matricesWeightsExtra[a + 1] *= recip;
  1463. matricesWeightsExtra[a + 2] *= recip;
  1464. matricesWeightsExtra[a + 3] *= recip;
  1465. }
  1466. }
  1467. this.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeights);
  1468. this.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeightsExtra);
  1469. }
  1470. /**
  1471. * ValidateSkinning is used to determine that a mesh has valid skinning data along with skin metrics, if missing weights,
  1472. * or not normalized it is returned as invalid mesh the string can be used for console logs, or on screen messages to let
  1473. * the user know there was an issue with importing the mesh
  1474. * @returns a validation object with skinned, valid and report string
  1475. */
  1476. public validateSkinning(): { skinned: boolean, valid: boolean, report: string } {
  1477. let matricesWeightsExtra = (<FloatArray>this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind));
  1478. let matricesWeights = (<FloatArray>this.getVerticesData(VertexBuffer.MatricesWeightsKind));
  1479. if (matricesWeights === null || this.skeleton == null) {
  1480. return { skinned: false, valid: true, report: "not skinned" };
  1481. }
  1482. let numWeights = matricesWeights.length;
  1483. let numberNotSorted: number = 0;
  1484. let missingWeights: number = 0;
  1485. let maxUsedWeights: number = 0;
  1486. let numberNotNormalized: number = 0;
  1487. let numInfluences: number = matricesWeightsExtra === null ? 4 : 8;
  1488. var usedWeightCounts = new Array<number>();
  1489. for (var a = 0; a <= numInfluences; a++) {
  1490. usedWeightCounts[a] = 0;
  1491. }
  1492. const toleranceEpsilon: number = 0.001;
  1493. for (var a = 0; a < numWeights; a += 4) {
  1494. let lastWeight: number = matricesWeights[a];
  1495. var t = lastWeight;
  1496. let usedWeights: number = t === 0 ? 0 : 1;
  1497. for (var b = 1; b < numInfluences; b++) {
  1498. var d = b < 4 ? matricesWeights[a + b] : matricesWeightsExtra[a + b - 4];
  1499. if (d > lastWeight) { numberNotSorted++; }
  1500. if (d !== 0) { usedWeights++; }
  1501. t += d;
  1502. lastWeight = d;
  1503. }
  1504. // count the buffer weights usage
  1505. usedWeightCounts[usedWeights]++;
  1506. // max influences
  1507. if (usedWeights > maxUsedWeights) { maxUsedWeights = usedWeights; }
  1508. // check for invalid weight and just set it to 1.
  1509. if (t === 0) {
  1510. missingWeights++;
  1511. }
  1512. else {
  1513. // renormalize so everything adds to 1 use reciprical
  1514. let recip = 1 / t;
  1515. let tolerance = 0;
  1516. for (b = 0; b < numInfluences; b++) {
  1517. if (b < 4) {
  1518. tolerance += Math.abs(matricesWeights[a + b] - (matricesWeights[a + b] * recip));
  1519. }
  1520. else {
  1521. tolerance += Math.abs(matricesWeightsExtra[a + b - 4] - (matricesWeightsExtra[a + b - 4] * recip));
  1522. }
  1523. }
  1524. // arbitary epsilon value for dicdating not normalized
  1525. if (tolerance > toleranceEpsilon) { numberNotNormalized++; }
  1526. }
  1527. }
  1528. // validate bone indices are in range of the skeleton
  1529. let numBones: number = this.skeleton.bones.length;
  1530. let matricesIndices = (<FloatArray>this.getVerticesData(VertexBuffer.MatricesIndicesKind));
  1531. let matricesIndicesExtra = (<FloatArray>this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind));
  1532. let numBadBoneIndices: number = 0;
  1533. for (var a = 0; a < numWeights; a++) {
  1534. for (var b = 0; b < numInfluences; b++) {
  1535. let index = b < 4 ? matricesIndices[b] : matricesIndicesExtra[b - 4];
  1536. if (index >= numBones || index < 0) { numBadBoneIndices++; }
  1537. }
  1538. }
  1539. // log mesh stats
  1540. var output = "Number of Weights = " + numWeights / 4 + "\nMaximum influences = " + maxUsedWeights +
  1541. "\nMissing Weights = " + missingWeights + "\nNot Sorted = " + numberNotSorted +
  1542. "\nNot Normalized = " + numberNotNormalized + "\nWeightCounts = [" + usedWeightCounts + "]" +
  1543. "\nNumber of bones = " + numBones + "\nBad Bone Indices = " + numBadBoneIndices;
  1544. return { skinned: true, valid: missingWeights === 0 && numberNotNormalized === 0 && numBadBoneIndices === 0, report: output };
  1545. }
  1546. /** @hidden */
  1547. public _checkDelayState(): Mesh {
  1548. var scene = this.getScene();
  1549. if (this._geometry) {
  1550. this._geometry.load(scene);
  1551. }
  1552. else if (this.delayLoadState === Constants.DELAYLOADSTATE_NOTLOADED) {
  1553. this.delayLoadState = Constants.DELAYLOADSTATE_LOADING;
  1554. this._queueLoad(scene);
  1555. }
  1556. return this;
  1557. }
  1558. private _queueLoad(scene: Scene): Mesh {
  1559. scene._addPendingData(this);
  1560. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  1561. Tools.LoadFile(this.delayLoadingFile, (data) => {
  1562. if (data instanceof ArrayBuffer) {
  1563. this._delayLoadingFunction(data, this);
  1564. }
  1565. else {
  1566. this._delayLoadingFunction(JSON.parse(data), this);
  1567. }
  1568. this.instances.forEach((instance) => {
  1569. instance._syncSubMeshes();
  1570. });
  1571. this.delayLoadState = Constants.DELAYLOADSTATE_LOADED;
  1572. scene._removePendingData(this);
  1573. }, () => { }, scene.offlineProvider, getBinaryData);
  1574. return this;
  1575. }
  1576. /**
  1577. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  1578. * A mesh is in the frustum if its bounding box intersects the frustum
  1579. * @param frustumPlanes defines the frustum to test
  1580. * @returns true if the mesh is in the frustum planes
  1581. */
  1582. public isInFrustum(frustumPlanes: Plane[]): boolean {
  1583. if (this.delayLoadState === Constants.DELAYLOADSTATE_LOADING) {
  1584. return false;
  1585. }
  1586. if (!super.isInFrustum(frustumPlanes)) {
  1587. return false;
  1588. }
  1589. this._checkDelayState();
  1590. return true;
  1591. }
  1592. /**
  1593. * Sets the mesh material by the material or multiMaterial `id` property
  1594. * @param id is a string identifying the material or the multiMaterial
  1595. * @returns the current mesh
  1596. */
  1597. public setMaterialByID(id: string): Mesh {
  1598. var materials = this.getScene().materials;
  1599. var index: number;
  1600. for (index = materials.length - 1; index > -1; index--) {
  1601. if (materials[index].id === id) {
  1602. this.material = materials[index];
  1603. return this;
  1604. }
  1605. }
  1606. // Multi
  1607. var multiMaterials = this.getScene().multiMaterials;
  1608. for (index = multiMaterials.length - 1; index > -1; index--) {
  1609. if (multiMaterials[index].id === id) {
  1610. this.material = multiMaterials[index];
  1611. return this;
  1612. }
  1613. }
  1614. return this;
  1615. }
  1616. /**
  1617. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  1618. * @returns an array of IAnimatable
  1619. */
  1620. public getAnimatables(): IAnimatable[] {
  1621. var results = new Array<IAnimatable>();
  1622. if (this.material) {
  1623. results.push(this.material);
  1624. }
  1625. if (this.skeleton) {
  1626. results.push(this.skeleton);
  1627. }
  1628. return results;
  1629. }
  1630. /**
  1631. * Modifies the mesh geometry according to the passed transformation matrix.
  1632. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  1633. * The mesh normals are modified using the same transformation.
  1634. * Note that, under the hood, this method sets a new VertexBuffer each call.
  1635. * @param transform defines the transform matrix to use
  1636. * @see http://doc.babylonjs.com/resources/baking_transformations
  1637. * @returns the current mesh
  1638. */
  1639. public bakeTransformIntoVertices(transform: Matrix): Mesh {
  1640. // Position
  1641. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  1642. return this;
  1643. }
  1644. var submeshes = this.subMeshes.splice(0);
  1645. this._resetPointsArrayCache();
  1646. var data = <FloatArray>this.getVerticesData(VertexBuffer.PositionKind);
  1647. var temp = new Array<number>();
  1648. var index: number;
  1649. for (index = 0; index < data.length; index += 3) {
  1650. Vector3.TransformCoordinates(Vector3.FromArray(data, index), transform).toArray(temp, index);
  1651. }
  1652. this.setVerticesData(VertexBuffer.PositionKind, temp, (<VertexBuffer>this.getVertexBuffer(VertexBuffer.PositionKind)).isUpdatable());
  1653. // Normals
  1654. if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  1655. data = <FloatArray>this.getVerticesData(VertexBuffer.NormalKind);
  1656. temp = [];
  1657. for (index = 0; index < data.length; index += 3) {
  1658. Vector3.TransformNormal(Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  1659. }
  1660. this.setVerticesData(VertexBuffer.NormalKind, temp, (<VertexBuffer>this.getVertexBuffer(VertexBuffer.NormalKind)).isUpdatable());
  1661. }
  1662. // flip faces?
  1663. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) { this.flipFaces(); }
  1664. // Restore submeshes
  1665. this.releaseSubMeshes();
  1666. this.subMeshes = submeshes;
  1667. return this;
  1668. }
  1669. /**
  1670. * Modifies the mesh geometry according to its own current World Matrix.
  1671. * The mesh World Matrix is then reset.
  1672. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  1673. * Note that, under the hood, this method sets a new VertexBuffer each call.
  1674. * @see http://doc.babylonjs.com/resources/baking_transformations
  1675. * @returns the current mesh
  1676. */
  1677. public bakeCurrentTransformIntoVertices(): Mesh {
  1678. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  1679. this.scaling.copyFromFloats(1, 1, 1);
  1680. this.position.copyFromFloats(0, 0, 0);
  1681. this.rotation.copyFromFloats(0, 0, 0);
  1682. //only if quaternion is already set
  1683. if (this.rotationQuaternion) {
  1684. this.rotationQuaternion = Quaternion.Identity();
  1685. }
  1686. this._worldMatrix = Matrix.Identity();
  1687. return this;
  1688. }
  1689. // Cache
  1690. /** @hidden */
  1691. public get _positions(): Nullable<Vector3[]> {
  1692. if (this._geometry) {
  1693. return this._geometry._positions;
  1694. }
  1695. return null;
  1696. }
  1697. /** @hidden */
  1698. public _resetPointsArrayCache(): Mesh {
  1699. if (this._geometry) {
  1700. this._geometry._resetPointsArrayCache();
  1701. }
  1702. return this;
  1703. }
  1704. /** @hidden */
  1705. public _generatePointsArray(): boolean {
  1706. if (this._geometry) {
  1707. return this._geometry._generatePointsArray();
  1708. }
  1709. return false;
  1710. }
  1711. /**
  1712. * Returns a new Mesh object generated from the current mesh properties.
  1713. * This method must not get confused with createInstance()
  1714. * @param name is a string, the name given to the new mesh
  1715. * @param newParent can be any Node object (default `null`)
  1716. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  1717. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  1718. * @returns a new mesh
  1719. */
  1720. public clone(name: string = "", newParent?: Node, doNotCloneChildren?: boolean, clonePhysicsImpostor: boolean = true): Mesh {
  1721. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  1722. }
  1723. /**
  1724. * Releases resources associated with this mesh.
  1725. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  1726. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  1727. */
  1728. public dispose(doNotRecurse?: boolean, disposeMaterialAndTextures = false): void {
  1729. this.morphTargetManager = null;
  1730. if (this._geometry) {
  1731. this._geometry.releaseForMesh(this, true);
  1732. }
  1733. if (this._onBeforeDrawObservable) {
  1734. this._onBeforeDrawObservable.clear();
  1735. }
  1736. if (this._onBeforeBindObservable) {
  1737. this._onBeforeBindObservable.clear();
  1738. }
  1739. if (this._onBeforeRenderObservable) {
  1740. this._onBeforeRenderObservable.clear();
  1741. }
  1742. if (this._onAfterRenderObservable) {
  1743. this._onAfterRenderObservable.clear();
  1744. }
  1745. // Sources
  1746. if (this._scene.useClonedMeshhMap) {
  1747. if (this.meshMap) {
  1748. for (const uniqueId in this.meshMap) {
  1749. const mesh = this.meshMap[uniqueId];
  1750. if (mesh) {
  1751. mesh._source = null;
  1752. this.meshMap[uniqueId] = undefined;
  1753. }
  1754. }
  1755. }
  1756. if (this._source && this._source.meshMap) {
  1757. this._source.meshMap[this.uniqueId] = undefined;
  1758. }
  1759. }
  1760. else {
  1761. var meshes = this.getScene().meshes;
  1762. for (const abstractMesh of meshes) {
  1763. let mesh = abstractMesh as Mesh;
  1764. if (mesh._source && mesh._source === this) {
  1765. mesh._source = null;
  1766. }
  1767. }
  1768. }
  1769. this._source = null;
  1770. // Instances
  1771. if (this._instanceDataStorage.instancesBuffer) {
  1772. this._instanceDataStorage.instancesBuffer.dispose();
  1773. this._instanceDataStorage.instancesBuffer = null;
  1774. }
  1775. while (this.instances.length) {
  1776. this.instances[0].dispose();
  1777. }
  1778. super.dispose(doNotRecurse, disposeMaterialAndTextures);
  1779. }
  1780. /**
  1781. * Modifies the mesh geometry according to a displacement map.
  1782. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  1783. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  1784. * @param url is a string, the URL from the image file is to be downloaded.
  1785. * @param minHeight is the lower limit of the displacement.
  1786. * @param maxHeight is the upper limit of the displacement.
  1787. * @param onSuccess is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  1788. * @param uvOffset is an optional vector2 used to offset UV.
  1789. * @param uvScale is an optional vector2 used to scale UV.
  1790. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is useful to apply on a deserialized model for instance.
  1791. * @returns the Mesh.
  1792. */
  1793. public applyDisplacementMap(url: string, minHeight: number, maxHeight: number, onSuccess?: (mesh: Mesh) => void, uvOffset?: Vector2, uvScale?: Vector2, forceUpdate = false): Mesh {
  1794. var scene = this.getScene();
  1795. var onload = (img: HTMLImageElement) => {
  1796. // Getting height map data
  1797. var canvas = document.createElement("canvas");
  1798. var context = <CanvasRenderingContext2D>canvas.getContext("2d");
  1799. var heightMapWidth = img.width;
  1800. var heightMapHeight = img.height;
  1801. canvas.width = heightMapWidth;
  1802. canvas.height = heightMapHeight;
  1803. context.drawImage(img, 0, 0);
  1804. // Create VertexData from map data
  1805. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  1806. var buffer = <Uint8Array>(<any>context.getImageData(0, 0, heightMapWidth, heightMapHeight).data);
  1807. this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  1808. //execute success callback, if set
  1809. if (onSuccess) {
  1810. onSuccess(this);
  1811. }
  1812. };
  1813. Tools.LoadImage(url, onload, () => { }, scene.offlineProvider);
  1814. return this;
  1815. }
  1816. /**
  1817. * Modifies the mesh geometry according to a displacementMap buffer.
  1818. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  1819. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  1820. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  1821. * @param heightMapWidth is the width of the buffer image.
  1822. * @param heightMapHeight is the height of the buffer image.
  1823. * @param minHeight is the lower limit of the displacement.
  1824. * @param maxHeight is the upper limit of the displacement.
  1825. * @param onSuccess is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  1826. * @param uvOffset is an optional vector2 used to offset UV.
  1827. * @param uvScale is an optional vector2 used to scale UV.
  1828. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is useful to apply on a deserialized model for instance.
  1829. * @returns the Mesh.
  1830. */
  1831. public applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number, uvOffset?: Vector2, uvScale?: Vector2, forceUpdate = false): Mesh {
  1832. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)
  1833. || !this.isVerticesDataPresent(VertexBuffer.NormalKind)
  1834. || !this.isVerticesDataPresent(VertexBuffer.UVKind)) {
  1835. Logger.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  1836. return this;
  1837. }
  1838. var positions = <FloatArray>this.getVerticesData(VertexBuffer.PositionKind, true, true);
  1839. var normals = <FloatArray>this.getVerticesData(VertexBuffer.NormalKind);
  1840. var uvs = <number[]>this.getVerticesData(VertexBuffer.UVKind);
  1841. var position = Vector3.Zero();
  1842. var normal = Vector3.Zero();
  1843. var uv = Vector2.Zero();
  1844. uvOffset = uvOffset || Vector2.Zero();
  1845. uvScale = uvScale || new Vector2(1, 1);
  1846. for (var index = 0; index < positions.length; index += 3) {
  1847. Vector3.FromArrayToRef(positions, index, position);
  1848. Vector3.FromArrayToRef(normals, index, normal);
  1849. Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  1850. // Compute height
  1851. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  1852. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  1853. var pos = (u + v * heightMapWidth) * 4;
  1854. var r = buffer[pos] / 255.0;
  1855. var g = buffer[pos + 1] / 255.0;
  1856. var b = buffer[pos + 2] / 255.0;
  1857. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  1858. normal.normalize();
  1859. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  1860. position = position.add(normal);
  1861. position.toArray(positions, index);
  1862. }
  1863. VertexData.ComputeNormals(positions, this.getIndices(), normals);
  1864. if (forceUpdate) {
  1865. this.setVerticesData(VertexBuffer.PositionKind, positions);
  1866. this.setVerticesData(VertexBuffer.NormalKind, normals);
  1867. }
  1868. else {
  1869. this.updateVerticesData(VertexBuffer.PositionKind, positions);
  1870. this.updateVerticesData(VertexBuffer.NormalKind, normals);
  1871. }
  1872. return this;
  1873. }
  1874. /**
  1875. * Modify the mesh to get a flat shading rendering.
  1876. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  1877. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  1878. * @returns current mesh
  1879. */
  1880. public convertToFlatShadedMesh(): Mesh {
  1881. var kinds = this.getVerticesDataKinds();
  1882. var vbs: { [key: string]: VertexBuffer } = {};
  1883. var data: { [key: string]: FloatArray } = {};
  1884. var newdata: { [key: string]: Array<number> } = {};
  1885. var updatableNormals = false;
  1886. var kindIndex: number;
  1887. var kind: string;
  1888. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1889. kind = kinds[kindIndex];
  1890. var vertexBuffer = <VertexBuffer>this.getVertexBuffer(kind);
  1891. if (kind === VertexBuffer.NormalKind) {
  1892. updatableNormals = vertexBuffer.isUpdatable();
  1893. kinds.splice(kindIndex, 1);
  1894. kindIndex--;
  1895. continue;
  1896. }
  1897. vbs[kind] = vertexBuffer;
  1898. data[kind] = <FloatArray>vbs[kind].getData();
  1899. newdata[kind] = [];
  1900. }
  1901. // Save previous submeshes
  1902. var previousSubmeshes = this.subMeshes.slice(0);
  1903. var indices = <IndicesArray>this.getIndices();
  1904. var totalIndices = this.getTotalIndices();
  1905. // Generating unique vertices per face
  1906. var index: number;
  1907. for (index = 0; index < totalIndices; index++) {
  1908. var vertexIndex = indices[index];
  1909. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1910. kind = kinds[kindIndex];
  1911. var stride = vbs[kind].getStrideSize();
  1912. for (var offset = 0; offset < stride; offset++) {
  1913. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  1914. }
  1915. }
  1916. }
  1917. // Updating faces & normal
  1918. var normals = [];
  1919. var positions = newdata[VertexBuffer.PositionKind];
  1920. for (index = 0; index < totalIndices; index += 3) {
  1921. indices[index] = index;
  1922. indices[index + 1] = index + 1;
  1923. indices[index + 2] = index + 2;
  1924. var p1 = Vector3.FromArray(positions, index * 3);
  1925. var p2 = Vector3.FromArray(positions, (index + 1) * 3);
  1926. var p3 = Vector3.FromArray(positions, (index + 2) * 3);
  1927. var p1p2 = p1.subtract(p2);
  1928. var p3p2 = p3.subtract(p2);
  1929. var normal = Vector3.Normalize(Vector3.Cross(p1p2, p3p2));
  1930. // Store same normals for every vertex
  1931. for (var localIndex = 0; localIndex < 3; localIndex++) {
  1932. normals.push(normal.x);
  1933. normals.push(normal.y);
  1934. normals.push(normal.z);
  1935. }
  1936. }
  1937. this.setIndices(indices);
  1938. this.setVerticesData(VertexBuffer.NormalKind, normals, updatableNormals);
  1939. // Updating vertex buffers
  1940. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1941. kind = kinds[kindIndex];
  1942. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  1943. }
  1944. // Updating submeshes
  1945. this.releaseSubMeshes();
  1946. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  1947. var previousOne = previousSubmeshes[submeshIndex];
  1948. SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  1949. }
  1950. this.synchronizeInstances();
  1951. return this;
  1952. }
  1953. /**
  1954. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  1955. * In other words, more vertices, no more indices and a single bigger VBO.
  1956. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  1957. * @returns current mesh
  1958. */
  1959. public convertToUnIndexedMesh(): Mesh {
  1960. var kinds = this.getVerticesDataKinds();
  1961. var vbs: { [key: string]: VertexBuffer } = {};
  1962. var data: { [key: string]: FloatArray } = {};
  1963. var newdata: { [key: string]: Array<number> } = {};
  1964. var kindIndex: number;
  1965. var kind: string;
  1966. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1967. kind = kinds[kindIndex];
  1968. var vertexBuffer = <VertexBuffer>this.getVertexBuffer(kind);
  1969. vbs[kind] = vertexBuffer;
  1970. data[kind] = <FloatArray>vbs[kind].getData();
  1971. newdata[kind] = [];
  1972. }
  1973. // Save previous submeshes
  1974. var previousSubmeshes = this.subMeshes.slice(0);
  1975. var indices = <IndicesArray>this.getIndices();
  1976. var totalIndices = this.getTotalIndices();
  1977. // Generating unique vertices per face
  1978. var index: number;
  1979. for (index = 0; index < totalIndices; index++) {
  1980. var vertexIndex = indices[index];
  1981. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1982. kind = kinds[kindIndex];
  1983. var stride = vbs[kind].getStrideSize();
  1984. for (var offset = 0; offset < stride; offset++) {
  1985. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  1986. }
  1987. }
  1988. }
  1989. // Updating indices
  1990. for (index = 0; index < totalIndices; index += 3) {
  1991. indices[index] = index;
  1992. indices[index + 1] = index + 1;
  1993. indices[index + 2] = index + 2;
  1994. }
  1995. this.setIndices(indices);
  1996. // Updating vertex buffers
  1997. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1998. kind = kinds[kindIndex];
  1999. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  2000. }
  2001. // Updating submeshes
  2002. this.releaseSubMeshes();
  2003. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  2004. var previousOne = previousSubmeshes[submeshIndex];
  2005. SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  2006. }
  2007. this._unIndexed = true;
  2008. this.synchronizeInstances();
  2009. return this;
  2010. }
  2011. /**
  2012. * Inverses facet orientations.
  2013. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  2014. * @param flipNormals will also inverts the normals
  2015. * @returns current mesh
  2016. */
  2017. public flipFaces(flipNormals: boolean = false): Mesh {
  2018. var vertex_data = VertexData.ExtractFromMesh(this);
  2019. var i: number;
  2020. if (flipNormals && this.isVerticesDataPresent(VertexBuffer.NormalKind) && vertex_data.normals) {
  2021. for (i = 0; i < vertex_data.normals.length; i++) {
  2022. vertex_data.normals[i] *= -1;
  2023. }
  2024. }
  2025. if (vertex_data.indices) {
  2026. var temp;
  2027. for (i = 0; i < vertex_data.indices.length; i += 3) {
  2028. // reassign indices
  2029. temp = vertex_data.indices[i + 1];
  2030. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  2031. vertex_data.indices[i + 2] = temp;
  2032. }
  2033. }
  2034. vertex_data.applyToMesh(this);
  2035. return this;
  2036. }
  2037. /**
  2038. * Increase the number of facets and hence vertices in a mesh
  2039. * Vertex normals are interpolated from existing vertex normals
  2040. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  2041. * @param numberPerEdge the number of new vertices to add to each edge of a facet, optional default 1
  2042. */
  2043. public increaseVertices(numberPerEdge: number): void {
  2044. var vertex_data = VertexData.ExtractFromMesh(this);
  2045. var uvs = vertex_data.uvs;
  2046. var currentIndices = vertex_data.indices;
  2047. var positions = vertex_data.positions;
  2048. var normals = vertex_data.normals;
  2049. if (currentIndices === null || positions === null || normals === null || uvs === null) {
  2050. Logger.Warn("VertexData contains null entries");
  2051. }
  2052. else {
  2053. var segments: number = numberPerEdge + 1; //segments per current facet edge, become sides of new facets
  2054. var tempIndices: Array<Array<number>> = new Array();
  2055. for (var i = 0; i < segments + 1; i++) {
  2056. tempIndices[i] = new Array();
  2057. }
  2058. var a: number; //vertex index of one end of a side
  2059. var b: number; //vertex index of other end of the side
  2060. var deltaPosition: Vector3 = new Vector3(0, 0, 0);
  2061. var deltaNormal: Vector3 = new Vector3(0, 0, 0);
  2062. var deltaUV: Vector2 = new Vector2(0, 0);
  2063. var indices: number[] = new Array();
  2064. var vertexIndex: number[] = new Array();
  2065. var side: Array<Array<Array<number>>> = new Array();
  2066. var len: number;
  2067. var positionPtr: number = positions.length;
  2068. var uvPtr: number = uvs.length;
  2069. for (var i = 0; i < currentIndices.length; i += 3) {
  2070. vertexIndex[0] = currentIndices[i];
  2071. vertexIndex[1] = currentIndices[i + 1];
  2072. vertexIndex[2] = currentIndices[i + 2];
  2073. for (var j = 0; j < 3; j++) {
  2074. a = vertexIndex[j];
  2075. b = vertexIndex[(j + 1) % 3];
  2076. if (side[a] === undefined && side[b] === undefined) {
  2077. side[a] = new Array();
  2078. side[b] = new Array();
  2079. }
  2080. else {
  2081. if (side[a] === undefined) {
  2082. side[a] = new Array();
  2083. }
  2084. if (side[b] === undefined) {
  2085. side[b] = new Array();
  2086. }
  2087. }
  2088. if (side[a][b] === undefined && side[b][a] === undefined) {
  2089. side[a][b] = [];
  2090. deltaPosition.x = (positions[3 * b] - positions[3 * a]) / segments;
  2091. deltaPosition.y = (positions[3 * b + 1] - positions[3 * a + 1]) / segments;
  2092. deltaPosition.z = (positions[3 * b + 2] - positions[3 * a + 2]) / segments;
  2093. deltaNormal.x = (normals[3 * b] - normals[3 * a]) / segments;
  2094. deltaNormal.y = (normals[3 * b + 1] - normals[3 * a + 1]) / segments;
  2095. deltaNormal.z = (normals[3 * b + 2] - normals[3 * a + 2]) / segments;
  2096. deltaUV.x = (uvs[2 * b] - uvs[2 * a]) / segments;
  2097. deltaUV.y = (uvs[2 * b + 1] - uvs[2 * a + 1]) / segments;
  2098. side[a][b].push(a);
  2099. for (var k = 1; k < segments; k++) {
  2100. side[a][b].push(positions.length / 3);
  2101. positions[positionPtr] = positions[3 * a] + k * deltaPosition.x;
  2102. normals[positionPtr++] = normals[3 * a] + k * deltaNormal.x;
  2103. positions[positionPtr] = positions[3 * a + 1] + k * deltaPosition.y;
  2104. normals[positionPtr++] = normals[3 * a + 1] + k * deltaNormal.y;
  2105. positions[positionPtr] = positions[3 * a + 2] + k * deltaPosition.z;
  2106. normals[positionPtr++] = normals[3 * a + 2] + k * deltaNormal.z;
  2107. uvs[uvPtr++] = uvs[2 * a] + k * deltaUV.x;
  2108. uvs[uvPtr++] = uvs[2 * a + 1] + k * deltaUV.y;
  2109. }
  2110. side[a][b].push(b);
  2111. side[b][a] = new Array();
  2112. len = side[a][b].length;
  2113. for (var idx = 0; idx < len; idx++) {
  2114. side[b][a][idx] = side[a][b][len - 1 - idx];
  2115. }
  2116. }
  2117. }
  2118. //Calculate positions, normals and uvs of new internal vertices
  2119. tempIndices[0][0] = currentIndices[i];
  2120. tempIndices[1][0] = side[currentIndices[i]][currentIndices[i + 1]][1];
  2121. tempIndices[1][1] = side[currentIndices[i]][currentIndices[i + 2]][1];
  2122. for (var k = 2; k < segments; k++) {
  2123. tempIndices[k][0] = side[currentIndices[i]][currentIndices[i + 1]][k];
  2124. tempIndices[k][k] = side[currentIndices[i]][currentIndices[i + 2]][k];
  2125. deltaPosition.x = (positions[3 * tempIndices[k][k]] - positions[3 * tempIndices[k][0]]) / k;
  2126. deltaPosition.y = (positions[3 * tempIndices[k][k] + 1] - positions[3 * tempIndices[k][0] + 1]) / k;
  2127. deltaPosition.z = (positions[3 * tempIndices[k][k] + 2] - positions[3 * tempIndices[k][0] + 2]) / k;
  2128. deltaNormal.x = (normals[3 * tempIndices[k][k]] - normals[3 * tempIndices[k][0]]) / k;
  2129. deltaNormal.y = (normals[3 * tempIndices[k][k] + 1] - normals[3 * tempIndices[k][0] + 1]) / k;
  2130. deltaNormal.z = (normals[3 * tempIndices[k][k] + 2] - normals[3 * tempIndices[k][0] + 2]) / k;
  2131. deltaUV.x = (uvs[2 * tempIndices[k][k]] - uvs[2 * tempIndices[k][0]]) / k;
  2132. deltaUV.y = (uvs[2 * tempIndices[k][k] + 1] - uvs[2 * tempIndices[k][0] + 1]) / k;
  2133. for (var j = 1; j < k; j++) {
  2134. tempIndices[k][j] = positions.length / 3;
  2135. positions[positionPtr] = positions[3 * tempIndices[k][0]] + j * deltaPosition.x;
  2136. normals[positionPtr++] = normals[3 * tempIndices[k][0]] + j * deltaNormal.x;
  2137. positions[positionPtr] = positions[3 * tempIndices[k][0] + 1] + j * deltaPosition.y;
  2138. normals[positionPtr++] = normals[3 * tempIndices[k][0] + 1] + j * deltaNormal.y;
  2139. positions[positionPtr] = positions[3 * tempIndices[k][0] + 2] + j * deltaPosition.z;
  2140. normals[positionPtr++] = normals[3 * tempIndices[k][0] + 2] + j * deltaNormal.z;
  2141. uvs[uvPtr++] = uvs[2 * tempIndices[k][0]] + j * deltaUV.x;
  2142. uvs[uvPtr++] = uvs[2 * tempIndices[k][0] + 1] + j * deltaUV.y;
  2143. }
  2144. }
  2145. tempIndices[segments] = side[currentIndices[i + 1]][currentIndices[i + 2]];
  2146. // reform indices
  2147. indices.push(tempIndices[0][0], tempIndices[1][0], tempIndices[1][1]);
  2148. for (var k = 1; k < segments; k++) {
  2149. for (var j = 0; j < k; j++) {
  2150. indices.push(tempIndices[k][j], tempIndices[k + 1][j], tempIndices[k + 1][j + 1]);
  2151. indices.push(tempIndices[k][j], tempIndices[k + 1][j + 1], tempIndices[k][j + 1]);
  2152. }
  2153. indices.push(tempIndices[k][j], tempIndices[k + 1][j], tempIndices[k + 1][j + 1]);
  2154. }
  2155. }
  2156. vertex_data.indices = indices;
  2157. vertex_data.applyToMesh(this);
  2158. }
  2159. }
  2160. /**
  2161. * Force adjacent facets to share vertices and remove any facets that have all vertices in a line
  2162. * This will undo any application of covertToFlatShadedMesh
  2163. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  2164. */
  2165. public forceSharedVertices(): void {
  2166. var vertex_data = VertexData.ExtractFromMesh(this);
  2167. var currentUVs = vertex_data.uvs;
  2168. var currentIndices = vertex_data.indices;
  2169. var currentPositions = vertex_data.positions;
  2170. var currentNormals = vertex_data.normals;
  2171. if (currentIndices === null || currentPositions === null || currentNormals === null || currentUVs === null) {
  2172. Logger.Warn("VertexData contains null entries");
  2173. }
  2174. else {
  2175. var positions: Array<number> = new Array();
  2176. var indices: Array<number> = new Array();
  2177. var uvs: Array<number> = new Array();
  2178. var pstring: Array<string> = new Array(); //lists facet vertex positions (a,b,c) as string "a|b|c"
  2179. var indexPtr: number = 0; // pointer to next available index value
  2180. var uniquePositions: Array<string> = new Array(); // unique vertex positions
  2181. var ptr: number; // pointer to element in uniquePositions
  2182. var facet: Array<number>;
  2183. for (var i = 0; i < currentIndices.length; i += 3) {
  2184. facet = [currentIndices[i], currentIndices[i + 1], currentIndices[i + 2]]; //facet vertex indices
  2185. pstring = new Array();
  2186. for (var j = 0; j < 3; j++) {
  2187. pstring[j] = "";
  2188. for (var k = 0; k < 3; k++) {
  2189. //small values make 0
  2190. if (Math.abs(currentPositions[3 * facet[j] + k]) < 0.00000001) {
  2191. currentPositions[3 * facet[j] + k] = 0;
  2192. }
  2193. pstring[j] += currentPositions[3 * facet[j] + k] + "|";
  2194. }
  2195. pstring[j] = pstring[j].slice(0, -1);
  2196. }
  2197. //check facet vertices to see that none are repeated
  2198. // do not process any facet that has a repeated vertex, ie is a line
  2199. if (!(pstring[0] == pstring[1] || pstring[0] == pstring[2] || pstring[1] == pstring[2])) {
  2200. //for each facet position check if already listed in uniquePositions
  2201. // if not listed add to uniquePositions and set index pointer
  2202. // if listed use its index in uniquePositions and new index pointer
  2203. for (var j = 0; j < 3; j++) {
  2204. ptr = uniquePositions.indexOf(pstring[j]);
  2205. if (ptr < 0) {
  2206. uniquePositions.push(pstring[j]);
  2207. ptr = indexPtr++;
  2208. //not listed so add individual x, y, z coordinates to positions
  2209. for (var k = 0; k < 3; k++) {
  2210. positions.push(currentPositions[3 * facet[j] + k]);
  2211. }
  2212. for (var k = 0; k < 2; k++) {
  2213. uvs.push(currentUVs[2 * facet[j] + k]);
  2214. }
  2215. }
  2216. // add new index pointer to indices array
  2217. indices.push(ptr);
  2218. }
  2219. }
  2220. }
  2221. var normals: Array<number> = new Array();
  2222. VertexData.ComputeNormals(positions, indices, normals);
  2223. //create new vertex data object and update
  2224. vertex_data.positions = positions;
  2225. vertex_data.indices = indices;
  2226. vertex_data.normals = normals;
  2227. vertex_data.uvs = uvs;
  2228. vertex_data.applyToMesh(this);
  2229. }
  2230. }
  2231. // Instances
  2232. /** @hidden */
  2233. public static _instancedMeshFactory(name: string, mesh: Mesh): InstancedMesh {
  2234. throw _DevTools.WarnImport("InstancedMesh");
  2235. }
  2236. /** @hidden */
  2237. public static _PhysicsImpostorParser(scene: Scene, physicObject: IPhysicsEnabledObject, jsonObject: any): PhysicsImpostor {
  2238. throw _DevTools.WarnImport("PhysicsImpostor");
  2239. }
  2240. /**
  2241. * Creates a new InstancedMesh object from the mesh model.
  2242. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  2243. * @param name defines the name of the new instance
  2244. * @returns a new InstancedMesh
  2245. */
  2246. public createInstance(name: string): InstancedMesh {
  2247. return Mesh._instancedMeshFactory(name, this);
  2248. }
  2249. /**
  2250. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  2251. * After this call, all the mesh instances have the same submeshes than the current mesh.
  2252. * @returns the current mesh
  2253. */
  2254. public synchronizeInstances(): Mesh {
  2255. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  2256. var instance = this.instances[instanceIndex];
  2257. instance._syncSubMeshes();
  2258. }
  2259. return this;
  2260. }
  2261. /**
  2262. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  2263. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  2264. * This should be used together with the simplification to avoid disappearing triangles.
  2265. * @param successCallback an optional success callback to be called after the optimization finished.
  2266. * @returns the current mesh
  2267. */
  2268. public optimizeIndices(successCallback?: (mesh?: Mesh) => void): Mesh {
  2269. var indices = <IndicesArray>this.getIndices();
  2270. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  2271. if (!positions || !indices) {
  2272. return this;
  2273. }
  2274. var vectorPositions = new Array<Vector3>();
  2275. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  2276. vectorPositions.push(Vector3.FromArray(positions, pos));
  2277. }
  2278. var dupes = new Array<number>();
  2279. AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, (iteration) => {
  2280. var realPos = vectorPositions.length - 1 - iteration;
  2281. var testedPosition = vectorPositions[realPos];
  2282. for (var j = 0; j < realPos; ++j) {
  2283. var againstPosition = vectorPositions[j];
  2284. if (testedPosition.equals(againstPosition)) {
  2285. dupes[realPos] = j;
  2286. break;
  2287. }
  2288. }
  2289. }, () => {
  2290. for (var i = 0; i < indices.length; ++i) {
  2291. indices[i] = dupes[indices[i]] || indices[i];
  2292. }
  2293. //indices are now reordered
  2294. var originalSubMeshes = this.subMeshes.slice(0);
  2295. this.setIndices(indices);
  2296. this.subMeshes = originalSubMeshes;
  2297. if (successCallback) {
  2298. successCallback(this);
  2299. }
  2300. });
  2301. return this;
  2302. }
  2303. /**
  2304. * Serialize current mesh
  2305. * @param serializationObject defines the object which will receive the serialization data
  2306. */
  2307. public serialize(serializationObject: any): void {
  2308. serializationObject.name = this.name;
  2309. serializationObject.id = this.id;
  2310. serializationObject.type = this.getClassName();
  2311. if (Tags && Tags.HasTags(this)) {
  2312. serializationObject.tags = Tags.GetTags(this);
  2313. }
  2314. serializationObject.position = this.position.asArray();
  2315. if (this.rotationQuaternion) {
  2316. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  2317. } else if (this.rotation) {
  2318. serializationObject.rotation = this.rotation.asArray();
  2319. }
  2320. serializationObject.scaling = this.scaling.asArray();
  2321. if (this._postMultiplyPivotMatrix) {
  2322. serializationObject.pivotMatrix = this.getPivotMatrix().asArray();
  2323. } else {
  2324. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  2325. }
  2326. serializationObject.isEnabled = this.isEnabled(false);
  2327. serializationObject.isVisible = this.isVisible;
  2328. serializationObject.infiniteDistance = this.infiniteDistance;
  2329. serializationObject.pickable = this.isPickable;
  2330. serializationObject.receiveShadows = this.receiveShadows;
  2331. serializationObject.billboardMode = this.billboardMode;
  2332. serializationObject.visibility = this.visibility;
  2333. serializationObject.checkCollisions = this.checkCollisions;
  2334. serializationObject.isBlocker = this.isBlocker;
  2335. // Parent
  2336. if (this.parent) {
  2337. serializationObject.parentId = this.parent.id;
  2338. }
  2339. // Geometry
  2340. serializationObject.isUnIndexed = this.isUnIndexed;
  2341. var geometry = this._geometry;
  2342. if (geometry) {
  2343. var geometryId = geometry.id;
  2344. serializationObject.geometryId = geometryId;
  2345. // SubMeshes
  2346. serializationObject.subMeshes = [];
  2347. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  2348. var subMesh = this.subMeshes[subIndex];
  2349. serializationObject.subMeshes.push({
  2350. materialIndex: subMesh.materialIndex,
  2351. verticesStart: subMesh.verticesStart,
  2352. verticesCount: subMesh.verticesCount,
  2353. indexStart: subMesh.indexStart,
  2354. indexCount: subMesh.indexCount
  2355. });
  2356. }
  2357. }
  2358. // Material
  2359. if (this.material) {
  2360. serializationObject.materialId = this.material.id;
  2361. } else {
  2362. this.material = null;
  2363. }
  2364. // Morph targets
  2365. if (this.morphTargetManager) {
  2366. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  2367. }
  2368. // Skeleton
  2369. if (this.skeleton) {
  2370. serializationObject.skeletonId = this.skeleton.id;
  2371. }
  2372. // Physics
  2373. //TODO implement correct serialization for physics impostors.
  2374. let impostor = this.getPhysicsImpostor();
  2375. if (impostor) {
  2376. serializationObject.physicsMass = impostor.getParam("mass");
  2377. serializationObject.physicsFriction = impostor.getParam("friction");
  2378. serializationObject.physicsRestitution = impostor.getParam("mass");
  2379. serializationObject.physicsImpostor = impostor.type;
  2380. }
  2381. // Metadata
  2382. if (this.metadata) {
  2383. serializationObject.metadata = this.metadata;
  2384. }
  2385. // Instances
  2386. serializationObject.instances = [];
  2387. for (var index = 0; index < this.instances.length; index++) {
  2388. var instance = this.instances[index];
  2389. if (instance.doNotSerialize) {
  2390. continue;
  2391. }
  2392. var serializationInstance: any = {
  2393. name: instance.name,
  2394. id: instance.id,
  2395. position: instance.position.asArray(),
  2396. scaling: instance.scaling.asArray()
  2397. };
  2398. if (instance.parent) {
  2399. serializationInstance.parentId = instance.parent.id;
  2400. }
  2401. if (instance.rotationQuaternion) {
  2402. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  2403. } else if (instance.rotation) {
  2404. serializationInstance.rotation = instance.rotation.asArray();
  2405. }
  2406. serializationObject.instances.push(serializationInstance);
  2407. // Animations
  2408. SerializationHelper.AppendSerializedAnimations(instance, serializationInstance);
  2409. serializationInstance.ranges = instance.serializeAnimationRanges();
  2410. }
  2411. //
  2412. // Animations
  2413. SerializationHelper.AppendSerializedAnimations(this, serializationObject);
  2414. serializationObject.ranges = this.serializeAnimationRanges();
  2415. // Layer mask
  2416. serializationObject.layerMask = this.layerMask;
  2417. // Alpha
  2418. serializationObject.alphaIndex = this.alphaIndex;
  2419. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  2420. // Overlay
  2421. serializationObject.overlayAlpha = this.overlayAlpha;
  2422. serializationObject.overlayColor = this.overlayColor.asArray();
  2423. serializationObject.renderOverlay = this.renderOverlay;
  2424. // Fog
  2425. serializationObject.applyFog = this.applyFog;
  2426. // Action Manager
  2427. if (this.actionManager) {
  2428. serializationObject.actions = this.actionManager.serialize(this.name);
  2429. }
  2430. }
  2431. /** @hidden */
  2432. public _syncGeometryWithMorphTargetManager() {
  2433. if (!this.geometry) {
  2434. return;
  2435. }
  2436. this._markSubMeshesAsAttributesDirty();
  2437. let morphTargetManager = this._morphTargetManager;
  2438. if (morphTargetManager && morphTargetManager.vertexCount) {
  2439. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  2440. Logger.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  2441. this.morphTargetManager = null;
  2442. return;
  2443. }
  2444. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  2445. var morphTarget = morphTargetManager.getActiveTarget(index);
  2446. const positions = morphTarget.getPositions();
  2447. if (!positions) {
  2448. Logger.Error("Invalid morph target. Target must have positions.");
  2449. return;
  2450. }
  2451. this.geometry.setVerticesData(VertexBuffer.PositionKind + index, positions, false, 3);
  2452. const normals = morphTarget.getNormals();
  2453. if (normals) {
  2454. this.geometry.setVerticesData(VertexBuffer.NormalKind + index, normals, false, 3);
  2455. }
  2456. const tangents = morphTarget.getTangents();
  2457. if (tangents) {
  2458. this.geometry.setVerticesData(VertexBuffer.TangentKind + index, tangents, false, 3);
  2459. }
  2460. }
  2461. } else {
  2462. var index = 0;
  2463. // Positions
  2464. while (this.geometry.isVerticesDataPresent(VertexBuffer.PositionKind + index)) {
  2465. this.geometry.removeVerticesData(VertexBuffer.PositionKind + index);
  2466. if (this.geometry.isVerticesDataPresent(VertexBuffer.NormalKind + index)) {
  2467. this.geometry.removeVerticesData(VertexBuffer.NormalKind + index);
  2468. }
  2469. if (this.geometry.isVerticesDataPresent(VertexBuffer.TangentKind + index)) {
  2470. this.geometry.removeVerticesData(VertexBuffer.TangentKind + index);
  2471. }
  2472. index++;
  2473. }
  2474. }
  2475. }
  2476. // Statics
  2477. /** @hidden */
  2478. public static _GroundMeshParser = (parsedMesh: any, scene: Scene): Mesh => {
  2479. throw _DevTools.WarnImport("GroundMesh");
  2480. }
  2481. /**
  2482. * Returns a new Mesh object parsed from the source provided.
  2483. * @param parsedMesh is the source
  2484. * @param scene defines the hosting scene
  2485. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  2486. * @returns a new Mesh
  2487. */
  2488. public static Parse(parsedMesh: any, scene: Scene, rootUrl: string): Mesh {
  2489. var mesh: Mesh;
  2490. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  2491. mesh = Mesh._GroundMeshParser(parsedMesh, scene);
  2492. } else {
  2493. mesh = new Mesh(parsedMesh.name, scene);
  2494. }
  2495. mesh.id = parsedMesh.id;
  2496. if (Tags) {
  2497. Tags.AddTagsTo(mesh, parsedMesh.tags);
  2498. }
  2499. mesh.position = Vector3.FromArray(parsedMesh.position);
  2500. if (parsedMesh.metadata !== undefined) {
  2501. mesh.metadata = parsedMesh.metadata;
  2502. }
  2503. if (parsedMesh.rotationQuaternion) {
  2504. mesh.rotationQuaternion = Quaternion.FromArray(parsedMesh.rotationQuaternion);
  2505. } else if (parsedMesh.rotation) {
  2506. mesh.rotation = Vector3.FromArray(parsedMesh.rotation);
  2507. }
  2508. mesh.scaling = Vector3.FromArray(parsedMesh.scaling);
  2509. if (parsedMesh.localMatrix) {
  2510. mesh.setPreTransformMatrix(Matrix.FromArray(parsedMesh.localMatrix));
  2511. } else if (parsedMesh.pivotMatrix) {
  2512. mesh.setPivotMatrix(Matrix.FromArray(parsedMesh.pivotMatrix));
  2513. }
  2514. mesh.setEnabled(parsedMesh.isEnabled);
  2515. mesh.isVisible = parsedMesh.isVisible;
  2516. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  2517. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  2518. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  2519. if (parsedMesh.applyFog !== undefined) {
  2520. mesh.applyFog = parsedMesh.applyFog;
  2521. }
  2522. if (parsedMesh.pickable !== undefined) {
  2523. mesh.isPickable = parsedMesh.pickable;
  2524. }
  2525. if (parsedMesh.alphaIndex !== undefined) {
  2526. mesh.alphaIndex = parsedMesh.alphaIndex;
  2527. }
  2528. mesh.receiveShadows = parsedMesh.receiveShadows;
  2529. mesh.billboardMode = parsedMesh.billboardMode;
  2530. if (parsedMesh.visibility !== undefined) {
  2531. mesh.visibility = parsedMesh.visibility;
  2532. }
  2533. mesh.checkCollisions = parsedMesh.checkCollisions;
  2534. if (parsedMesh.isBlocker !== undefined) {
  2535. mesh.isBlocker = parsedMesh.isBlocker;
  2536. }
  2537. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  2538. // freezeWorldMatrix
  2539. if (parsedMesh.freezeWorldMatrix) {
  2540. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  2541. }
  2542. // Parent
  2543. if (parsedMesh.parentId) {
  2544. mesh._waitingParentId = parsedMesh.parentId;
  2545. }
  2546. // Actions
  2547. if (parsedMesh.actions !== undefined) {
  2548. mesh._waitingActions = parsedMesh.actions;
  2549. }
  2550. // Overlay
  2551. if (parsedMesh.overlayAlpha !== undefined) {
  2552. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  2553. }
  2554. if (parsedMesh.overlayColor !== undefined) {
  2555. mesh.overlayColor = Color3.FromArray(parsedMesh.overlayColor);
  2556. }
  2557. if (parsedMesh.renderOverlay !== undefined) {
  2558. mesh.renderOverlay = parsedMesh.renderOverlay;
  2559. }
  2560. // Geometry
  2561. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  2562. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  2563. if (parsedMesh.delayLoadingFile) {
  2564. mesh.delayLoadState = Constants.DELAYLOADSTATE_NOTLOADED;
  2565. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  2566. mesh._boundingInfo = new BoundingInfo(Vector3.FromArray(parsedMesh.boundingBoxMinimum), Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  2567. if (parsedMesh._binaryInfo) {
  2568. mesh._binaryInfo = parsedMesh._binaryInfo;
  2569. }
  2570. mesh._delayInfo = [];
  2571. if (parsedMesh.hasUVs) {
  2572. mesh._delayInfo.push(VertexBuffer.UVKind);
  2573. }
  2574. if (parsedMesh.hasUVs2) {
  2575. mesh._delayInfo.push(VertexBuffer.UV2Kind);
  2576. }
  2577. if (parsedMesh.hasUVs3) {
  2578. mesh._delayInfo.push(VertexBuffer.UV3Kind);
  2579. }
  2580. if (parsedMesh.hasUVs4) {
  2581. mesh._delayInfo.push(VertexBuffer.UV4Kind);
  2582. }
  2583. if (parsedMesh.hasUVs5) {
  2584. mesh._delayInfo.push(VertexBuffer.UV5Kind);
  2585. }
  2586. if (parsedMesh.hasUVs6) {
  2587. mesh._delayInfo.push(VertexBuffer.UV6Kind);
  2588. }
  2589. if (parsedMesh.hasColors) {
  2590. mesh._delayInfo.push(VertexBuffer.ColorKind);
  2591. }
  2592. if (parsedMesh.hasMatricesIndices) {
  2593. mesh._delayInfo.push(VertexBuffer.MatricesIndicesKind);
  2594. }
  2595. if (parsedMesh.hasMatricesWeights) {
  2596. mesh._delayInfo.push(VertexBuffer.MatricesWeightsKind);
  2597. }
  2598. mesh._delayLoadingFunction = Geometry._ImportGeometry;
  2599. if (SceneLoaderFlags.ForceFullSceneLoadingForIncremental) {
  2600. mesh._checkDelayState();
  2601. }
  2602. } else {
  2603. Geometry._ImportGeometry(parsedMesh, mesh);
  2604. }
  2605. // Material
  2606. if (parsedMesh.materialId) {
  2607. mesh.setMaterialByID(parsedMesh.materialId);
  2608. } else {
  2609. mesh.material = null;
  2610. }
  2611. // Morph targets
  2612. if (parsedMesh.morphTargetManagerId > -1) {
  2613. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  2614. }
  2615. // Skeleton
  2616. if (parsedMesh.skeletonId > -1) {
  2617. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  2618. if (parsedMesh.numBoneInfluencers) {
  2619. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  2620. }
  2621. }
  2622. // Animations
  2623. if (parsedMesh.animations) {
  2624. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  2625. var parsedAnimation = parsedMesh.animations[animationIndex];
  2626. const internalClass = _TypeStore.GetClass("BABYLON.Animation");
  2627. if (internalClass) {
  2628. mesh.animations.push(internalClass.Parse(parsedAnimation));
  2629. }
  2630. }
  2631. Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  2632. }
  2633. if (parsedMesh.autoAnimate) {
  2634. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  2635. }
  2636. // Layer Mask
  2637. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  2638. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  2639. } else {
  2640. mesh.layerMask = 0x0FFFFFFF;
  2641. }
  2642. // Physics
  2643. if (parsedMesh.physicsImpostor) {
  2644. Mesh._PhysicsImpostorParser(scene, mesh, parsedMesh);
  2645. }
  2646. // Instances
  2647. if (parsedMesh.instances) {
  2648. for (var index = 0; index < parsedMesh.instances.length; index++) {
  2649. var parsedInstance = parsedMesh.instances[index];
  2650. var instance = mesh.createInstance(parsedInstance.name);
  2651. if (parsedInstance.id) {
  2652. instance.id = parsedInstance.id;
  2653. }
  2654. if (Tags) {
  2655. if (parsedInstance.tags) {
  2656. Tags.AddTagsTo(instance, parsedInstance.tags);
  2657. } else {
  2658. Tags.AddTagsTo(instance, parsedMesh.tags);
  2659. }
  2660. }
  2661. instance.position = Vector3.FromArray(parsedInstance.position);
  2662. if (parsedInstance.parentId) {
  2663. instance._waitingParentId = parsedInstance.parentId;
  2664. }
  2665. if (parsedInstance.rotationQuaternion) {
  2666. instance.rotationQuaternion = Quaternion.FromArray(parsedInstance.rotationQuaternion);
  2667. } else if (parsedInstance.rotation) {
  2668. instance.rotation = Vector3.FromArray(parsedInstance.rotation);
  2669. }
  2670. instance.scaling = Vector3.FromArray(parsedInstance.scaling);
  2671. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  2672. instance.checkCollisions = parsedInstance.checkCollisions;
  2673. }
  2674. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  2675. instance.isPickable = parsedInstance.pickable;
  2676. }
  2677. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  2678. instance.showBoundingBox = parsedInstance.showBoundingBox;
  2679. }
  2680. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  2681. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  2682. }
  2683. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  2684. instance.alphaIndex = parsedInstance.alphaIndex;
  2685. }
  2686. // Physics
  2687. if (parsedInstance.physicsImpostor) {
  2688. Mesh._PhysicsImpostorParser(scene, instance, parsedInstance);
  2689. }
  2690. // Animation
  2691. if (parsedInstance.animations) {
  2692. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  2693. parsedAnimation = parsedInstance.animations[animationIndex];
  2694. const internalClass = _TypeStore.GetClass("BABYLON.Animation");
  2695. if (internalClass) {
  2696. instance.animations.push(internalClass.Parse(parsedAnimation));
  2697. }
  2698. }
  2699. Node.ParseAnimationRanges(instance, parsedInstance, scene);
  2700. if (parsedInstance.autoAnimate) {
  2701. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  2702. }
  2703. }
  2704. }
  2705. }
  2706. return mesh;
  2707. }
  2708. /**
  2709. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  2710. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  2711. * @param name defines the name of the mesh to create
  2712. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  2713. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  2714. * @param closePath creates a seam between the first and the last points of each path of the path array
  2715. * @param offset is taken in account only if the `pathArray` is containing a single path
  2716. * @param scene defines the hosting scene
  2717. * @param updatable defines if the mesh must be flagged as updatable
  2718. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2719. * @param instance defines an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#ribbon)
  2720. * @returns a new Mesh
  2721. */
  2722. public static CreateRibbon(name: string, pathArray: Vector3[][], closeArray: boolean, closePath: boolean, offset: number, scene?: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh {
  2723. throw _DevTools.WarnImport("MeshBuilder");
  2724. }
  2725. /**
  2726. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  2727. * @param name defines the name of the mesh to create
  2728. * @param radius sets the radius size (float) of the polygon (default 0.5)
  2729. * @param tessellation sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc
  2730. * @param scene defines the hosting scene
  2731. * @param updatable defines if the mesh must be flagged as updatable
  2732. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2733. * @returns a new Mesh
  2734. */
  2735. public static CreateDisc(name: string, radius: number, tessellation: number, scene: Nullable<Scene> = null, updatable?: boolean, sideOrientation?: number): Mesh {
  2736. throw _DevTools.WarnImport("MeshBuilder");
  2737. }
  2738. /**
  2739. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  2740. * @param name defines the name of the mesh to create
  2741. * @param size sets the size (float) of each box side (default 1)
  2742. * @param scene defines the hosting scene
  2743. * @param updatable defines if the mesh must be flagged as updatable
  2744. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2745. * @returns a new Mesh
  2746. */
  2747. public static CreateBox(name: string, size: number, scene: Nullable<Scene> = null, updatable?: boolean, sideOrientation?: number): Mesh {
  2748. throw _DevTools.WarnImport("MeshBuilder");
  2749. }
  2750. /**
  2751. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  2752. * @param name defines the name of the mesh to create
  2753. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  2754. * @param diameter sets the diameter size (float) of the sphere (default 1)
  2755. * @param scene defines the hosting scene
  2756. * @param updatable defines if the mesh must be flagged as updatable
  2757. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2758. * @returns a new Mesh
  2759. */
  2760. public static CreateSphere(name: string, segments: number, diameter: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  2761. throw _DevTools.WarnImport("MeshBuilder");
  2762. }
  2763. /**
  2764. * Creates a hemisphere mesh. Please consider using the same method from the MeshBuilder class instead
  2765. * @param name defines the name of the mesh to create
  2766. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  2767. * @param diameter sets the diameter size (float) of the sphere (default 1)
  2768. * @param scene defines the hosting scene
  2769. * @returns a new Mesh
  2770. */
  2771. public static CreateHemisphere(name: string, segments: number, diameter: number, scene?: Scene): Mesh {
  2772. throw _DevTools.WarnImport("MeshBuilder");
  2773. }
  2774. /**
  2775. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  2776. * @param name defines the name of the mesh to create
  2777. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  2778. * @param diameterTop set the top cap diameter (floats, default 1)
  2779. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  2780. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  2781. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  2782. * @param scene defines the hosting scene
  2783. * @param updatable defines if the mesh must be flagged as updatable
  2784. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2785. * @returns a new Mesh
  2786. */
  2787. public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene?: Scene, updatable?: any, sideOrientation?: number): Mesh {
  2788. throw _DevTools.WarnImport("MeshBuilder");
  2789. }
  2790. // Torus (Code from SharpDX.org)
  2791. /**
  2792. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  2793. * @param name defines the name of the mesh to create
  2794. * @param diameter sets the diameter size (float) of the torus (default 1)
  2795. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  2796. * @param tessellation sets the number of torus sides (postive integer, default 16)
  2797. * @param scene defines the hosting scene
  2798. * @param updatable defines if the mesh must be flagged as updatable
  2799. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2800. * @returns a new Mesh
  2801. */
  2802. public static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  2803. throw _DevTools.WarnImport("MeshBuilder");
  2804. }
  2805. /**
  2806. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  2807. * @param name defines the name of the mesh to create
  2808. * @param radius sets the global radius size (float) of the torus knot (default 2)
  2809. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  2810. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  2811. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  2812. * @param p the number of windings on X axis (positive integers, default 2)
  2813. * @param q the number of windings on Y axis (positive integers, default 3)
  2814. * @param scene defines the hosting scene
  2815. * @param updatable defines if the mesh must be flagged as updatable
  2816. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2817. * @returns a new Mesh
  2818. */
  2819. public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  2820. throw _DevTools.WarnImport("MeshBuilder");
  2821. }
  2822. /**
  2823. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  2824. * @param name defines the name of the mesh to create
  2825. * @param points is an array successive Vector3
  2826. * @param scene defines the hosting scene
  2827. * @param updatable defines if the mesh must be flagged as updatable
  2828. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines).
  2829. * @returns a new Mesh
  2830. */
  2831. public static CreateLines(name: string, points: Vector3[], scene: Nullable<Scene> = null, updatable: boolean = false, instance: Nullable<LinesMesh> = null): LinesMesh {
  2832. throw _DevTools.WarnImport("MeshBuilder");
  2833. }
  2834. /**
  2835. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  2836. * @param name defines the name of the mesh to create
  2837. * @param points is an array successive Vector3
  2838. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  2839. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  2840. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  2841. * @param scene defines the hosting scene
  2842. * @param updatable defines if the mesh must be flagged as updatable
  2843. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines)
  2844. * @returns a new Mesh
  2845. */
  2846. public static CreateDashedLines(name: string, points: Vector3[], dashSize: number, gapSize: number, dashNb: number, scene: Nullable<Scene> = null, updatable?: boolean, instance?: LinesMesh): LinesMesh {
  2847. throw _DevTools.WarnImport("MeshBuilder");
  2848. }
  2849. /**
  2850. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  2851. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  2852. * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
  2853. * You can set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
  2854. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2855. * Remember you can only change the shape positions, not their number when updating a polygon.
  2856. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  2857. * @param name defines the name of the mesh to create
  2858. * @param shape is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors
  2859. * @param scene defines the hosting scene
  2860. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  2861. * @param updatable defines if the mesh must be flagged as updatable
  2862. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2863. * @param earcutInjection can be used to inject your own earcut reference
  2864. * @returns a new Mesh
  2865. */
  2866. public static CreatePolygon(name: string, shape: Vector3[], scene: Scene, holes?: Vector3[][], updatable?: boolean, sideOrientation?: number, earcutInjection = earcut): Mesh {
  2867. throw _DevTools.WarnImport("MeshBuilder");
  2868. }
  2869. /**
  2870. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  2871. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  2872. * @param name defines the name of the mesh to create
  2873. * @param shape is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors
  2874. * @param depth defines the height of extrusion
  2875. * @param scene defines the hosting scene
  2876. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  2877. * @param updatable defines if the mesh must be flagged as updatable
  2878. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2879. * @param earcutInjection can be used to inject your own earcut reference
  2880. * @returns a new Mesh
  2881. */
  2882. public static ExtrudePolygon(name: string, shape: Vector3[], depth: number, scene: Scene, holes?: Vector3[][], updatable?: boolean, sideOrientation?: number, earcutInjection = earcut): Mesh {
  2883. throw _DevTools.WarnImport("MeshBuilder");
  2884. }
  2885. /**
  2886. * Creates an extruded shape mesh.
  2887. * The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. Please consider using the same method from the MeshBuilder class instead
  2888. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  2889. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  2890. * @param name defines the name of the mesh to create
  2891. * @param shape is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis
  2892. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  2893. * @param scale is the value to scale the shape
  2894. * @param rotation is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve
  2895. * @param cap sets the way the extruded shape is capped. Possible values : Mesh.NO_CAP (default), Mesh.CAP_START, Mesh.CAP_END, Mesh.CAP_ALL
  2896. * @param scene defines the hosting scene
  2897. * @param updatable defines if the mesh must be flagged as updatable
  2898. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2899. * @param instance is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#extruded-shape)
  2900. * @returns a new Mesh
  2901. */
  2902. public static ExtrudeShape(name: string, shape: Vector3[], path: Vector3[], scale: number, rotation: number, cap: number, scene: Nullable<Scene> = null, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh {
  2903. throw _DevTools.WarnImport("MeshBuilder");
  2904. }
  2905. /**
  2906. * Creates an custom extruded shape mesh.
  2907. * The custom extrusion is a parametric shape.
  2908. * It has no predefined shape. Its final shape will depend on the input parameters.
  2909. * Please consider using the same method from the MeshBuilder class instead
  2910. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  2911. * @param name defines the name of the mesh to create
  2912. * @param shape is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis
  2913. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  2914. * @param scaleFunction is a custom Javascript function called on each path point
  2915. * @param rotationFunction is a custom Javascript function called on each path point
  2916. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  2917. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  2918. * @param cap sets the way the extruded shape is capped. Possible values : Mesh.NO_CAP (default), Mesh.CAP_START, Mesh.CAP_END, Mesh.CAP_ALL
  2919. * @param scene defines the hosting scene
  2920. * @param updatable defines if the mesh must be flagged as updatable
  2921. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2922. * @param instance is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters (http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#extruded-shape)
  2923. * @returns a new Mesh
  2924. */
  2925. public static ExtrudeShapeCustom(name: string, shape: Vector3[], path: Vector3[], scaleFunction: Function, rotationFunction: Function, ribbonCloseArray: boolean, ribbonClosePath: boolean, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh {
  2926. throw _DevTools.WarnImport("MeshBuilder");
  2927. }
  2928. /**
  2929. * Creates lathe mesh.
  2930. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  2931. * Please consider using the same method from the MeshBuilder class instead
  2932. * @param name defines the name of the mesh to create
  2933. * @param shape is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  2934. * @param radius is the radius value of the lathe
  2935. * @param tessellation is the side number of the lathe.
  2936. * @param scene defines the hosting scene
  2937. * @param updatable defines if the mesh must be flagged as updatable
  2938. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2939. * @returns a new Mesh
  2940. */
  2941. public static CreateLathe(name: string, shape: Vector3[], radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  2942. throw _DevTools.WarnImport("MeshBuilder");
  2943. }
  2944. /**
  2945. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  2946. * @param name defines the name of the mesh to create
  2947. * @param size sets the size (float) of both sides of the plane at once (default 1)
  2948. * @param scene defines the hosting scene
  2949. * @param updatable defines if the mesh must be flagged as updatable
  2950. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2951. * @returns a new Mesh
  2952. */
  2953. public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  2954. throw _DevTools.WarnImport("MeshBuilder");
  2955. }
  2956. /**
  2957. * Creates a ground mesh.
  2958. * Please consider using the same method from the MeshBuilder class instead
  2959. * @param name defines the name of the mesh to create
  2960. * @param width set the width of the ground
  2961. * @param height set the height of the ground
  2962. * @param subdivisions sets the number of subdivisions per side
  2963. * @param scene defines the hosting scene
  2964. * @param updatable defines if the mesh must be flagged as updatable
  2965. * @returns a new Mesh
  2966. */
  2967. public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene?: Scene, updatable?: boolean): Mesh {
  2968. throw _DevTools.WarnImport("MeshBuilder");
  2969. }
  2970. /**
  2971. * Creates a tiled ground mesh.
  2972. * Please consider using the same method from the MeshBuilder class instead
  2973. * @param name defines the name of the mesh to create
  2974. * @param xmin set the ground minimum X coordinate
  2975. * @param zmin set the ground minimum Y coordinate
  2976. * @param xmax set the ground maximum X coordinate
  2977. * @param zmax set the ground maximum Z coordinate
  2978. * @param subdivisions is an object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  2979. * @param precision is an object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  2980. * @param scene defines the hosting scene
  2981. * @param updatable defines if the mesh must be flagged as updatable
  2982. * @returns a new Mesh
  2983. */
  2984. public static CreateTiledGround(name: string, xmin: number, zmin: number, xmax: number, zmax: number, subdivisions: { w: number; h: number; }, precision: { w: number; h: number; }, scene: Scene, updatable?: boolean): Mesh {
  2985. throw _DevTools.WarnImport("MeshBuilder");
  2986. }
  2987. /**
  2988. * Creates a ground mesh from a height map.
  2989. * Please consider using the same method from the MeshBuilder class instead
  2990. * @see http://doc.babylonjs.com/babylon101/height_map
  2991. * @param name defines the name of the mesh to create
  2992. * @param url sets the URL of the height map image resource
  2993. * @param width set the ground width size
  2994. * @param height set the ground height size
  2995. * @param subdivisions sets the number of subdivision per side
  2996. * @param minHeight is the minimum altitude on the ground
  2997. * @param maxHeight is the maximum altitude on the ground
  2998. * @param scene defines the hosting scene
  2999. * @param updatable defines if the mesh must be flagged as updatable
  3000. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  3001. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  3002. * @returns a new Mesh
  3003. */
  3004. public static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene: Scene, updatable?: boolean, onReady?: (mesh: GroundMesh) => void, alphaFilter?: number): GroundMesh {
  3005. throw _DevTools.WarnImport("MeshBuilder");
  3006. }
  3007. /**
  3008. * Creates a tube mesh.
  3009. * The tube is a parametric shape.
  3010. * It has no predefined shape. Its final shape will depend on the input parameters.
  3011. * Please consider using the same method from the MeshBuilder class instead
  3012. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  3013. * @param name defines the name of the mesh to create
  3014. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  3015. * @param radius sets the tube radius size
  3016. * @param tessellation is the number of sides on the tubular surface
  3017. * @param radiusFunction is a custom function. If it is not null, it overwrittes the parameter `radius`. This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path
  3018. * @param cap sets the way the extruded shape is capped. Possible values : Mesh.NO_CAP (default), Mesh.CAP_START, Mesh.CAP_END, Mesh.CAP_ALL
  3019. * @param scene defines the hosting scene
  3020. * @param updatable defines if the mesh must be flagged as updatable
  3021. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  3022. * @param instance is an instance of an existing Tube object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#tube)
  3023. * @returns a new Mesh
  3024. */
  3025. public static CreateTube(name: string, path: Vector3[], radius: number, tessellation: number, radiusFunction: { (i: number, distance: number): number; }, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh {
  3026. throw _DevTools.WarnImport("MeshBuilder");
  3027. }
  3028. /**
  3029. * Creates a polyhedron mesh.
  3030. * Please consider using the same method from the MeshBuilder class instead.
  3031. * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type
  3032. * * The parameter `size` (positive float, default 1) sets the polygon size
  3033. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  3034. * * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`
  3035. * * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  3036. * * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`)
  3037. * * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : https://doc.babylonjs.com/how_to/createbox_per_face_textures_and_colors
  3038. * * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored
  3039. * * You can also set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
  3040. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  3041. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  3042. * @param name defines the name of the mesh to create
  3043. * @param options defines the options used to create the mesh
  3044. * @param scene defines the hosting scene
  3045. * @returns a new Mesh
  3046. */
  3047. public static CreatePolyhedron(name: string, options: { type?: number, size?: number, sizeX?: number, sizeY?: number, sizeZ?: number, custom?: any, faceUV?: Vector4[], faceColors?: Color4[], updatable?: boolean, sideOrientation?: number }, scene: Scene): Mesh {
  3048. throw _DevTools.WarnImport("MeshBuilder");
  3049. }
  3050. /**
  3051. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  3052. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  3053. * * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`)
  3054. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  3055. * * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface
  3056. * * You can also set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
  3057. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  3058. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  3059. * @param name defines the name of the mesh
  3060. * @param options defines the options used to create the mesh
  3061. * @param scene defines the hosting scene
  3062. * @returns a new Mesh
  3063. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  3064. */
  3065. public static CreateIcoSphere(name: string, options: { radius?: number, flat?: boolean, subdivisions?: number, sideOrientation?: number, updatable?: boolean }, scene: Scene): Mesh {
  3066. throw _DevTools.WarnImport("MeshBuilder");
  3067. }
  3068. /**
  3069. * Creates a decal mesh.
  3070. * Please consider using the same method from the MeshBuilder class instead.
  3071. * A decal is a mesh usually applied as a model onto the surface of another mesh
  3072. * @param name defines the name of the mesh
  3073. * @param sourceMesh defines the mesh receiving the decal
  3074. * @param position sets the position of the decal in world coordinates
  3075. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  3076. * @param size sets the decal scaling
  3077. * @param angle sets the angle to rotate the decal
  3078. * @returns a new Mesh
  3079. */
  3080. public static CreateDecal(name: string, sourceMesh: AbstractMesh, position: Vector3, normal: Vector3, size: Vector3, angle: number): Mesh {
  3081. throw _DevTools.WarnImport("MeshBuilder");
  3082. }
  3083. // Skeletons
  3084. /**
  3085. * Prepare internal position array for software CPU skinning
  3086. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  3087. */
  3088. public setPositionsForCPUSkinning(): Float32Array {
  3089. if (!this._sourcePositions) {
  3090. let source = this.getVerticesData(VertexBuffer.PositionKind);
  3091. if (!source) {
  3092. return this._sourcePositions;
  3093. }
  3094. this._sourcePositions = new Float32Array(<any>source);
  3095. if (!this.isVertexBufferUpdatable(VertexBuffer.PositionKind)) {
  3096. this.setVerticesData(VertexBuffer.PositionKind, source, true);
  3097. }
  3098. }
  3099. return this._sourcePositions;
  3100. }
  3101. /**
  3102. * Prepare internal normal array for software CPU skinning
  3103. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  3104. */
  3105. public setNormalsForCPUSkinning(): Float32Array {
  3106. if (!this._sourceNormals) {
  3107. let source = this.getVerticesData(VertexBuffer.NormalKind);
  3108. if (!source) {
  3109. return this._sourceNormals;
  3110. }
  3111. this._sourceNormals = new Float32Array(<any>source);
  3112. if (!this.isVertexBufferUpdatable(VertexBuffer.NormalKind)) {
  3113. this.setVerticesData(VertexBuffer.NormalKind, source, true);
  3114. }
  3115. }
  3116. return this._sourceNormals;
  3117. }
  3118. /**
  3119. * Updates the vertex buffer by applying transformation from the bones
  3120. * @param skeleton defines the skeleton to apply to current mesh
  3121. * @returns the current mesh
  3122. */
  3123. public applySkeleton(skeleton: Skeleton): Mesh {
  3124. if (!this.geometry) {
  3125. return this;
  3126. }
  3127. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  3128. return this;
  3129. }
  3130. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  3131. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  3132. return this;
  3133. }
  3134. if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  3135. return this;
  3136. }
  3137. if (!this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {
  3138. return this;
  3139. }
  3140. if (!this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
  3141. return this;
  3142. }
  3143. if (!this._sourcePositions) {
  3144. var submeshes = this.subMeshes.slice();
  3145. this.setPositionsForCPUSkinning();
  3146. this.subMeshes = submeshes;
  3147. }
  3148. if (!this._sourceNormals) {
  3149. this.setNormalsForCPUSkinning();
  3150. }
  3151. // positionsData checks for not being Float32Array will only pass at most once
  3152. var positionsData = this.getVerticesData(VertexBuffer.PositionKind);
  3153. if (!positionsData) {
  3154. return this;
  3155. }
  3156. if (!(positionsData instanceof Float32Array)) {
  3157. positionsData = new Float32Array(positionsData);
  3158. }
  3159. // normalsData checks for not being Float32Array will only pass at most once
  3160. var normalsData = this.getVerticesData(VertexBuffer.NormalKind);
  3161. if (!normalsData) {
  3162. return this;
  3163. }
  3164. if (!(normalsData instanceof Float32Array)) {
  3165. normalsData = new Float32Array(normalsData);
  3166. }
  3167. var matricesIndicesData = this.getVerticesData(VertexBuffer.MatricesIndicesKind);
  3168. var matricesWeightsData = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
  3169. if (!matricesWeightsData || !matricesIndicesData) {
  3170. return this;
  3171. }
  3172. var needExtras = this.numBoneInfluencers > 4;
  3173. var matricesIndicesExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind) : null;
  3174. var matricesWeightsExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind) : null;
  3175. var skeletonMatrices = skeleton.getTransformMatrices(this);
  3176. var tempVector3 = Vector3.Zero();
  3177. var finalMatrix = new Matrix();
  3178. var tempMatrix = new Matrix();
  3179. var matWeightIdx = 0;
  3180. var inf: number;
  3181. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  3182. var weight: number;
  3183. for (inf = 0; inf < 4; inf++) {
  3184. weight = matricesWeightsData[matWeightIdx + inf];
  3185. if (weight > 0) {
  3186. Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  3187. finalMatrix.addToSelf(tempMatrix);
  3188. }
  3189. }
  3190. if (needExtras) {
  3191. for (inf = 0; inf < 4; inf++) {
  3192. weight = matricesWeightsExtraData![matWeightIdx + inf];
  3193. if (weight > 0) {
  3194. Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData![matWeightIdx + inf] * 16), weight, tempMatrix);
  3195. finalMatrix.addToSelf(tempMatrix);
  3196. }
  3197. }
  3198. }
  3199. Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  3200. tempVector3.toArray(positionsData, index);
  3201. Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  3202. tempVector3.toArray(normalsData, index);
  3203. finalMatrix.reset();
  3204. }
  3205. this.updateVerticesData(VertexBuffer.PositionKind, positionsData);
  3206. this.updateVerticesData(VertexBuffer.NormalKind, normalsData);
  3207. return this;
  3208. }
  3209. // Tools
  3210. /**
  3211. * Returns an object containing a min and max Vector3 which are the minimum and maximum vectors of each mesh bounding box from the passed array, in the world coordinates
  3212. * @param meshes defines the list of meshes to scan
  3213. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  3214. */
  3215. public static MinMax(meshes: AbstractMesh[]): { min: Vector3; max: Vector3 } {
  3216. var minVector: Nullable<Vector3> = null;
  3217. var maxVector: Nullable<Vector3> = null;
  3218. meshes.forEach(function(mesh) {
  3219. let boundingInfo = mesh.getBoundingInfo();
  3220. let boundingBox = boundingInfo.boundingBox;
  3221. if (!minVector || !maxVector) {
  3222. minVector = boundingBox.minimumWorld;
  3223. maxVector = boundingBox.maximumWorld;
  3224. } else {
  3225. minVector.minimizeInPlace(boundingBox.minimumWorld);
  3226. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  3227. }
  3228. });
  3229. if (!minVector || !maxVector) {
  3230. return {
  3231. min: Vector3.Zero(),
  3232. max: Vector3.Zero()
  3233. };
  3234. }
  3235. return {
  3236. min: minVector,
  3237. max: maxVector
  3238. };
  3239. }
  3240. /**
  3241. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  3242. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  3243. * @returns a vector3
  3244. */
  3245. public static Center(meshesOrMinMaxVector: { min: Vector3; max: Vector3 } | AbstractMesh[]): Vector3 {
  3246. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  3247. return Vector3.Center(minMaxVector.min, minMaxVector.max);
  3248. }
  3249. /**
  3250. * Merge the array of meshes into a single mesh for performance reasons.
  3251. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  3252. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  3253. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  3254. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  3255. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  3256. * @param multiMultiMaterials when true (false default), subdivide mesh and accept multiple multi materials, ignores subdivideWithSubMeshes.
  3257. * @returns a new mesh
  3258. */
  3259. public static MergeMeshes(meshes: Array<Mesh>, disposeSource = true, allow32BitsIndices?: boolean, meshSubclass?: Mesh, subdivideWithSubMeshes?: boolean, multiMultiMaterials?: boolean): Nullable<Mesh> {
  3260. var index: number;
  3261. if (!allow32BitsIndices) {
  3262. var totalVertices = 0;
  3263. // Counting vertices
  3264. for (index = 0; index < meshes.length; index++) {
  3265. if (meshes[index]) {
  3266. totalVertices += meshes[index].getTotalVertices();
  3267. if (totalVertices > 65536) {
  3268. Logger.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  3269. return null;
  3270. }
  3271. }
  3272. }
  3273. }
  3274. if (multiMultiMaterials) {
  3275. var newMultiMaterial: Nullable<MultiMaterial> = null;
  3276. var subIndex: number;
  3277. var matIndex: number;
  3278. subdivideWithSubMeshes = false;
  3279. }
  3280. var materialArray: Array<Material> = new Array<Material>();
  3281. var materialIndexArray: Array<number> = new Array<number>();
  3282. // Merge
  3283. var vertexData: Nullable<VertexData> = null;
  3284. var otherVertexData: VertexData;
  3285. var indiceArray: Array<number> = new Array<number>();
  3286. var source: Nullable<Mesh> = null;
  3287. for (index = 0; index < meshes.length; index++) {
  3288. if (meshes[index]) {
  3289. var mesh = meshes[index];
  3290. const wm = mesh.computeWorldMatrix(true);
  3291. otherVertexData = VertexData.ExtractFromMesh(mesh, true, true);
  3292. otherVertexData.transform(wm);
  3293. if (vertexData) {
  3294. vertexData.merge(otherVertexData, allow32BitsIndices);
  3295. } else {
  3296. vertexData = otherVertexData;
  3297. source = mesh;
  3298. }
  3299. if (subdivideWithSubMeshes) {
  3300. indiceArray.push(mesh.getTotalIndices());
  3301. }
  3302. if (multiMultiMaterials) {
  3303. if (mesh.material) {
  3304. var material = mesh.material;
  3305. if (material instanceof MultiMaterial) {
  3306. for (matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  3307. if (materialArray.indexOf(<Material>material.subMaterials[matIndex]) < 0) {
  3308. materialArray.push(<Material>material.subMaterials[matIndex]);
  3309. }
  3310. }
  3311. for (subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  3312. materialIndexArray.push(materialArray.indexOf(<Material>material.subMaterials[mesh.subMeshes[subIndex].materialIndex]));
  3313. indiceArray.push(mesh.subMeshes[subIndex].indexCount);
  3314. }
  3315. } else {
  3316. if (materialArray.indexOf(<Material>material) < 0) {
  3317. materialArray.push(<Material>material);
  3318. }
  3319. for (subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  3320. materialIndexArray.push(materialArray.indexOf(<Material>material));
  3321. indiceArray.push(mesh.subMeshes[subIndex].indexCount);
  3322. }
  3323. }
  3324. } else {
  3325. for (subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  3326. materialIndexArray.push(0);
  3327. indiceArray.push(mesh.subMeshes[subIndex].indexCount);
  3328. }
  3329. }
  3330. }
  3331. }
  3332. }
  3333. source = <Mesh>source;
  3334. if (!meshSubclass) {
  3335. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  3336. }
  3337. (<VertexData>vertexData).applyToMesh(meshSubclass);
  3338. // Setting properties
  3339. meshSubclass.checkCollisions = source.checkCollisions;
  3340. // Cleaning
  3341. if (disposeSource) {
  3342. for (index = 0; index < meshes.length; index++) {
  3343. if (meshes[index]) {
  3344. meshes[index].dispose();
  3345. }
  3346. }
  3347. }
  3348. // Subdivide
  3349. if (subdivideWithSubMeshes || multiMultiMaterials) {
  3350. //-- removal of global submesh
  3351. meshSubclass.releaseSubMeshes();
  3352. index = 0;
  3353. var offset = 0;
  3354. //-- apply subdivision according to index table
  3355. while (index < indiceArray.length) {
  3356. SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  3357. offset += indiceArray[index];
  3358. index++;
  3359. }
  3360. }
  3361. if (multiMultiMaterials) {
  3362. newMultiMaterial = new MultiMaterial(source.name + "_merged", source.getScene());
  3363. newMultiMaterial.subMaterials = materialArray;
  3364. for (subIndex = 0; subIndex < meshSubclass.subMeshes.length; subIndex++) {
  3365. meshSubclass.subMeshes[subIndex].materialIndex = materialIndexArray[subIndex];
  3366. }
  3367. meshSubclass.material = newMultiMaterial;
  3368. } else {
  3369. meshSubclass.material = source.material;
  3370. }
  3371. return meshSubclass;
  3372. }
  3373. /** @hidden */
  3374. public addInstance(instance: InstancedMesh) {
  3375. instance._indexInSourceMeshInstanceArray = this.instances.length;
  3376. this.instances.push(instance);
  3377. }
  3378. /** @hidden */
  3379. public removeInstance(instance: InstancedMesh) {
  3380. // Remove from mesh
  3381. const index = instance._indexInSourceMeshInstanceArray;
  3382. if (index != -1) {
  3383. if (index !== this.instances.length - 1) {
  3384. const last = this.instances[this.instances.length - 1];
  3385. this.instances[index] = last;
  3386. last._indexInSourceMeshInstanceArray = index;
  3387. }
  3388. instance._indexInSourceMeshInstanceArray = -1;
  3389. this.instances.pop();
  3390. }
  3391. }
  3392. }