12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449 |
- module BABYLON {
- /**
- * @hidden
- **/
- export class _InstancesBatch {
- public mustReturn = false;
- public visibleInstances = new Array<Nullable<Array<InstancedMesh>>>();
- public renderSelf = new Array<boolean>();
- }
- export class Mesh extends AbstractMesh implements IGetSetVerticesData {
- // Consts
- public static _FRONTSIDE: number = 0;
- public static _BACKSIDE: number = 1;
- public static _DOUBLESIDE: number = 2;
- public static _DEFAULTSIDE: number = 0;
- public static _NO_CAP = 0;
- public static _CAP_START = 1;
- public static _CAP_END = 2;
- public static _CAP_ALL = 3;
- /**
- * Mesh side orientation : usually the external or front surface
- */
- public static get FRONTSIDE(): number {
- return Mesh._FRONTSIDE;
- }
- /**
- * Mesh side orientation : usually the internal or back surface
- */
- public static get BACKSIDE(): number {
- return Mesh._BACKSIDE;
- }
- /**
- * Mesh side orientation : both internal and external or front and back surfaces
- */
- public static get DOUBLESIDE(): number {
- return Mesh._DOUBLESIDE;
- }
- /**
- * Mesh side orientation : by default, `FRONTSIDE`
- */
- public static get DEFAULTSIDE(): number {
- return Mesh._DEFAULTSIDE;
- }
- /**
- * Mesh cap setting : no cap
- */
- public static get NO_CAP(): number {
- return Mesh._NO_CAP;
- }
- /**
- * Mesh cap setting : one cap at the beginning of the mesh
- */
- public static get CAP_START(): number {
- return Mesh._CAP_START;
- }
- /**
- * Mesh cap setting : one cap at the end of the mesh
- */
- public static get CAP_END(): number {
- return Mesh._CAP_END;
- }
- /**
- * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
- */
- public static get CAP_ALL(): number {
- return Mesh._CAP_ALL;
- }
- // Events
- /**
- * An event triggered before rendering the mesh
- */
- public onBeforeRenderObservable = new Observable<Mesh>();
- /**
- * An event triggered after rendering the mesh
- */
- public onAfterRenderObservable = new Observable<Mesh>();
- /**
- * An event triggered before drawing the mesh
- */
- public onBeforeDrawObservable = new Observable<Mesh>();
- private _onBeforeDrawObserver: Nullable<Observer<Mesh>>;
- public set onBeforeDraw(callback: () => void) {
- if (this._onBeforeDrawObserver) {
- this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
- }
- this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
- }
- // Members
- public delayLoadState = Engine.DELAYLOADSTATE_NONE;
- public instances = new Array<InstancedMesh>();
- public delayLoadingFile: string;
- public _binaryInfo: any;
- private _LODLevels = new Array<MeshLODLevel>();
- public onLODLevelSelection: (distance: number, mesh: Mesh, selectedLevel: Nullable<Mesh>) => void;
- // Morph
- private _morphTargetManager: Nullable<MorphTargetManager>;
- public get morphTargetManager(): Nullable<MorphTargetManager> {
- return this._morphTargetManager;
- }
- public set morphTargetManager(value: Nullable<MorphTargetManager>) {
- if (this._morphTargetManager === value) {
- return;
- }
- this._morphTargetManager = value;
- this._syncGeometryWithMorphTargetManager();
- }
- // Private
- public _geometry: Nullable<Geometry>;
- public _delayInfo: Array<string>;
- public _delayLoadingFunction: (any: any, mesh: Mesh) => void;
- public _visibleInstances: any = {};
- private _renderIdForInstances = new Array<number>();
- private _batchCache = new _InstancesBatch();
- private _instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
- private _instancesBuffer: Nullable<Buffer>;
- private _instancesData: Float32Array;
- private _overridenInstanceCount: number;
- private _effectiveMaterial: Material;
- public _shouldGenerateFlatShading: boolean;
- private _preActivateId: number;
- // Use by builder only to know what orientation were the mesh build in.
- public _originalBuilderSideOrientation: number = Mesh._DEFAULTSIDE;
- public overrideMaterialSideOrientation: Nullable<number> = null;
- private _areNormalsFrozen: boolean = false; // Will be used by ribbons mainly
- private _sourcePositions: Float32Array; // Will be used to save original positions when using software skinning
- private _sourceNormals: Float32Array; // Will be used to save original normals when using software skinning
- // Will be used to save a source mesh reference, If any
- private _source: Nullable<Mesh> = null;
- public get source(): Nullable<Mesh> {
- return this._source;
- }
- public get isUnIndexed(): boolean {
- return this._unIndexed;
- }
- public set isUnIndexed(value: boolean) {
- if (this._unIndexed !== value) {
- this._unIndexed = value;
- this._markSubMeshesAsAttributesDirty();
- }
- }
- /**
- * @constructor
- * @param {string} name The value used by scene.getMeshByName() to do a lookup.
- * @param {Scene} scene The scene to add this mesh to.
- * @param {Node} parent The parent of this mesh, if it has one
- * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
- * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
- * When false, achieved by calling a clone(), also passing False.
- * This will make creation of children, recursive.
- * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
- */
- constructor(name: string, scene: Nullable<Scene> = null, parent: Nullable<Node> = null, source: Nullable<Mesh> = null, doNotCloneChildren?: boolean, clonePhysicsImpostor: boolean = true) {
- super(name, scene);
- scene = this.getScene();
- if (source) {
- // Geometry
- if (source._geometry) {
- source._geometry.applyToMesh(this);
- }
- // Deep copy
- Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
- "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"],
- ["_poseMatrix"]);
- // Source mesh
- this._source = source;
- // Metadata
- if (source.metadata && source.metadata.clone) {
- this.metadata = source.metadata.clone();
- } else {
- this.metadata = source.metadata;
- }
- // Tags
- if (Tags && Tags.HasTags(source)) {
- Tags.AddTagsTo(this, Tags.GetTags(source, true));
- }
- // Parent
- this.parent = source.parent;
- // Pivot
- this.setPivotMatrix(source.getPivotMatrix());
- this.id = name + "." + source.id;
- // Material
- this.material = source.material;
- var index: number;
- if (!doNotCloneChildren) {
- // Children
- let directDescendants = source.getDescendants(true);
- for (let index = 0; index < directDescendants.length; index++) {
- var child = directDescendants[index];
- if ((<any>child).clone) {
- (<any>child).clone(name + "." + child.name, this);
- }
- }
- }
- // Physics clone
- var physicsEngine = this.getScene().getPhysicsEngine();
- if (clonePhysicsImpostor && physicsEngine) {
- var impostor = physicsEngine.getImpostorForPhysicsObject(source);
- if (impostor) {
- this.physicsImpostor = impostor.clone(this);
- }
- }
- // Particles
- for (index = 0; index < scene.particleSystems.length; index++) {
- var system = scene.particleSystems[index];
- if (system.emitter === source) {
- system.clone(system.name, this);
- }
- }
- this.refreshBoundingInfo();
- this.computeWorldMatrix(true);
- }
- // Parent
- if (parent !== null) {
- this.parent = parent;
- }
- }
- // Methods
- /**
- * Returns the string "Mesh".
- */
- public getClassName(): string {
- return "Mesh";
- }
- /**
- * Returns a string.
- * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
- */
- public toString(fullDetails?: boolean): string {
- var ret = super.toString(fullDetails);
- ret += ", n vertices: " + this.getTotalVertices();
- ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
- if (this.animations) {
- for (var i = 0; i < this.animations.length; i++) {
- ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
- }
- }
- if (fullDetails) {
- if (this._geometry) {
- let ib = this.getIndices();
- let vb = this.getVerticesData(VertexBuffer.PositionKind);
- if (vb && ib) {
- ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
- }
- } else {
- ret += ", flat shading: UNKNOWN";
- }
- }
- return ret;
- }
- public _unBindEffect() {
- super._unBindEffect();
- for (var instance of this.instances) {
- instance._unBindEffect();
- }
- }
- /**
- * True if the mesh has some Levels Of Details (LOD).
- * Returns a boolean.
- */
- public get hasLODLevels(): boolean {
- return this._LODLevels.length > 0;
- }
- /**
- * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
- * @returns an array of {BABYLON.MeshLODLevel}
- */
- public getLODLevels(): MeshLODLevel[] {
- return this._LODLevels;
- }
- private _sortLODLevels(): void {
- this._LODLevels.sort((a, b) => {
- if (a.distance < b.distance) {
- return 1;
- }
- if (a.distance > b.distance) {
- return -1;
- }
- return 0;
- });
- }
- /**
- * Add a mesh as LOD level triggered at the given distance.
- * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
- * @param distance The distance from the center of the object to show this level
- * @param mesh The mesh to be added as LOD level (can be null)
- * @return This mesh (for chaining)
- */
- public addLODLevel(distance: number, mesh: Nullable<Mesh>): Mesh {
- if (mesh && mesh._masterMesh) {
- Tools.Warn("You cannot use a mesh as LOD level twice");
- return this;
- }
- var level = new MeshLODLevel(distance, mesh);
- this._LODLevels.push(level);
- if (mesh) {
- mesh._masterMesh = this;
- }
- this._sortLODLevels();
- return this;
- }
- /**
- * Returns the LOD level mesh at the passed distance or null if not found.
- * It is related to the method `addLODLevel(distance, mesh)`.
- * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
- * Returns an object Mesh or `null`.
- */
- public getLODLevelAtDistance(distance: number): Nullable<Mesh> {
- for (var index = 0; index < this._LODLevels.length; index++) {
- var level = this._LODLevels[index];
- if (level.distance === distance) {
- return level.mesh;
- }
- }
- return null;
- }
- /**
- * Remove a mesh from the LOD array
- * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
- * @param {Mesh} mesh The mesh to be removed.
- * @return {Mesh} This mesh (for chaining)
- */
- public removeLODLevel(mesh: Mesh): Mesh {
- for (var index = 0; index < this._LODLevels.length; index++) {
- if (this._LODLevels[index].mesh === mesh) {
- this._LODLevels.splice(index, 1);
- if (mesh) {
- mesh._masterMesh = null;
- }
- }
- }
- this._sortLODLevels();
- return this;
- }
- /**
- * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
- * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
- */
- public getLOD(camera: Camera, boundingSphere?: BoundingSphere): Nullable<AbstractMesh> {
- if (!this._LODLevels || this._LODLevels.length === 0) {
- return this;
- }
- let bSphere: BoundingSphere;
- if (boundingSphere) {
- bSphere = boundingSphere;
- } else {
- let boundingInfo = this.getBoundingInfo();
- bSphere = boundingInfo.boundingSphere;
- }
- var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
- if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
- if (this.onLODLevelSelection) {
- this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
- }
- return this;
- }
- for (var index = 0; index < this._LODLevels.length; index++) {
- var level = this._LODLevels[index];
- if (level.distance < distanceToCamera) {
- if (level.mesh) {
- level.mesh._preActivate();
- level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
- }
- if (this.onLODLevelSelection) {
- this.onLODLevelSelection(distanceToCamera, this, level.mesh);
- }
- return level.mesh;
- }
- }
- if (this.onLODLevelSelection) {
- this.onLODLevelSelection(distanceToCamera, this, this);
- }
- return this;
- }
- /**
- * Returns the mesh internal Geometry object.
- */
- public get geometry(): Nullable<Geometry> {
- return this._geometry;
- }
- /**
- * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
- */
- public getTotalVertices(): number {
- if (this._geometry === null || this._geometry === undefined) {
- return 0;
- }
- return this._geometry.getTotalVertices();
- }
- /**
- * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
- * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
- * You can force the copy with forceCopy === true
- * Returns null if the mesh has no geometry or no vertex buffer.
- * Possible `kind` values :
- * - BABYLON.VertexBuffer.PositionKind
- * - BABYLON.VertexBuffer.UVKind
- * - BABYLON.VertexBuffer.UV2Kind
- * - BABYLON.VertexBuffer.UV3Kind
- * - BABYLON.VertexBuffer.UV4Kind
- * - BABYLON.VertexBuffer.UV5Kind
- * - BABYLON.VertexBuffer.UV6Kind
- * - BABYLON.VertexBuffer.ColorKind
- * - BABYLON.VertexBuffer.MatricesIndicesKind
- * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
- * - BABYLON.VertexBuffer.MatricesWeightsKind
- * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
- */
- public getVerticesData(kind: string, copyWhenShared?: boolean, forceCopy?: boolean): Nullable<FloatArray> {
- if (!this._geometry) {
- return null;
- }
- return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
- }
- /**
- * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
- * Returns `null` if the mesh has no geometry.
- * Possible `kind` values :
- * - BABYLON.VertexBuffer.PositionKind
- * - BABYLON.VertexBuffer.UVKind
- * - BABYLON.VertexBuffer.UV2Kind
- * - BABYLON.VertexBuffer.UV3Kind
- * - BABYLON.VertexBuffer.UV4Kind
- * - BABYLON.VertexBuffer.UV5Kind
- * - BABYLON.VertexBuffer.UV6Kind
- * - BABYLON.VertexBuffer.ColorKind
- * - BABYLON.VertexBuffer.MatricesIndicesKind
- * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
- * - BABYLON.VertexBuffer.MatricesWeightsKind
- * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
- */
- public getVertexBuffer(kind: string): Nullable<VertexBuffer> {
- if (!this._geometry) {
- return null;
- }
- return this._geometry.getVertexBuffer(kind);
- }
- public isVerticesDataPresent(kind: string): boolean {
- if (!this._geometry) {
- if (this._delayInfo) {
- return this._delayInfo.indexOf(kind) !== -1;
- }
- return false;
- }
- return this._geometry.isVerticesDataPresent(kind);
- }
- /**
- * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
- * Possible `kind` values :
- * - BABYLON.VertexBuffer.PositionKind
- * - BABYLON.VertexBuffer.UVKind
- * - BABYLON.VertexBuffer.UV2Kind
- * - BABYLON.VertexBuffer.UV3Kind
- * - BABYLON.VertexBuffer.UV4Kind
- * - BABYLON.VertexBuffer.UV5Kind
- * - BABYLON.VertexBuffer.UV6Kind
- * - BABYLON.VertexBuffer.ColorKind
- * - BABYLON.VertexBuffer.MatricesIndicesKind
- * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
- * - BABYLON.VertexBuffer.MatricesWeightsKind
- * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
- */
- public isVertexBufferUpdatable(kind: string): boolean {
- if (!this._geometry) {
- if (this._delayInfo) {
- return this._delayInfo.indexOf(kind) !== -1;
- }
- return false;
- }
- return this._geometry.isVertexBufferUpdatable(kind);
- }
- /**
- * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
- * Possible `kind` values :
- * - BABYLON.VertexBuffer.PositionKind
- * - BABYLON.VertexBuffer.UVKind
- * - BABYLON.VertexBuffer.UV2Kind
- * - BABYLON.VertexBuffer.UV3Kind
- * - BABYLON.VertexBuffer.UV4Kind
- * - BABYLON.VertexBuffer.UV5Kind
- * - BABYLON.VertexBuffer.UV6Kind
- * - BABYLON.VertexBuffer.ColorKind
- * - BABYLON.VertexBuffer.MatricesIndicesKind
- * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
- * - BABYLON.VertexBuffer.MatricesWeightsKind
- * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
- */
- public getVerticesDataKinds(): string[] {
- if (!this._geometry) {
- var result = new Array<string>();
- if (this._delayInfo) {
- this._delayInfo.forEach(function (kind, index, array) {
- result.push(kind);
- });
- }
- return result;
- }
- return this._geometry.getVerticesDataKinds();
- }
- /**
- * Returns a positive integer : the total number of indices in this mesh geometry.
- * Returns zero if the mesh has no geometry.
- */
- public getTotalIndices(): number {
- if (!this._geometry) {
- return 0;
- }
- return this._geometry.getTotalIndices();
- }
- /**
- * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
- * If the parameter `copyWhenShared` is 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.
- * Returns an empty array if the mesh has no geometry.
- */
- public getIndices(copyWhenShared?: boolean): Nullable<IndicesArray> {
- if (!this._geometry) {
- return [];
- }
- return this._geometry.getIndices(copyWhenShared);
- }
- public get isBlocked(): boolean {
- return this._masterMesh !== null && this._masterMesh !== undefined;
- }
- /**
- * Determine if the current mesh is ready to be rendered
- * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
- * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
- * @returns true if all associated assets are ready (material, textures, shaders)
- */
- public isReady(completeCheck = false, forceInstanceSupport = false): boolean {
- if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
- return false;
- }
- if (!super.isReady(completeCheck)) {
- return false;
- }
- if (!this.subMeshes || this.subMeshes.length === 0) {
- return true;
- }
- if (!completeCheck) {
- return true;
- }
- let engine = this.getEngine();
- let scene = this.getScene();
- let hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
- this.computeWorldMatrix();
- let mat = this.material || scene.defaultMaterial;
- if (mat) {
- if (mat.storeEffectOnSubMeshes) {
- for (var subMesh of this.subMeshes) {
- let effectiveMaterial = subMesh.getMaterial();
- if (effectiveMaterial) {
- if (effectiveMaterial.storeEffectOnSubMeshes) {
- if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
- return false;
- }
- }
- else {
- if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
- return false;
- }
- }
- }
- }
- } else {
- if (!mat.isReady(this, hardwareInstancedRendering)) {
- return false;
- }
- }
- }
- // Shadows
- for (var light of this._lightSources) {
- let generator = light.getShadowGenerator();
- if (generator) {
- for (var subMesh of this.subMeshes) {
- if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
- return false;
- }
- }
- }
- }
- // LOD
- for (var lod of this._LODLevels) {
- if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
- return false;
- }
- }
- return true;
- }
- /**
- * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
- * This property is pertinent only for updatable parametric shapes.
- */
- public get areNormalsFrozen(): boolean {
- return this._areNormalsFrozen;
- }
- /**
- * 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.
- * Returns the Mesh.
- */
- public freezeNormals(): Mesh {
- this._areNormalsFrozen = true;
- return this;
- }
- /**
- * 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.
- * Returns the Mesh.
- */
- public unfreezeNormals(): Mesh {
- this._areNormalsFrozen = false;
- return this;
- }
- /**
- * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
- */
- public set overridenInstanceCount(count: number) {
- this._overridenInstanceCount = count;
- }
- // Methods
- public _preActivate(): Mesh {
- var sceneRenderId = this.getScene().getRenderId();
- if (this._preActivateId === sceneRenderId) {
- return this;
- }
- this._preActivateId = sceneRenderId;
- this._visibleInstances = null;
- return this;
- }
- public _preActivateForIntermediateRendering(renderId: number): Mesh {
- if (this._visibleInstances) {
- this._visibleInstances.intermediateDefaultRenderId = renderId;
- }
- return this;
- }
- public _registerInstanceForRenderId(instance: InstancedMesh, renderId: number): Mesh {
- if (!this._visibleInstances) {
- this._visibleInstances = {};
- this._visibleInstances.defaultRenderId = renderId;
- this._visibleInstances.selfDefaultRenderId = this._renderId;
- }
- if (!this._visibleInstances[renderId]) {
- this._visibleInstances[renderId] = new Array<InstancedMesh>();
- }
- this._visibleInstances[renderId].push(instance);
- return this;
- }
- /**
- * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
- * This means the mesh underlying bounding box and sphere are recomputed.
- * Returns the Mesh.
- */
- public refreshBoundingInfo(): Mesh {
- return this._refreshBoundingInfo(false);
- }
- public _refreshBoundingInfo(applySkeleton: boolean): Mesh {
- if (this._boundingInfo && this._boundingInfo.isLocked) {
- return this;
- }
- var data = this._getPositionData(applySkeleton);
- if (data) {
- var extend = Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
- this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);
- }
- if (this.subMeshes) {
- for (var index = 0; index < this.subMeshes.length; index++) {
- this.subMeshes[index].refreshBoundingInfo();
- }
- }
- this._updateBoundingInfo();
- return this;
- }
- private _getPositionData(applySkeleton: boolean): Nullable<FloatArray> {
- var data = this.getVerticesData(VertexBuffer.PositionKind);
- if (data && applySkeleton && this.skeleton) {
- data = Tools.Slice(data);
- var matricesIndicesData = this.getVerticesData(VertexBuffer.MatricesIndicesKind);
- var matricesWeightsData = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
- if (matricesWeightsData && matricesIndicesData) {
- var needExtras = this.numBoneInfluencers > 4;
- var matricesIndicesExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind) : null;
- var matricesWeightsExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind) : null;
- var skeletonMatrices = this.skeleton.getTransformMatrices(this);
- var tempVector = Tmp.Vector3[0];
- var finalMatrix = Tmp.Matrix[0];
- var tempMatrix = Tmp.Matrix[1];
- var matWeightIdx = 0;
- for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
- finalMatrix.reset();
- var inf: number;
- var weight: number;
- for (inf = 0; inf < 4; inf++) {
- weight = matricesWeightsData[matWeightIdx + inf];
- if (weight > 0) {
- Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
- finalMatrix.addToSelf(tempMatrix);
- }
- }
- if (needExtras) {
- for (inf = 0; inf < 4; inf++) {
- weight = matricesWeightsExtraData![matWeightIdx + inf];
- if (weight > 0) {
- Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData![matWeightIdx + inf] * 16), weight, tempMatrix);
- finalMatrix.addToSelf(tempMatrix);
- }
- }
- }
- Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
- tempVector.toArray(data, index);
- }
- }
- }
- return data;
- }
- public _createGlobalSubMesh(force: boolean): Nullable<SubMesh> {
- var totalVertices = this.getTotalVertices();
- if (!totalVertices || !this.getIndices()) {
- return null;
- }
- // Check if we need to recreate the submeshes
- if (this.subMeshes && this.subMeshes.length > 0) {
- let ib = this.getIndices();
- if (!ib) {
- return null;
- }
- var totalIndices = ib.length;
- let needToRecreate = false;
- if (force) {
- needToRecreate = true;
- } else {
- for (var submesh of this.subMeshes) {
- if (submesh.indexStart + submesh.indexCount >= totalIndices) {
- needToRecreate = true;
- break;
- }
- if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
- needToRecreate = true;
- break;
- }
- }
- }
- if (!needToRecreate) {
- return this.subMeshes[0];
- }
- }
- this.releaseSubMeshes();
- return new SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
- }
- public subdivide(count: number): void {
- if (count < 1) {
- return;
- }
- var totalIndices = this.getTotalIndices();
- var subdivisionSize = (totalIndices / count) | 0;
- var offset = 0;
- // Ensure that subdivisionSize is a multiple of 3
- while (subdivisionSize % 3 !== 0) {
- subdivisionSize++;
- }
- this.releaseSubMeshes();
- for (var index = 0; index < count; index++) {
- if (offset >= totalIndices) {
- break;
- }
- SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
- offset += subdivisionSize;
- }
- this.synchronizeInstances();
- }
- public setVerticesData(kind: string, data: FloatArray, updatable: boolean = false, stride?: number): Mesh {
- if (!this._geometry) {
- var vertexData = new VertexData();
- vertexData.set(data, kind);
- var scene = this.getScene();
- new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
- }
- else {
- this._geometry.setVerticesData(kind, data, updatable, stride);
- }
- return this;
- }
- public markVerticesDataAsUpdatable(kind: string, updatable = true) {
- let vb = this.getVertexBuffer(kind);
- if (!vb || vb.isUpdatable() === updatable) {
- return;
- }
- this.setVerticesData(kind, (<FloatArray>this.getVerticesData(kind)), updatable);
- }
- /**
- * Sets the mesh VertexBuffer.
- * Returns the Mesh.
- */
- public setVerticesBuffer(buffer: VertexBuffer): Mesh {
- if (!this._geometry) {
- this._geometry = Geometry.CreateGeometryForMesh(this);
- }
- this._geometry.setVerticesBuffer(buffer);
- return this;
- }
- public updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean, makeItUnique?: boolean): Mesh {
- if (!this._geometry) {
- return this;
- }
- if (!makeItUnique) {
- this._geometry.updateVerticesData(kind, data, updateExtends);
- }
- else {
- this.makeGeometryUnique();
- this.updateVerticesData(kind, data, updateExtends, false);
- }
- return this;
- }
- /**
- * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
- * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
- * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
- * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
- * Returns the Mesh.
- */
- public updateMeshPositions(positionFunction: (data: FloatArray) => void, computeNormals: boolean = true): Mesh {
- var positions = this.getVerticesData(VertexBuffer.PositionKind);
- if (!positions) {
- return this;
- }
- positionFunction(positions);
- this.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);
- if (computeNormals) {
- var indices = this.getIndices();
- var normals = this.getVerticesData(VertexBuffer.NormalKind);
- if (!normals) {
- return this;
- }
- VertexData.ComputeNormals(positions, indices, normals);
- this.updateVerticesData(VertexBuffer.NormalKind, normals, false, false);
- }
- return this;
- }
- /**
- * Creates a un-shared specific occurence of the geometry for the mesh.
- * Returns the Mesh.
- */
- public makeGeometryUnique(): Mesh {
- if (!this._geometry) {
- return this;
- }
- var oldGeometry = this._geometry;
- var geometry = this._geometry.copy(Geometry.RandomId());
- oldGeometry.releaseForMesh(this, true);
- geometry.applyToMesh(this);
- return this;
- }
- public setIndices(indices: IndicesArray, totalVertices: Nullable<number> = null, updatable: boolean = false): Mesh {
- if (!this._geometry) {
- var vertexData = new VertexData();
- vertexData.indices = indices;
- var scene = this.getScene();
- new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
- }
- else {
- this._geometry.setIndices(indices, totalVertices, updatable);
- }
- return this;
- }
- /**
- * Update the current index buffer
- * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
- * Returns the Mesh.
- */
- public updateIndices(indices: IndicesArray, offset?: number): Mesh {
- if (!this._geometry) {
- return this;
- }
- this._geometry.updateIndices(indices, offset);
- return this;
- }
- /**
- * Invert the geometry to move from a right handed system to a left handed one.
- * Returns the Mesh.
- */
- public toLeftHanded(): Mesh {
- if (!this._geometry) {
- return this;
- }
- this._geometry.toLeftHanded();
- return this;
- }
- public _bind(subMesh: SubMesh, effect: Effect, fillMode: number): Mesh {
- if (!this._geometry) {
- return this;
- }
- var engine = this.getScene().getEngine();
- // Wireframe
- var indexToBind;
- if (this._unIndexed) {
- indexToBind = null;
- } else {
- switch (fillMode) {
- case Material.PointFillMode:
- indexToBind = null;
- break;
- case Material.WireFrameFillMode:
- indexToBind = subMesh.getLinesIndexBuffer(<IndicesArray>this.getIndices(), engine);
- break;
- default:
- case Material.TriangleFillMode:
- indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
- break;
- }
- }
- // VBOs
- this._geometry._bind(effect, indexToBind);
- return this;
- }
- public _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number, alternate = false): Mesh {
- if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
- return this;
- }
- this.onBeforeDrawObservable.notifyObservers(this);
- let scene = this.getScene();
- let engine = scene.getEngine();
- if (this._unIndexed || fillMode == Material.PointFillMode) {
- // or triangles as points
- engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
- } else if (fillMode == Material.WireFrameFillMode) {
- // Triangles as wireframe
- engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
- } else {
- engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
- }
- if (scene._isAlternateRenderingEnabled && !alternate) {
- let effect = subMesh.effect || this._effectiveMaterial.getEffect();
- if (!effect || !scene.activeCamera) {
- return this;
- }
- scene._switchToAlternateCameraConfiguration(true);
- this._effectiveMaterial.bindView(effect);
- this._effectiveMaterial.bindViewProjection(effect);
- engine.setViewport(scene.activeCamera._alternateCamera.viewport);
- this._draw(subMesh, fillMode, instancesCount, true);
- engine.setViewport(scene.activeCamera.viewport);
- scene._switchToAlternateCameraConfiguration(false);
- this._effectiveMaterial.bindView(effect);
- this._effectiveMaterial.bindViewProjection(effect);
- }
- return this;
- }
- /**
- * Registers for this mesh a javascript function called just before the rendering process.
- * This function is passed the current mesh.
- * Return the Mesh.
- */
- public registerBeforeRender(func: (mesh: AbstractMesh) => void): Mesh {
- this.onBeforeRenderObservable.add(func);
- return this;
- }
- /**
- * Disposes a previously registered javascript function called before the rendering.
- * This function is passed the current mesh.
- * Returns the Mesh.
- */
- public unregisterBeforeRender(func: (mesh: AbstractMesh) => void): Mesh {
- this.onBeforeRenderObservable.removeCallback(func);
- return this;
- }
- /**
- * Registers for this mesh a javascript function called just after the rendering is complete.
- * This function is passed the current mesh.
- * Returns the Mesh.
- */
- public registerAfterRender(func: (mesh: AbstractMesh) => void): Mesh {
- this.onAfterRenderObservable.add(func);
- return this;
- }
- /**
- * Disposes a previously registered javascript function called after the rendering.
- * This function is passed the current mesh.
- * Return the Mesh.
- */
- public unregisterAfterRender(func: (mesh: AbstractMesh) => void): Mesh {
- this.onAfterRenderObservable.removeCallback(func);
- return this;
- }
- public _getInstancesRenderList(subMeshId: number): _InstancesBatch {
- var scene = this.getScene();
- this._batchCache.mustReturn = false;
- this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
- this._batchCache.visibleInstances[subMeshId] = null;
- if (this._visibleInstances) {
- var currentRenderId = scene.getRenderId();
- var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
- this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
- var selfRenderId = this._renderId;
- if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
- this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
- currentRenderId = Math.max(defaultRenderId, currentRenderId);
- selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
- }
- let visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
- if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
- if (this._renderIdForInstances[subMeshId] === currentRenderId) {
- this._batchCache.mustReturn = true;
- return this._batchCache;
- }
- if (currentRenderId !== selfRenderId) {
- this._batchCache.renderSelf[subMeshId] = false;
- }
- }
- this._renderIdForInstances[subMeshId] = currentRenderId;
- }
- return this._batchCache;
- }
- public _renderWithInstances(subMesh: SubMesh, fillMode: number, batch: _InstancesBatch, effect: Effect, engine: Engine): Mesh {
- var visibleInstances = batch.visibleInstances[subMesh._id];
- if (!visibleInstances) {
- return this;
- }
- var matricesCount = visibleInstances.length + 1;
- var bufferSize = matricesCount * 16 * 4;
- var currentInstancesBufferSize = this._instancesBufferSize;
- var instancesBuffer = this._instancesBuffer;
- while (this._instancesBufferSize < bufferSize) {
- this._instancesBufferSize *= 2;
- }
- if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
- this._instancesData = new Float32Array(this._instancesBufferSize / 4);
- }
- var offset = 0;
- var instancesCount = 0;
- var world = this.getWorldMatrix();
- if (batch.renderSelf[subMesh._id]) {
- world.copyToArray(this._instancesData, offset);
- offset += 16;
- instancesCount++;
- }
- if (visibleInstances) {
- for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
- var instance = visibleInstances[instanceIndex];
- instance.getWorldMatrix().copyToArray(this._instancesData, offset);
- offset += 16;
- instancesCount++;
- }
- }
- if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
- if (instancesBuffer) {
- instancesBuffer.dispose();
- }
- instancesBuffer = new Buffer(engine, this._instancesData, true, 16, false, true);
- this._instancesBuffer = instancesBuffer;
- this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
- this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
- this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
- this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
- } else {
- instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
- }
- this._bind(subMesh, effect, fillMode);
- this._draw(subMesh, fillMode, instancesCount);
- engine.unbindInstanceAttributes();
- return this;
- }
- public _processRendering(subMesh: SubMesh, effect: Effect, fillMode: number, batch: _InstancesBatch, hardwareInstancedRendering: boolean,
- onBeforeDraw: (isInstance: boolean, world: Matrix, effectiveMaterial?: Material) => void, effectiveMaterial?: Material): Mesh {
- var scene = this.getScene();
- var engine = scene.getEngine();
- if (hardwareInstancedRendering) {
- this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
- } else {
- if (batch.renderSelf[subMesh._id]) {
- // Draw
- if (onBeforeDraw) {
- onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
- }
- this._draw(subMesh, fillMode, this._overridenInstanceCount);
- }
- let visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
- if (visibleInstancesForSubMesh) {
- for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
- var instance = visibleInstancesForSubMesh[instanceIndex];
- // World
- var world = instance.getWorldMatrix();
- if (onBeforeDraw) {
- onBeforeDraw(true, world, effectiveMaterial);
- }
- // Draw
- this._draw(subMesh, fillMode);
- }
- }
- }
- return this;
- }
- /**
- * 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
- * @param subMesh defines the subMesh to render
- * @param enableAlphaMode defines if alpha mode can be changed
- * @returns the current mesh
- */
- public render(subMesh: SubMesh, enableAlphaMode: boolean): Mesh {
- this._checkOcclusionQuery();
- if (this._isOccluded) {
- return this;
- }
- var scene = this.getScene();
- // Managing instances
- var batch = this._getInstancesRenderList(subMesh._id);
- if (batch.mustReturn) {
- return this;
- }
- // Checking geometry state
- if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
- return this;
- }
- this.onBeforeRenderObservable.notifyObservers(this);
- var engine = scene.getEngine();
- var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
- // Material
- let material = subMesh.getMaterial();
- if (!material) {
- return this;
- }
- this._effectiveMaterial = material;
- if (this._effectiveMaterial.storeEffectOnSubMeshes) {
- if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
- return this;
- }
- } else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
- return this;
- }
- // Alpha mode
- if (enableAlphaMode) {
- engine.setAlphaMode(this._effectiveMaterial.alphaMode);
- }
- // Outline - step 1
- var savedDepthWrite = engine.getDepthWrite();
- if (this.renderOutline) {
- engine.setDepthWrite(false);
- scene.getOutlineRenderer().render(subMesh, batch);
- engine.setDepthWrite(savedDepthWrite);
- }
- var effect: Nullable<Effect>;
- if (this._effectiveMaterial.storeEffectOnSubMeshes) {
- effect = subMesh.effect;
- } else {
- effect = this._effectiveMaterial.getEffect();
- }
- if (!effect) {
- return this;
- }
- var sideOrientation = this.overrideMaterialSideOrientation;
- if (sideOrientation == null) {
- sideOrientation = this._effectiveMaterial.sideOrientation;
- if (this._getWorldMatrixDeterminant() < 0) {
- sideOrientation = (sideOrientation === Material.ClockWiseSideOrientation ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation);
- }
- }
- var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
- if (this._effectiveMaterial.forceDepthWrite) {
- engine.setDepthWrite(true);
- }
- // Bind
- var fillMode = scene.forcePointsCloud ? Material.PointFillMode : (scene.forceWireframe ? Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
- if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
- this._bind(subMesh, effect, fillMode);
- }
- var world = this.getWorldMatrix();
- if (this._effectiveMaterial.storeEffectOnSubMeshes) {
- this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
- } else {
- this._effectiveMaterial.bind(world, this);
- }
- if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
- engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
- this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
- engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
- }
- // Draw
- this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
- // Unbind
- this._effectiveMaterial.unbind();
- // Outline - step 2
- if (this.renderOutline && savedDepthWrite) {
- engine.setDepthWrite(true);
- engine.setColorWrite(false);
- scene.getOutlineRenderer().render(subMesh, batch);
- engine.setColorWrite(true);
- }
- // Overlay
- if (this.renderOverlay) {
- var currentMode = engine.getAlphaMode();
- engine.setAlphaMode(Engine.ALPHA_COMBINE);
- scene.getOutlineRenderer().render(subMesh, batch, true);
- engine.setAlphaMode(currentMode);
- }
- this.onAfterRenderObservable.notifyObservers(this);
- return this;
- }
- private _onBeforeDraw(isInstance: boolean, world: Matrix, effectiveMaterial?: Material): void {
- if (isInstance && effectiveMaterial) {
- effectiveMaterial.bindOnlyWorldMatrix(world);
- }
- }
- /**
- * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
- */
- public getEmittedParticleSystems(): IParticleSystem[] {
- var results = new Array<IParticleSystem>();
- for (var index = 0; index < this.getScene().particleSystems.length; index++) {
- var particleSystem = this.getScene().particleSystems[index];
- if (particleSystem.emitter === this) {
- results.push(particleSystem);
- }
- }
- return results;
- }
- /**
- * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
- */
- public getHierarchyEmittedParticleSystems(): IParticleSystem[] {
- var results = new Array<IParticleSystem>();
- var descendants = this.getDescendants();
- descendants.push(this);
- for (var index = 0; index < this.getScene().particleSystems.length; index++) {
- var particleSystem = this.getScene().particleSystems[index];
- let emitter: any = particleSystem.emitter;
- if (emitter.position && descendants.indexOf(emitter) !== -1) {
- results.push(particleSystem);
- }
- }
- return results;
- }
-
- /**
- * Normalize matrix weights so that all vertices have a total weight set to 1
- */
- public cleanMatrixWeights(): void {
- const epsilon: number = 1e-3;
- let noInfluenceBoneIndex = 0.0;
- if (this.skeleton) {
- noInfluenceBoneIndex = this.skeleton.bones.length;
- } else {
- return;
- }
- let matricesIndices = (<FloatArray>this.getVerticesData(VertexBuffer.MatricesIndicesKind));
- let matricesIndicesExtra = (<FloatArray>this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind));
- let matricesWeights = (<FloatArray>this.getVerticesData(VertexBuffer.MatricesWeightsKind));
- let matricesWeightsExtra = (<FloatArray>this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind));
- let influencers = this.numBoneInfluencers;
- let size = matricesWeights.length;
- for (var i = 0; i < size; i += 4) {
- let weight = 0.0;
- let firstZeroWeight = -1;
- for (var j = 0; j < 4; j++) {
- let w = matricesWeights[i + j];
- weight += w;
- if (w < epsilon && firstZeroWeight < 0) {
- firstZeroWeight = j;
- }
- }
- if (matricesWeightsExtra) {
- for (var j = 0; j < 4; j++) {
- let w = matricesWeightsExtra[i + j];
- weight += w;
- if (w < epsilon && firstZeroWeight < 0) {
- firstZeroWeight = j + 4;
- }
- }
- }
- if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
- firstZeroWeight = influencers - 1;
- }
- if (weight > epsilon) {
- let mweight = 1.0 / weight;
- for (var j = 0; j < 4; j++) {
- matricesWeights[i + j] *= mweight;
- }
- if (matricesWeightsExtra) {
- for (var j = 0; j < 4; j++) {
- matricesWeightsExtra[i + j] *= mweight;
- }
- }
- } else {
- if (firstZeroWeight >= 4) {
- matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
- matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
- } else {
- matricesWeights[i + firstZeroWeight] = 1.0 - weight;
- matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
- }
- }
- }
- this.setVerticesData(VertexBuffer.MatricesIndicesKind, matricesIndices);
- if (matricesIndicesExtra) {
- this.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
- }
- this.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeights);
- if (matricesWeightsExtra) {
- this.setVerticesData(VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
- }
- }
- public _checkDelayState(): Mesh {
- var scene = this.getScene();
- if (this._geometry) {
- this._geometry.load(scene);
- }
- else if (this.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
- this.delayLoadState = Engine.DELAYLOADSTATE_LOADING;
- this._queueLoad(scene);
- }
- return this;
- }
- private _queueLoad(scene: Scene): Mesh {
- scene._addPendingData(this);
- var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
- Tools.LoadFile(this.delayLoadingFile, data => {
- if (data instanceof ArrayBuffer) {
- this._delayLoadingFunction(data, this);
- }
- else {
- this._delayLoadingFunction(JSON.parse(data), this);
- }
- this.instances.forEach(instance => {
- instance._syncSubMeshes();
- });
- this.delayLoadState = Engine.DELAYLOADSTATE_LOADED;
- scene._removePendingData(this);
- }, () => { }, scene.database, getBinaryData);
- return this;
- }
- /**
- * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
- */
- public isInFrustum(frustumPlanes: Plane[]): boolean {
- if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
- return false;
- }
- if (!super.isInFrustum(frustumPlanes)) {
- return false;
- }
- this._checkDelayState();
- return true;
- }
- /**
- * Sets the mesh material by the material or multiMaterial `id` property.
- * The material `id` is a string identifying the material or the multiMaterial.
- * This method returns the Mesh.
- */
- public setMaterialByID(id: string): Mesh {
- var materials = this.getScene().materials;
- var index: number;
- for (index = materials.length - 1; index > -1; index--) {
- if (materials[index].id === id) {
- this.material = materials[index];
- return this;
- }
- }
- // Multi
- var multiMaterials = this.getScene().multiMaterials;
- for (index = multiMaterials.length - 1; index > -1; index--) {
- if (multiMaterials[index].id === id) {
- this.material = multiMaterials[index];
- return this;
- }
- }
- return this;
- }
- /**
- * Returns as a new array populated with the mesh material and/or skeleton, if any.
- */
- public getAnimatables(): IAnimatable[] {
- var results = new Array<IAnimatable>();
- if (this.material) {
- results.push(this.material);
- }
- if (this.skeleton) {
- results.push(this.skeleton);
- }
- return results;
- }
- /**
- * Modifies the mesh geometry according to the passed transformation matrix.
- * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
- * The mesh normals are modified accordingly the same transformation.
- * tuto : http://doc.babylonjs.com/resources/baking_transformations
- * Note that, under the hood, this method sets a new VertexBuffer each call.
- * Returns the Mesh.
- */
- public bakeTransformIntoVertices(transform: Matrix): Mesh {
- // Position
- if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
- return this;
- }
- var submeshes = this.subMeshes.splice(0);
- this._resetPointsArrayCache();
- var data = <FloatArray>this.getVerticesData(VertexBuffer.PositionKind);
- var temp = new Array<number>();
- var index: number;
- for (index = 0; index < data.length; index += 3) {
- Vector3.TransformCoordinates(Vector3.FromArray(data, index), transform).toArray(temp, index);
- }
- this.setVerticesData(VertexBuffer.PositionKind, temp, (<VertexBuffer>this.getVertexBuffer(VertexBuffer.PositionKind)).isUpdatable());
- // Normals
- if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
- return this;
- }
- data = <FloatArray>this.getVerticesData(VertexBuffer.NormalKind);
- temp = [];
- for (index = 0; index < data.length; index += 3) {
- Vector3.TransformNormal(Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
- }
- this.setVerticesData(VertexBuffer.NormalKind, temp, (<VertexBuffer>this.getVertexBuffer(VertexBuffer.NormalKind)).isUpdatable());
- // flip faces?
- if (transform.m[0] * transform.m[5] * transform.m[10] < 0) { this.flipFaces(); }
- // Restore submeshes
- this.releaseSubMeshes();
- this.subMeshes = submeshes;
- return this;
- }
- /**
- * Modifies the mesh geometry according to its own current World Matrix.
- * The mesh World Matrix is then reset.
- * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
- * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
- * Note that, under the hood, this method sets a new VertexBuffer each call.
- * Returns the Mesh.
- */
- public bakeCurrentTransformIntoVertices(): Mesh {
- this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
- this.scaling.copyFromFloats(1, 1, 1);
- this.position.copyFromFloats(0, 0, 0);
- this.rotation.copyFromFloats(0, 0, 0);
- //only if quaternion is already set
- if (this.rotationQuaternion) {
- this.rotationQuaternion = Quaternion.Identity();
- }
- this._worldMatrix = Matrix.Identity();
- return this;
- }
- // Cache
- public get _positions(): Nullable<Vector3[]> {
- if (this._geometry) {
- return this._geometry._positions;
- }
- return null;
- }
- public _resetPointsArrayCache(): Mesh {
- if (this._geometry) {
- this._geometry._resetPointsArrayCache();
- }
- return this;
- }
- public _generatePointsArray(): boolean {
- if (this._geometry) {
- return this._geometry._generatePointsArray();
- }
- return false;
- }
- /**
- * Returns a new Mesh object generated from the current mesh properties.
- * This method must not get confused with createInstance().
- * The parameter `name` is a string, the name given to the new mesh.
- * The optional parameter `newParent` can be any Node object (default `null`).
- * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
- * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
- */
- public clone(name: string, newParent?: Node, doNotCloneChildren?: boolean, clonePhysicsImpostor: boolean = true): Mesh {
- return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
- }
- /**
- * Releases resources associated with this mesh.
- * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
- * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
- */
- public dispose(doNotRecurse?: boolean, disposeMaterialAndTextures = false): void {
- this.morphTargetManager = null;
- if (this._geometry) {
- this._geometry.releaseForMesh(this, true);
- }
- // Sources
- var meshes = this.getScene().meshes;
- meshes.forEach((abstractMesh: AbstractMesh) => {
- let mesh = abstractMesh as Mesh;
- if (mesh._source && mesh._source === this) {
- mesh._source = null;
- }
- });
- this._source = null;
- // Instances
- if (this._instancesBuffer) {
- this._instancesBuffer.dispose();
- this._instancesBuffer = null;
- }
- while (this.instances.length) {
- this.instances[0].dispose();
- }
- super.dispose(doNotRecurse, disposeMaterialAndTextures);
- }
- /**
- * Modifies the mesh geometry according to a displacement map.
- * 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.
- * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
- * This method returns nothing.
- * The parameter `url` is a string, the URL from the image file is to be downloaded.
- * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
- * The parameter `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.
- * The parameter `uvOffset` is an optional vector2 used to offset UV.
- * The parameter `uvScale` is an optional vector2 used to scale UV.
- *
- * Returns the Mesh.
- */
- public applyDisplacementMap(url: string, minHeight: number, maxHeight: number, onSuccess?: (mesh: Mesh) => void, uvOffset?: Vector2, uvScale?: Vector2): Mesh {
- var scene = this.getScene();
- var onload = (img: HTMLImageElement) => {
- // Getting height map data
- var canvas = document.createElement("canvas");
- var context = <CanvasRenderingContext2D>canvas.getContext("2d");
- var heightMapWidth = img.width;
- var heightMapHeight = img.height;
- canvas.width = heightMapWidth;
- canvas.height = heightMapHeight;
- context.drawImage(img, 0, 0);
- // Create VertexData from map data
- //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
- var buffer = <Uint8Array>(<any>context.getImageData(0, 0, heightMapWidth, heightMapHeight).data);
- this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
- //execute success callback, if set
- if (onSuccess) {
- onSuccess(this);
- }
- };
- Tools.LoadImage(url, onload, () => { }, scene.database);
- return this;
- }
- /**
- * Modifies the mesh geometry according to a displacementMap buffer.
- * 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.
- * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
- * This method returns nothing.
- * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
- * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
- * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
- * The parameter `uvOffset` is an optional vector2 used to offset UV.
- * The parameter `uvScale` is an optional vector2 used to scale UV.
- *
- * Returns the Mesh.
- */
- public applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number, uvOffset?: Vector2, uvScale?: Vector2): Mesh {
- if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)
- || !this.isVerticesDataPresent(VertexBuffer.NormalKind)
- || !this.isVerticesDataPresent(VertexBuffer.UVKind)) {
- Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
- return this;
- }
- var positions = <FloatArray>this.getVerticesData(VertexBuffer.PositionKind);
- var normals = <FloatArray>this.getVerticesData(VertexBuffer.NormalKind);
- var uvs = <number[]>this.getVerticesData(VertexBuffer.UVKind);
- var position = Vector3.Zero();
- var normal = Vector3.Zero();
- var uv = Vector2.Zero();
- uvOffset = uvOffset || Vector2.Zero();
- uvScale = uvScale || new Vector2(1, 1);
- for (var index = 0; index < positions.length; index += 3) {
- Vector3.FromArrayToRef(positions, index, position);
- Vector3.FromArrayToRef(normals, index, normal);
- Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
- // Compute height
- var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
- var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
- var pos = (u + v * heightMapWidth) * 4;
- var r = buffer[pos] / 255.0;
- var g = buffer[pos + 1] / 255.0;
- var b = buffer[pos + 2] / 255.0;
- var gradient = r * 0.3 + g * 0.59 + b * 0.11;
- normal.normalize();
- normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
- position = position.add(normal);
- position.toArray(positions, index);
- }
- VertexData.ComputeNormals(positions, this.getIndices(), normals);
- this.updateVerticesData(VertexBuffer.PositionKind, positions);
- this.updateVerticesData(VertexBuffer.NormalKind, normals);
- return this;
- }
- /**
- * Modify the mesh to get a flat shading rendering.
- * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
- * This method returns the Mesh.
- * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
- */
- public convertToFlatShadedMesh(): Mesh {
- /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
- /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
- var kinds = this.getVerticesDataKinds();
- var vbs: { [key: string]: VertexBuffer } = {};
- var data: { [key: string]: FloatArray } = {};
- var newdata: { [key: string]: Array<number> } = {};
- var updatableNormals = false;
- var kindIndex: number;
- var kind: string;
- for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- kind = kinds[kindIndex];
- var vertexBuffer = <VertexBuffer>this.getVertexBuffer(kind);
- if (kind === VertexBuffer.NormalKind) {
- updatableNormals = vertexBuffer.isUpdatable();
- kinds.splice(kindIndex, 1);
- kindIndex--;
- continue;
- }
- vbs[kind] = vertexBuffer;
- data[kind] = <FloatArray>vbs[kind].getData();
- newdata[kind] = [];
- }
- // Save previous submeshes
- var previousSubmeshes = this.subMeshes.slice(0);
- var indices = <IndicesArray>this.getIndices();
- var totalIndices = this.getTotalIndices();
- // Generating unique vertices per face
- var index: number;
- for (index = 0; index < totalIndices; index++) {
- var vertexIndex = indices[index];
- for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- kind = kinds[kindIndex];
- var stride = vbs[kind].getStrideSize();
- for (var offset = 0; offset < stride; offset++) {
- newdata[kind].push(data[kind][vertexIndex * stride + offset]);
- }
- }
- }
- // Updating faces & normal
- var normals = [];
- var positions = newdata[VertexBuffer.PositionKind];
- for (index = 0; index < totalIndices; index += 3) {
- indices[index] = index;
- indices[index + 1] = index + 1;
- indices[index + 2] = index + 2;
- var p1 = Vector3.FromArray(positions, index * 3);
- var p2 = Vector3.FromArray(positions, (index + 1) * 3);
- var p3 = Vector3.FromArray(positions, (index + 2) * 3);
- var p1p2 = p1.subtract(p2);
- var p3p2 = p3.subtract(p2);
- var normal = Vector3.Normalize(Vector3.Cross(p1p2, p3p2));
- // Store same normals for every vertex
- for (var localIndex = 0; localIndex < 3; localIndex++) {
- normals.push(normal.x);
- normals.push(normal.y);
- normals.push(normal.z);
- }
- }
- this.setIndices(indices);
- this.setVerticesData(VertexBuffer.NormalKind, normals, updatableNormals);
- // Updating vertex buffers
- for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- kind = kinds[kindIndex];
- this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
- }
- // Updating submeshes
- this.releaseSubMeshes();
- for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
- var previousOne = previousSubmeshes[submeshIndex];
- SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
- }
- this.synchronizeInstances();
- return this;
- }
- /**
- * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
- * In other words, more vertices, no more indices and a single bigger VBO.
- * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
- * Returns the Mesh.
- */
- public convertToUnIndexedMesh(): Mesh {
- /// <summary>Remove indices by unfolding faces into buffers</summary>
- /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
- var kinds = this.getVerticesDataKinds();
- var vbs: { [key: string]: VertexBuffer } = {};
- var data: { [key: string]: FloatArray } = {};
- var newdata: { [key: string]: Array<number> } = {};
- var kindIndex: number;
- var kind: string;
- for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- kind = kinds[kindIndex];
- var vertexBuffer = <VertexBuffer>this.getVertexBuffer(kind);
- vbs[kind] = vertexBuffer;
- data[kind] = <FloatArray>vbs[kind].getData();
- newdata[kind] = [];
- }
- // Save previous submeshes
- var previousSubmeshes = this.subMeshes.slice(0);
- var indices = <IndicesArray>this.getIndices();
- var totalIndices = this.getTotalIndices();
- // Generating unique vertices per face
- var index: number;
- for (index = 0; index < totalIndices; index++) {
- var vertexIndex = indices[index];
- for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- kind = kinds[kindIndex];
- var stride = vbs[kind].getStrideSize();
- for (var offset = 0; offset < stride; offset++) {
- newdata[kind].push(data[kind][vertexIndex * stride + offset]);
- }
- }
- }
- // Updating indices
- for (index = 0; index < totalIndices; index += 3) {
- indices[index] = index;
- indices[index + 1] = index + 1;
- indices[index + 2] = index + 2;
- }
- this.setIndices(indices);
- // Updating vertex buffers
- for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- kind = kinds[kindIndex];
- this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
- }
- // Updating submeshes
- this.releaseSubMeshes();
- for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
- var previousOne = previousSubmeshes[submeshIndex];
- SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
- }
- this._unIndexed = true;
- this.synchronizeInstances();
- return this;
- }
- /**
- * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
- * This method returns the Mesh.
- * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
- */
- public flipFaces(flipNormals: boolean = false): Mesh {
- var vertex_data = VertexData.ExtractFromMesh(this);
- var i: number;
- if (flipNormals && this.isVerticesDataPresent(VertexBuffer.NormalKind) && vertex_data.normals) {
- for (i = 0; i < vertex_data.normals.length; i++) {
- vertex_data.normals[i] *= -1;
- }
- }
- if (vertex_data.indices) {
- var temp;
- for (i = 0; i < vertex_data.indices.length; i += 3) {
- // reassign indices
- temp = vertex_data.indices[i + 1];
- vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
- vertex_data.indices[i + 2] = temp;
- }
- }
- vertex_data.applyToMesh(this);
- return this;
- }
- // Instances
- /**
- * Creates a new InstancedMesh object from the mesh model.
- * An instance shares the same properties and the same material than its model.
- * Only these properties of each instance can then be set individually :
- * - position
- * - rotation
- * - rotationQuaternion
- * - setPivotMatrix
- * - scaling
- * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
- * Warning : this method is not supported for Line mesh and LineSystem
- */
- public createInstance(name: string): InstancedMesh {
- return new InstancedMesh(name, this);
- }
- /**
- * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
- * After this call, all the mesh instances have the same submeshes than the current mesh.
- * This method returns the Mesh.
- */
- public synchronizeInstances(): Mesh {
- for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
- var instance = this.instances[instanceIndex];
- instance._syncSubMeshes();
- }
- return this;
- }
- /**
- * Simplify the mesh according to the given array of settings.
- * Function will return immediately and will simplify async. It returns the Mesh.
- * @param settings a collection of simplification settings.
- * @param parallelProcessing should all levels calculate parallel or one after the other.
- * @param type the type of simplification to run.
- * @param successCallback optional success callback to be called after the simplification finished processing all settings.
- */
- public simplify(settings: Array<ISimplificationSettings>, parallelProcessing: boolean = true, simplificationType: SimplificationType = SimplificationType.QUADRATIC, successCallback?: (mesh?: Mesh, submeshIndex?: number) => void): Mesh {
- this.getScene().simplificationQueue.addTask({
- settings: settings,
- parallelProcessing: parallelProcessing,
- mesh: this,
- simplificationType: simplificationType,
- successCallback: successCallback
- });
- return this;
- }
- /**
- * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
- * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
- * This should be used together with the simplification to avoid disappearing triangles.
- * Returns the Mesh.
- * @param successCallback an optional success callback to be called after the optimization finished.
- */
- public optimizeIndices(successCallback?: (mesh?: Mesh) => void): Mesh {
- var indices = <IndicesArray>this.getIndices();
- var positions = this.getVerticesData(VertexBuffer.PositionKind);
- if (!positions || !indices) {
- return this;
- }
- var vectorPositions = new Array<Vector3>();
- for (var pos = 0; pos < positions.length; pos = pos + 3) {
- vectorPositions.push(Vector3.FromArray(positions, pos));
- }
- var dupes = new Array<number>();
- AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, (iteration) => {
- var realPos = vectorPositions.length - 1 - iteration;
- var testedPosition = vectorPositions[realPos];
- for (var j = 0; j < realPos; ++j) {
- var againstPosition = vectorPositions[j];
- if (testedPosition.equals(againstPosition)) {
- dupes[realPos] = j;
- break;
- }
- }
- }, () => {
- for (var i = 0; i < indices.length; ++i) {
- indices[i] = dupes[indices[i]] || indices[i];
- }
- //indices are now reordered
- var originalSubMeshes = this.subMeshes.slice(0);
- this.setIndices(indices);
- this.subMeshes = originalSubMeshes;
- if (successCallback) {
- successCallback(this);
- }
- });
- return this;
- }
- public serialize(serializationObject: any): void {
- serializationObject.name = this.name;
- serializationObject.id = this.id;
- serializationObject.type = this.getClassName();
- if (Tags && Tags.HasTags(this)) {
- serializationObject.tags = Tags.GetTags(this);
- }
- serializationObject.position = this.position.asArray();
- if (this.rotationQuaternion) {
- serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
- } else if (this.rotation) {
- serializationObject.rotation = this.rotation.asArray();
- }
- serializationObject.scaling = this.scaling.asArray();
- serializationObject.localMatrix = this.getPivotMatrix().asArray();
- serializationObject.isEnabled = this.isEnabled(false);
- serializationObject.isVisible = this.isVisible;
- serializationObject.infiniteDistance = this.infiniteDistance;
- serializationObject.pickable = this.isPickable;
- serializationObject.receiveShadows = this.receiveShadows;
- serializationObject.billboardMode = this.billboardMode;
- serializationObject.visibility = this.visibility;
- serializationObject.checkCollisions = this.checkCollisions;
- serializationObject.isBlocker = this.isBlocker;
- // Parent
- if (this.parent) {
- serializationObject.parentId = this.parent.id;
- }
- // Geometry
- serializationObject.isUnIndexed = this.isUnIndexed;
- var geometry = this._geometry;
- if (geometry) {
- var geometryId = geometry.id;
- serializationObject.geometryId = geometryId;
- // SubMeshes
- serializationObject.subMeshes = [];
- for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
- var subMesh = this.subMeshes[subIndex];
- serializationObject.subMeshes.push({
- materialIndex: subMesh.materialIndex,
- verticesStart: subMesh.verticesStart,
- verticesCount: subMesh.verticesCount,
- indexStart: subMesh.indexStart,
- indexCount: subMesh.indexCount
- });
- }
- }
- // Material
- if (this.material) {
- serializationObject.materialId = this.material.id;
- } else {
- this.material = null;
- }
- // Morph targets
- if (this.morphTargetManager) {
- serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
- }
- // Skeleton
- if (this.skeleton) {
- serializationObject.skeletonId = this.skeleton.id;
- }
- // Physics
- //TODO implement correct serialization for physics impostors.
- let impostor = this.getPhysicsImpostor();
- if (impostor) {
- serializationObject.physicsMass = impostor.getParam("mass");
- serializationObject.physicsFriction = impostor.getParam("friction");
- serializationObject.physicsRestitution = impostor.getParam("mass");
- serializationObject.physicsImpostor = impostor.type;
- }
- // Metadata
- if (this.metadata) {
- serializationObject.metadata = this.metadata;
- }
- // Instances
- serializationObject.instances = [];
- for (var index = 0; index < this.instances.length; index++) {
- var instance = this.instances[index];
- var serializationInstance: any = {
- name: instance.name,
- id: instance.id,
- position: instance.position.asArray(),
- scaling: instance.scaling.asArray()
- };
- if (instance.rotationQuaternion) {
- serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
- } else if (instance.rotation) {
- serializationInstance.rotation = instance.rotation.asArray();
- }
- serializationObject.instances.push(serializationInstance);
- // Animations
- Animation.AppendSerializedAnimations(instance, serializationInstance);
- serializationInstance.ranges = instance.serializeAnimationRanges();
- }
- //
- // Animations
- Animation.AppendSerializedAnimations(this, serializationObject);
- serializationObject.ranges = this.serializeAnimationRanges();
- // Layer mask
- serializationObject.layerMask = this.layerMask;
- // Alpha
- serializationObject.alphaIndex = this.alphaIndex;
- serializationObject.hasVertexAlpha = this.hasVertexAlpha;
- // Overlay
- serializationObject.overlayAlpha = this.overlayAlpha;
- serializationObject.overlayColor = this.overlayColor.asArray();
- serializationObject.renderOverlay = this.renderOverlay;
- // Fog
- serializationObject.applyFog = this.applyFog;
- // Action Manager
- if (this.actionManager) {
- serializationObject.actions = this.actionManager.serialize(this.name);
- }
- }
- public _syncGeometryWithMorphTargetManager() {
- if (!this.geometry) {
- return;
- }
- this._markSubMeshesAsAttributesDirty();
- let morphTargetManager = this._morphTargetManager;
- if (morphTargetManager && morphTargetManager.vertexCount) {
- if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
- Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
- this.morphTargetManager = null;
- return;
- }
- for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
- var morphTarget = morphTargetManager.getActiveTarget(index);
- const positions = morphTarget.getPositions();
- if (!positions) {
- Tools.Error("Invalid morph target. Target must have positions.");
- return;
- }
- this.geometry.setVerticesData(VertexBuffer.PositionKind + index, positions, false, 3);
- const normals = morphTarget.getNormals();
- if (normals) {
- this.geometry.setVerticesData(VertexBuffer.NormalKind + index, normals, false, 3);
- }
- const tangents = morphTarget.getTangents();
- if (tangents) {
- this.geometry.setVerticesData(VertexBuffer.TangentKind + index, tangents, false, 3);
- }
- }
- } else {
- var index = 0;
- // Positions
- while (this.geometry.isVerticesDataPresent(VertexBuffer.PositionKind + index)) {
- this.geometry.removeVerticesData(VertexBuffer.PositionKind + index);
- if (this.geometry.isVerticesDataPresent(VertexBuffer.NormalKind + index)) {
- this.geometry.removeVerticesData(VertexBuffer.NormalKind + index);
- }
- if (this.geometry.isVerticesDataPresent(VertexBuffer.TangentKind + index)) {
- this.geometry.removeVerticesData(VertexBuffer.TangentKind + index);
- }
- index++;
- }
- }
- }
- // Statics
- /**
- * Returns a new Mesh object parsed from the source provided.
- * The parameter `parsedMesh` is the source.
- * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
- */
- public static Parse(parsedMesh: any, scene: Scene, rootUrl: string): Mesh {
- var mesh: Mesh;
- if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
- mesh = GroundMesh.Parse(parsedMesh, scene);
- } else {
- mesh = new Mesh(parsedMesh.name, scene);
- }
- mesh.id = parsedMesh.id;
- if (Tags) {
- Tags.AddTagsTo(mesh, parsedMesh.tags);
- }
- mesh.position = Vector3.FromArray(parsedMesh.position);
- if (parsedMesh.metadata !== undefined) {
- mesh.metadata = parsedMesh.metadata;
- }
- if (parsedMesh.rotationQuaternion) {
- mesh.rotationQuaternion = Quaternion.FromArray(parsedMesh.rotationQuaternion);
- } else if (parsedMesh.rotation) {
- mesh.rotation = Vector3.FromArray(parsedMesh.rotation);
- }
- mesh.scaling = Vector3.FromArray(parsedMesh.scaling);
- if (parsedMesh.localMatrix) {
- mesh.setPreTransformMatrix(Matrix.FromArray(parsedMesh.localMatrix));
- } else if (parsedMesh.pivotMatrix) {
- mesh.setPivotMatrix(Matrix.FromArray(parsedMesh.pivotMatrix));
- }
- mesh.setEnabled(parsedMesh.isEnabled);
- mesh.isVisible = parsedMesh.isVisible;
- mesh.infiniteDistance = parsedMesh.infiniteDistance;
- mesh.showBoundingBox = parsedMesh.showBoundingBox;
- mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
- if (parsedMesh.applyFog !== undefined) {
- mesh.applyFog = parsedMesh.applyFog;
- }
- if (parsedMesh.pickable !== undefined) {
- mesh.isPickable = parsedMesh.pickable;
- }
- if (parsedMesh.alphaIndex !== undefined) {
- mesh.alphaIndex = parsedMesh.alphaIndex;
- }
- mesh.receiveShadows = parsedMesh.receiveShadows;
- mesh.billboardMode = parsedMesh.billboardMode;
- if (parsedMesh.visibility !== undefined) {
- mesh.visibility = parsedMesh.visibility;
- }
- mesh.checkCollisions = parsedMesh.checkCollisions;
- if (parsedMesh.isBlocker !== undefined) {
- mesh.isBlocker = parsedMesh.isBlocker;
- }
- mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
- // freezeWorldMatrix
- if (parsedMesh.freezeWorldMatrix) {
- mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
- }
- // Parent
- if (parsedMesh.parentId) {
- mesh._waitingParentId = parsedMesh.parentId;
- }
- // Actions
- if (parsedMesh.actions !== undefined) {
- mesh._waitingActions = parsedMesh.actions;
- }
- // Overlay
- if (parsedMesh.overlayAlpha !== undefined) {
- mesh.overlayAlpha = parsedMesh.overlayAlpha;
- }
- if (parsedMesh.overlayColor !== undefined) {
- mesh.overlayColor = Color3.FromArray(parsedMesh.overlayColor);
- }
- if (parsedMesh.renderOverlay !== undefined) {
- mesh.renderOverlay = parsedMesh.renderOverlay;
- }
- // Geometry
- mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
- mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
- if (parsedMesh.delayLoadingFile) {
- mesh.delayLoadState = Engine.DELAYLOADSTATE_NOTLOADED;
- mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
- mesh._boundingInfo = new BoundingInfo(Vector3.FromArray(parsedMesh.boundingBoxMinimum), Vector3.FromArray(parsedMesh.boundingBoxMaximum));
- if (parsedMesh._binaryInfo) {
- mesh._binaryInfo = parsedMesh._binaryInfo;
- }
- mesh._delayInfo = [];
- if (parsedMesh.hasUVs) {
- mesh._delayInfo.push(VertexBuffer.UVKind);
- }
- if (parsedMesh.hasUVs2) {
- mesh._delayInfo.push(VertexBuffer.UV2Kind);
- }
- if (parsedMesh.hasUVs3) {
- mesh._delayInfo.push(VertexBuffer.UV3Kind);
- }
- if (parsedMesh.hasUVs4) {
- mesh._delayInfo.push(VertexBuffer.UV4Kind);
- }
- if (parsedMesh.hasUVs5) {
- mesh._delayInfo.push(VertexBuffer.UV5Kind);
- }
- if (parsedMesh.hasUVs6) {
- mesh._delayInfo.push(VertexBuffer.UV6Kind);
- }
- if (parsedMesh.hasColors) {
- mesh._delayInfo.push(VertexBuffer.ColorKind);
- }
- if (parsedMesh.hasMatricesIndices) {
- mesh._delayInfo.push(VertexBuffer.MatricesIndicesKind);
- }
- if (parsedMesh.hasMatricesWeights) {
- mesh._delayInfo.push(VertexBuffer.MatricesWeightsKind);
- }
- mesh._delayLoadingFunction = Geometry._ImportGeometry;
- if (SceneLoader.ForceFullSceneLoadingForIncremental) {
- mesh._checkDelayState();
- }
- } else {
- Geometry._ImportGeometry(parsedMesh, mesh);
- }
- // Material
- if (parsedMesh.materialId) {
- mesh.setMaterialByID(parsedMesh.materialId);
- } else {
- mesh.material = null;
- }
- // Morph targets
- if (parsedMesh.morphTargetManagerId > -1) {
- mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
- }
- // Skeleton
- if (parsedMesh.skeletonId > -1) {
- mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
- if (parsedMesh.numBoneInfluencers) {
- mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
- }
- }
- // Animations
- if (parsedMesh.animations) {
- for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
- var parsedAnimation = parsedMesh.animations[animationIndex];
- mesh.animations.push(Animation.Parse(parsedAnimation));
- }
- Node.ParseAnimationRanges(mesh, parsedMesh, scene);
- }
- if (parsedMesh.autoAnimate) {
- scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
- }
- // Layer Mask
- if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
- mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
- } else {
- mesh.layerMask = 0x0FFFFFFF;
- }
- // Physics
- if (parsedMesh.physicsImpostor) {
- mesh.physicsImpostor = new PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
- mass: parsedMesh.physicsMass,
- friction: parsedMesh.physicsFriction,
- restitution: parsedMesh.physicsRestitution
- }, scene);
- }
- // Instances
- if (parsedMesh.instances) {
- for (var index = 0; index < parsedMesh.instances.length; index++) {
- var parsedInstance = parsedMesh.instances[index];
- var instance = mesh.createInstance(parsedInstance.name);
- if (parsedInstance.id) {
- instance.id = parsedInstance.id;
- }
- if (Tags) {
- Tags.AddTagsTo(instance, parsedInstance.tags);
- }
- instance.position = Vector3.FromArray(parsedInstance.position);
- if (parsedInstance.parentId) {
- instance._waitingParentId = parsedInstance.parentId;
- }
- if (parsedInstance.rotationQuaternion) {
- instance.rotationQuaternion = Quaternion.FromArray(parsedInstance.rotationQuaternion);
- } else if (parsedInstance.rotation) {
- instance.rotation = Vector3.FromArray(parsedInstance.rotation);
- }
- instance.scaling = Vector3.FromArray(parsedInstance.scaling);
- instance.checkCollisions = mesh.checkCollisions;
- if (parsedMesh.animations) {
- for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
- parsedAnimation = parsedMesh.animations[animationIndex];
- instance.animations.push(Animation.Parse(parsedAnimation));
- }
- Node.ParseAnimationRanges(instance, parsedMesh, scene);
- if (parsedMesh.autoAnimate) {
- scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
- }
- }
- }
- }
- return mesh;
- }
- /**
- * Creates a ribbon mesh.
- * Please consider using the same method from the MeshBuilder class instead.
- * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
- *
- * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
- * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
- * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
- * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
- * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
- * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
- * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- public static CreateRibbon(name: string, pathArray: Vector3[][], closeArray: boolean = false, closePath: boolean, offset: number, scene?: Scene, updatable: boolean = false, sideOrientation?: number, instance?: Mesh): Mesh {
- return MeshBuilder.CreateRibbon(name, {
- pathArray: pathArray,
- closeArray: closeArray,
- closePath: closePath,
- offset: offset,
- updatable: updatable,
- sideOrientation: sideOrientation,
- instance: instance
- }, scene);
- }
- /**
- * Creates a plane polygonal mesh. By default, this is a disc.
- * Please consider using the same method from the MeshBuilder class instead.
- * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
- * The parameter `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.
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- public static CreateDisc(name: string, radius: number, tessellation: number, scene: Nullable<Scene> = null, updatable?: boolean, sideOrientation?: number): Mesh {
- var options = {
- radius: radius,
- tessellation: tessellation,
- sideOrientation: sideOrientation,
- updatable: updatable
- }
- return MeshBuilder.CreateDisc(name, options, scene);
- }
- /**
- * Creates a box mesh.
- * Please consider using the same method from the MeshBuilder class instead.
- * The parameter `size` sets the size (float) of each box side (default 1).
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- public static CreateBox(name: string, size: number, scene: Nullable<Scene> = null, updatable?: boolean, sideOrientation?: number): Mesh {
- var options = {
- size: size,
- sideOrientation: sideOrientation,
- updatable: updatable
- };
- return MeshBuilder.CreateBox(name, options, scene);
- }
- /**
- * Creates a sphere mesh.
- * Please consider using the same method from the MeshBuilder class instead.
- * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
- * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- public static CreateSphere(name: string, segments: number, diameter: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
- var options = {
- segments: segments,
- diameterX: diameter,
- diameterY: diameter,
- diameterZ: diameter,
- sideOrientation: sideOrientation,
- updatable: updatable
- }
- return MeshBuilder.CreateSphere(name, options, scene);
- }
- /**
- * Creates a cylinder or a cone mesh.
- * Please consider using the same method from the MeshBuilder class instead.
- * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
- * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
- * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
- * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
- * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene?: Scene, updatable?: any, sideOrientation?: number): Mesh {
- if (scene === undefined || !(scene instanceof Scene)) {
- if (scene !== undefined) {
- sideOrientation = updatable || Mesh.DEFAULTSIDE;
- updatable = scene;
- }
- scene = <Scene>subdivisions;
- subdivisions = 1;
- }
- var options = {
- height: height,
- diameterTop: diameterTop,
- diameterBottom: diameterBottom,
- tessellation: tessellation,
- subdivisions: subdivisions,
- sideOrientation: sideOrientation,
- updatable: updatable
- }
- return MeshBuilder.CreateCylinder(name, options, scene);
- }
- // Torus (Code from SharpDX.org)
- /**
- * Creates a torus mesh.
- * Please consider using the same method from the MeshBuilder class instead.
- * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
- * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
- * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- public static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
- var options = {
- diameter: diameter,
- thickness: thickness,
- tessellation: tessellation,
- sideOrientation: sideOrientation,
- updatable: updatable
- }
- return MeshBuilder.CreateTorus(name, options, scene);
- }
- /**
- * Creates a torus knot mesh.
- * Please consider using the same method from the MeshBuilder class instead.
- * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
- * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
- * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
- * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
- var options = {
- radius: radius,
- tube: tube,
- radialSegments: radialSegments,
- tubularSegments: tubularSegments,
- p: p,
- q: q,
- sideOrientation: sideOrientation,
- updatable: updatable
- }
- return MeshBuilder.CreateTorusKnot(name, options, scene);
- }
- /**
- * Creates a line mesh.
- * Please consider using the same method from the MeshBuilder class instead.
- * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
- * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
- * The parameter `points` is an array successive Vector3.
- * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
- * When updating an instance, remember that only point positions can change, not the number of points.
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- public static CreateLines(name: string, points: Vector3[], scene: Nullable<Scene> = null, updatable: boolean = false, instance: Nullable<LinesMesh> = null): LinesMesh {
- var options = {
- points: points,
- updatable: updatable,
- instance: instance
- }
- return MeshBuilder.CreateLines(name, options, scene);
- }
- /**
- * Creates a dashed line mesh.
- * Please consider using the same method from the MeshBuilder class instead.
- * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
- * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
- * The parameter `points` is an array successive Vector3.
- * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
- * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
- * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
- * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
- * When updating an instance, remember that only point positions can change, not the number of points.
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- public static CreateDashedLines(name: string, points: Vector3[], dashSize: number, gapSize: number, dashNb: number, scene: Nullable<Scene> = null, updatable?: boolean, instance?: LinesMesh): LinesMesh {
- var options = {
- points: points,
- dashSize: dashSize,
- gapSize: gapSize,
- dashNb: dashNb,
- updatable: updatable,
- instance: instance
- }
- return MeshBuilder.CreateDashedLines(name, options, scene);
- }
- /**
- * Creates a polygon mesh.
- * Please consider using the same method from the MeshBuilder class instead.
- * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
- * 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.
- * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- * Remember you can only change the shape positions, not their number when updating a polygon.
- */
- public static CreatePolygon(name: string, shape: Vector3[], scene: Scene, holes?: Vector3[][], updatable?: boolean, sideOrientation?: number): Mesh {
- var options = {
- shape: shape,
- holes: holes,
- updatable: updatable,
- sideOrientation: sideOrientation
- }
- return MeshBuilder.CreatePolygon(name, options, scene);
- }
- /**
- * Creates an extruded polygon mesh, with depth in the Y direction.
- * Please consider using the same method from the MeshBuilder class instead.
- */
- public static ExtrudePolygon(name: string, shape: Vector3[], depth: number, scene: Scene, holes?: Vector3[][], updatable?: boolean, sideOrientation?: number): Mesh {
- var options = {
- shape: shape,
- holes: holes,
- depth: depth,
- updatable: updatable,
- sideOrientation: sideOrientation
- }
- return MeshBuilder.ExtrudePolygon(name, options, scene);
- }
- /**
- * Creates an extruded shape mesh.
- * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. 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.
- *
- * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
- * The parameter `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.
- * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
- * The parameter `rotation` (float, default 0 radians) 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.
- * The parameter `scale` (float, default 1) is the value to scale the shape.
- * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
- * The optional parameter `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/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
- * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- 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 {
- var options = {
- shape: shape,
- path: path,
- scale: scale,
- rotation: rotation,
- cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
- sideOrientation: sideOrientation,
- instance: instance,
- updatable: updatable
- }
- return MeshBuilder.ExtrudeShape(name, options, scene);
- }
- /**
- * Creates an custom extruded shape mesh.
- * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. 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.
- *
- * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
- * The parameter `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.
- * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
- * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
- * and the distance of this point from the begining of the path :
- * ```javascript
- * var rotationFunction = function(i, distance) {
- * // do things
- * return rotationValue; }
- * ```
- * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
- * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
- * and the distance of this point from the begining of the path :
- * ```javascript
- * var scaleFunction = function(i, distance) {
- * // do things
- * return scaleValue;}
- * ```
- * It must returns a float value that will be the scale value applied to the shape on each path point.
- * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
- * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
- * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
- * The optional parameter `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/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
- * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- 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 {
- var options = {
- shape: shape,
- path: path,
- scaleFunction: scaleFunction,
- rotationFunction: rotationFunction,
- ribbonCloseArray: ribbonCloseArray,
- ribbonClosePath: ribbonClosePath,
- cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
- sideOrientation: sideOrientation,
- instance: instance,
- updatable: updatable
- }
- return MeshBuilder.ExtrudeShapeCustom(name, options, scene);
- }
- /**
- * Creates lathe mesh.
- * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
- * Please consider using the same method from the MeshBuilder class instead.
- * The parameter `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.
- * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
- * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- public static CreateLathe(name: string, shape: Vector3[], radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
- var options = {
- shape: shape,
- radius: radius,
- tessellation: tessellation,
- sideOrientation: sideOrientation,
- updatable: updatable
- };
- return MeshBuilder.CreateLathe(name, options, scene);
- }
- /**
- * Creates a plane mesh.
- * Please consider using the same method from the MeshBuilder class instead.
- * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
- var options = {
- size: size,
- width: size,
- height: size,
- sideOrientation: sideOrientation,
- updatable: updatable
- }
- return MeshBuilder.CreatePlane(name, options, scene);
- }
- /**
- * Creates a ground mesh.
- * Please consider using the same method from the MeshBuilder class instead.
- * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
- * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene?: Scene, updatable?: boolean): Mesh {
- var options = {
- width: width,
- height: height,
- subdivisions: subdivisions,
- updatable: updatable
- }
- return MeshBuilder.CreateGround(name, options, scene);
- }
- /**
- * Creates a tiled ground mesh.
- * Please consider using the same method from the MeshBuilder class instead.
- * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
- * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
- * The parameter `subdivisions` is a javascript 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.
- * The parameter `precision` is a javascript 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.
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- 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 {
- var options = {
- xmin: xmin,
- zmin: zmin,
- xmax: xmax,
- zmax: zmax,
- subdivisions: subdivisions,
- precision: precision,
- updatable: updatable
- }
- return MeshBuilder.CreateTiledGround(name, options, scene);
- }
- /**
- * Creates a ground mesh from a height map.
- * tuto : http://doc.babylonjs.com/babylon101/height_map
- * Please consider using the same method from the MeshBuilder class instead.
- * The parameter `url` sets the URL of the height map image resource.
- * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
- * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
- * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
- * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
- * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
- * This function is passed the newly built mesh :
- * ```javascript
- * function(mesh) { // do things
- * return; }
- * ```
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- 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): GroundMesh {
- var options = {
- width: width,
- height: height,
- subdivisions: subdivisions,
- minHeight: minHeight,
- maxHeight: maxHeight,
- updatable: updatable,
- onReady: onReady
- };
- return MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
- }
- /**
- * Creates a tube mesh.
- * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. 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.
- * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
- * The parameter `radius` (positive float, default 1) sets the tube radius size.
- * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
- * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript 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.
- * It must return a radius value (positive float) :
- * ```javascript
- * var radiusFunction = function(i, distance) {
- * // do things
- * return radius; }
- * ```
- * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
- * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- 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 {
- var options = {
- path: path,
- radius: radius,
- tessellation: tessellation,
- radiusFunction: radiusFunction,
- arc: 1,
- cap: cap,
- updatable: updatable,
- sideOrientation: sideOrientation,
- instance: instance
- }
- return MeshBuilder.CreateTube(name, options, scene);
- }
- /**
- * Creates a polyhedron mesh.
- * Please consider using the same method from the MeshBuilder class instead.
- * 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.
- * The parameter `size` (positive float, default 1) sets the polygon size.
- * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
- * 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`.
- * 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
- * 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)`).
- * 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 : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
- * 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.
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- 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 {
- return MeshBuilder.CreatePolyhedron(name, options, scene);
- }
- /**
- * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
- * Please consider using the same method from the MeshBuilder class instead.
- * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
- * 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`).
- * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
- * 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.
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- public static CreateIcoSphere(name: string, options: { radius?: number, flat?: boolean, subdivisions?: number, sideOrientation?: number, updatable?: boolean }, scene: Scene): Mesh {
- return MeshBuilder.CreateIcoSphere(name, options, scene);
- }
- /**
- * Creates a decal mesh.
- * Please consider using the same method from the MeshBuilder class instead.
- * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
- * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
- * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
- * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
- * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
- */
- public static CreateDecal(name: string, sourceMesh: AbstractMesh, position: Vector3, normal: Vector3, size: Vector3, angle: number): Mesh {
- var options = {
- position: position,
- normal: normal,
- size: size,
- angle: angle
- }
- return MeshBuilder.CreateDecal(name, sourceMesh, options);
- }
- // Skeletons
- /**
- * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
- */
- public setPositionsForCPUSkinning(): Float32Array {
- if (!this._sourcePositions) {
- let source = this.getVerticesData(VertexBuffer.PositionKind);
- if (!source) {
- return this._sourcePositions;
- }
- this._sourcePositions = new Float32Array(<any>source);
- if (!this.isVertexBufferUpdatable(VertexBuffer.PositionKind)) {
- this.setVerticesData(VertexBuffer.PositionKind, source, true);
- }
- }
- return this._sourcePositions;
- }
- /**
- * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
- */
- public setNormalsForCPUSkinning(): Float32Array {
- if (!this._sourceNormals) {
- let source = this.getVerticesData(VertexBuffer.NormalKind);
- if (!source) {
- return this._sourceNormals;
- }
- this._sourceNormals = new Float32Array(<any>source);
- if (!this.isVertexBufferUpdatable(VertexBuffer.NormalKind)) {
- this.setVerticesData(VertexBuffer.NormalKind, source, true);
- }
- }
- return this._sourceNormals;
- }
- /**
- * Updates the vertex buffer by applying transformation from the bones.
- * Returns the Mesh.
- *
- * @param {skeleton} skeleton to apply
- */
- public applySkeleton(skeleton: Skeleton): Mesh {
- if (!this.geometry) {
- return this;
- }
- if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
- return this;
- }
- this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
- if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
- return this;
- }
- if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
- return this;
- }
- if (!this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {
- return this;
- }
- if (!this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
- return this;
- }
- if (!this._sourcePositions) {
- var submeshes = this.subMeshes.slice();
- this.setPositionsForCPUSkinning();
- this.subMeshes = submeshes;
- }
- if (!this._sourceNormals) {
- this.setNormalsForCPUSkinning();
- }
- // positionsData checks for not being Float32Array will only pass at most once
- var positionsData = this.getVerticesData(VertexBuffer.PositionKind);
- if (!positionsData) {
- return this;
- }
- if (!(positionsData instanceof Float32Array)) {
- positionsData = new Float32Array(positionsData);
- }
- // normalsData checks for not being Float32Array will only pass at most once
- var normalsData = this.getVerticesData(VertexBuffer.NormalKind);
- if (!normalsData) {
- return this;
- }
- if (!(normalsData instanceof Float32Array)) {
- normalsData = new Float32Array(normalsData);
- }
- var matricesIndicesData = this.getVerticesData(VertexBuffer.MatricesIndicesKind);
- var matricesWeightsData = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
- if (!matricesWeightsData || !matricesIndicesData) {
- return this;
- }
- var needExtras = this.numBoneInfluencers > 4;
- var matricesIndicesExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind) : null;
- var matricesWeightsExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind) : null;
- var skeletonMatrices = skeleton.getTransformMatrices(this);
- var tempVector3 = Vector3.Zero();
- var finalMatrix = new Matrix();
- var tempMatrix = new Matrix();
- var matWeightIdx = 0;
- var inf: number;
- for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
- var weight: number;
- for (inf = 0; inf < 4; inf++) {
- weight = matricesWeightsData[matWeightIdx + inf];
- if (weight > 0) {
- Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
- finalMatrix.addToSelf(tempMatrix);
- }
- }
- if (needExtras) {
- for (inf = 0; inf < 4; inf++) {
- weight = matricesWeightsExtraData![matWeightIdx + inf];
- if (weight > 0) {
- Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData![matWeightIdx + inf] * 16), weight, tempMatrix);
- finalMatrix.addToSelf(tempMatrix);
- }
- }
- }
- Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
- tempVector3.toArray(positionsData, index);
- Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
- tempVector3.toArray(normalsData, index);
- finalMatrix.reset();
- }
- this.updateVerticesData(VertexBuffer.PositionKind, positionsData);
- this.updateVerticesData(VertexBuffer.NormalKind, normalsData);
- return this;
- }
- // Tools
- /**
- * Returns an object `{min:` Vector3`, max:` Vector3`}`
- * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
- */
- public static MinMax(meshes: AbstractMesh[]): { min: Vector3; max: Vector3 } {
- var minVector: Nullable<Vector3> = null;
- var maxVector: Nullable<Vector3> = null;
- meshes.forEach(function (mesh, index, array) {
- let boundingInfo = mesh.getBoundingInfo();
- let boundingBox = boundingInfo.boundingBox;
- if (!minVector || !maxVector) {
- minVector = boundingBox.minimumWorld;
- maxVector = boundingBox.maximumWorld;
- } else {
- minVector.minimizeInPlace(boundingBox.minimumWorld);
- maxVector.maximizeInPlace(boundingBox.maximumWorld);
- }
- });
- if (!minVector || !maxVector) {
- return {
- min: Vector3.Zero(),
- max: Vector3.Zero()
- }
- }
- return {
- min: minVector,
- max: maxVector
- };
- }
- /**
- * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
- */
- public static Center(meshesOrMinMaxVector: { min: Vector3; max: Vector3 } | AbstractMesh[]): Vector3 {
- var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
- return Vector3.Center(minMaxVector.min, minMaxVector.max);
- }
- /**
- * Merge the array of meshes into a single mesh for performance reasons.
- * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
- * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
- * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
- * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
- * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
- */
- public static MergeMeshes(meshes: Array<Mesh>, disposeSource = true, allow32BitsIndices?: boolean, meshSubclass?: Mesh, subdivideWithSubMeshes?: boolean): Nullable<Mesh> {
- var index: number;
- if (!allow32BitsIndices) {
- var totalVertices = 0;
- // Counting vertices
- for (index = 0; index < meshes.length; index++) {
- if (meshes[index]) {
- totalVertices += meshes[index].getTotalVertices();
- if (totalVertices > 65536) {
- Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
- return null;
- }
- }
- }
- }
- // Merge
- var vertexData: Nullable<VertexData> = null;
- var otherVertexData: VertexData;
- var indiceArray: Array<number> = new Array<number>();
- var source: Nullable<Mesh> = null;
- for (index = 0; index < meshes.length; index++) {
- if (meshes[index]) {
- meshes[index].computeWorldMatrix(true);
- otherVertexData = VertexData.ExtractFromMesh(meshes[index], true, true);
- otherVertexData.transform(meshes[index].getWorldMatrix());
- if (vertexData) {
- vertexData.merge(otherVertexData);
- } else {
- vertexData = otherVertexData;
- source = meshes[index];
- }
- if (subdivideWithSubMeshes) {
- indiceArray.push(meshes[index].getTotalIndices());
- }
- }
- }
- source = <Mesh>source;
- if (!meshSubclass) {
- meshSubclass = new Mesh(source.name + "_merged", source.getScene());
- }
- (<VertexData>vertexData).applyToMesh(meshSubclass);
- // Setting properties
- meshSubclass.material = source.material;
- meshSubclass.checkCollisions = source.checkCollisions;
- // Cleaning
- if (disposeSource) {
- for (index = 0; index < meshes.length; index++) {
- if (meshes[index]) {
- meshes[index].dispose();
- }
- }
- }
- // Subdivide
- if (subdivideWithSubMeshes) {
- //-- removal of global submesh
- meshSubclass.releaseSubMeshes();
- index = 0;
- var offset = 0;
- //-- apply subdivision according to index table
- while (index < indiceArray.length) {
- SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
- offset += indiceArray[index];
- index++;
- }
- }
- return meshSubclass;
- }
- }
- }
|