mesh.ts 176 KB

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