mesh.ts 175 KB

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