thinEngine.ts 180 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487
  1. import { EngineStore } from './engineStore';
  2. import { IInternalTextureLoader } from '../Materials/Textures/internalTextureLoader';
  3. import { Effect, IEffectCreationOptions } from '../Materials/effect';
  4. import { _DevTools } from '../Misc/devTools';
  5. import { IShaderProcessor } from './Processors/iShaderProcessor';
  6. import { UniformBuffer } from '../Materials/uniformBuffer';
  7. import { Nullable, DataArray, IndicesArray } from '../types';
  8. import { EngineCapabilities } from './engineCapabilities';
  9. import { Observable } from '../Misc/observable';
  10. import { DepthCullingState } from '../States/depthCullingState';
  11. import { StencilState } from '../States/stencilState';
  12. import { AlphaState } from '../States/alphaCullingState';
  13. import { Constants } from './constants';
  14. import { InternalTexture, InternalTextureSource } from '../Materials/Textures/internalTexture';
  15. import { IViewportLike, IColor4Like } from '../Maths/math.like';
  16. import { DataBuffer } from '../Meshes/dataBuffer';
  17. import { IFileRequest } from '../Misc/fileRequest';
  18. import { Logger } from '../Misc/logger';
  19. import { DomManagement } from '../Misc/domManagement';
  20. import { WebGL2ShaderProcessor } from './WebGL/webGL2ShaderProcessors';
  21. import { WebGLDataBuffer } from '../Meshes/WebGL/webGLDataBuffer';
  22. import { IPipelineContext } from './IPipelineContext';
  23. import { WebGLPipelineContext } from './WebGL/webGLPipelineContext';
  24. import { VertexBuffer } from '../Meshes/buffer';
  25. import { InstancingAttributeInfo } from './instancingAttributeInfo';
  26. import { BaseTexture } from '../Materials/Textures/baseTexture';
  27. import { IOfflineProvider } from '../Offline/IOfflineProvider';
  28. import { IEffectFallbacks } from '../Materials/iEffectFallbacks';
  29. import { IWebRequest } from '../Misc/interfaces/iWebRequest';
  30. import { CanvasGenerator } from '../Misc/canvasGenerator';
  31. import { PerformanceConfigurator } from './performanceConfigurator';
  32. declare type WebRequest = import("../Misc/webRequest").WebRequest;
  33. declare type LoadFileError = import("../Misc/fileTools").LoadFileError;
  34. declare type Observer<T> = import("../Misc/observable").Observer<T>;
  35. declare type VideoTexture = import("../Materials/Textures/videoTexture").VideoTexture;
  36. declare type RenderTargetTexture = import("../Materials/Textures/renderTargetTexture").RenderTargetTexture;
  37. declare type Texture = import("../Materials/Textures/texture").Texture;
  38. /**
  39. * Defines the interface used by objects working like Scene
  40. * @hidden
  41. */
  42. export interface ISceneLike {
  43. _addPendingData(data: any): void;
  44. _removePendingData(data: any): void;
  45. offlineProvider: IOfflineProvider;
  46. }
  47. /**
  48. * Keeps track of all the buffer info used in engine.
  49. */
  50. class BufferPointer {
  51. public active: boolean;
  52. public index: number;
  53. public size: number;
  54. public type: number;
  55. public normalized: boolean;
  56. public stride: number;
  57. public offset: number;
  58. public buffer: WebGLBuffer;
  59. }
  60. /**
  61. * Information about the current host
  62. */
  63. export interface HostInformation {
  64. /**
  65. * Defines if the current host is a mobile
  66. */
  67. isMobile: boolean;
  68. }
  69. /** Interface defining initialization parameters for Engine class */
  70. export interface EngineOptions extends WebGLContextAttributes {
  71. /**
  72. * Defines if the engine should no exceed a specified device ratio
  73. * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
  74. */
  75. limitDeviceRatio?: number;
  76. /**
  77. * Defines if webvr should be enabled automatically
  78. * @see https://doc.babylonjs.com/how_to/webvr_camera
  79. */
  80. autoEnableWebVR?: boolean;
  81. /**
  82. * Defines if webgl2 should be turned off even if supported
  83. * @see https://doc.babylonjs.com/features/webgl2
  84. */
  85. disableWebGL2Support?: boolean;
  86. /**
  87. * Defines if webaudio should be initialized as well
  88. * @see https://doc.babylonjs.com/how_to/playing_sounds_and_music
  89. */
  90. audioEngine?: boolean;
  91. /**
  92. * Defines if animations should run using a deterministic lock step
  93. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  94. */
  95. deterministicLockstep?: boolean;
  96. /** Defines the maximum steps to use with deterministic lock step mode */
  97. lockstepMaxSteps?: number;
  98. /** Defines the seconds between each deterministic lock step */
  99. timeStep?: number;
  100. /**
  101. * Defines that engine should ignore context lost events
  102. * If this event happens when this parameter is true, you will have to reload the page to restore rendering
  103. */
  104. doNotHandleContextLost?: boolean;
  105. /**
  106. * Defines that engine should ignore modifying touch action attribute and style
  107. * If not handle, you might need to set it up on your side for expected touch devices behavior.
  108. */
  109. doNotHandleTouchAction?: boolean;
  110. /**
  111. * Defines that engine should compile shaders with high precision floats (if supported). True by default
  112. */
  113. useHighPrecisionFloats?: boolean;
  114. /**
  115. * Make the canvas XR Compatible for XR sessions
  116. */
  117. xrCompatible?: boolean;
  118. /**
  119. * Make the matrix computations to be performed in 64 bits instead of 32 bits. False by default
  120. */
  121. useHighPrecisionMatrix?: boolean;
  122. /**
  123. * Will prevent the system from falling back to software implementation if a hardware device cannot be created
  124. */
  125. failIfMajorPerformanceCaveat?: boolean;
  126. }
  127. /**
  128. * The base engine class (root of all engines)
  129. */
  130. export class ThinEngine {
  131. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  132. public static ExceptionList = [
  133. { key: "Chrome\/63\.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  134. { key: "Firefox\/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  135. { key: "Firefox\/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  136. { key: "Chrome\/72.+?Mobile", capture: null, captureConstraint: null, targets: ["vao"] },
  137. { key: "Chrome\/73.+?Mobile", capture: null, captureConstraint: null, targets: ["vao"] },
  138. { key: "Chrome\/74.+?Mobile", capture: null, captureConstraint: null, targets: ["vao"] },
  139. { key: "Mac OS.+Chrome\/71", capture: null, captureConstraint: null, targets: ["vao"] },
  140. { key: "Mac OS.+Chrome\/72", capture: null, captureConstraint: null, targets: ["vao"] }
  141. ];
  142. /** @hidden */
  143. public static _TextureLoaders: IInternalTextureLoader[] = [];
  144. /**
  145. * Returns the current npm package of the sdk
  146. */
  147. // Not mixed with Version for tooling purpose.
  148. public static get NpmPackage(): string {
  149. return "babylonjs@4.2.0-beta.5";
  150. }
  151. /**
  152. * Returns the current version of the framework
  153. */
  154. public static get Version(): string {
  155. return "4.2.0-beta.5";
  156. }
  157. /**
  158. * Returns a string describing the current engine
  159. */
  160. public get description(): string {
  161. let description = "WebGL" + this.webGLVersion;
  162. if (this._caps.parallelShaderCompile) {
  163. description += " - Parallel shader compilation";
  164. }
  165. return description;
  166. }
  167. // Updatable statics so stick with vars here
  168. /**
  169. * Gets or sets the epsilon value used by collision engine
  170. */
  171. public static CollisionsEpsilon = 0.001;
  172. /**
  173. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  174. */
  175. public static get ShadersRepository(): string {
  176. return Effect.ShadersRepository;
  177. }
  178. public static set ShadersRepository(value: string) {
  179. Effect.ShadersRepository = value;
  180. }
  181. // Public members
  182. /** @hidden */
  183. public _shaderProcessor: IShaderProcessor;
  184. /**
  185. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  186. */
  187. public forcePOTTextures = false;
  188. /**
  189. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  190. */
  191. public isFullscreen = false;
  192. /**
  193. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  194. */
  195. public cullBackFaces = true;
  196. /**
  197. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  198. */
  199. public renderEvenInBackground = true;
  200. /**
  201. * Gets or sets a boolean indicating that cache can be kept between frames
  202. */
  203. public preventCacheWipeBetweenFrames = false;
  204. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  205. public validateShaderPrograms = false;
  206. /**
  207. * Gets or sets a boolean indicating if depth buffer should be reverse, going from far to near.
  208. * This can provide greater z depth for distant objects.
  209. */
  210. public useReverseDepthBuffer = false;
  211. // Uniform buffers list
  212. /**
  213. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  214. */
  215. public disableUniformBuffers = false;
  216. /** @hidden */
  217. public _uniformBuffers = new Array<UniformBuffer>();
  218. /**
  219. * Gets a boolean indicating that the engine supports uniform buffers
  220. * @see https://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  221. */
  222. public get supportsUniformBuffers(): boolean {
  223. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  224. }
  225. // Private Members
  226. /** @hidden */
  227. public _gl: WebGLRenderingContext;
  228. /** @hidden */
  229. public _webGLVersion = 1.0;
  230. protected _renderingCanvas: Nullable<HTMLCanvasElement>;
  231. protected _windowIsBackground = false;
  232. protected _creationOptions: EngineOptions;
  233. protected _highPrecisionShadersAllowed = true;
  234. /** @hidden */
  235. public get _shouldUseHighPrecisionShader(): boolean {
  236. return !!(this._caps.highPrecisionShaderSupported && this._highPrecisionShadersAllowed);
  237. }
  238. /**
  239. * Gets a boolean indicating that only power of 2 textures are supported
  240. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  241. */
  242. public get needPOTTextures(): boolean {
  243. return this._webGLVersion < 2 || this.forcePOTTextures;
  244. }
  245. /** @hidden */
  246. public _badOS = false;
  247. /** @hidden */
  248. public _badDesktopOS = false;
  249. private _hardwareScalingLevel: number;
  250. /** @hidden */
  251. public _caps: EngineCapabilities;
  252. private _isStencilEnable: boolean;
  253. private _glVersion: string;
  254. private _glRenderer: string;
  255. private _glVendor: string;
  256. /** @hidden */
  257. public _videoTextureSupported: boolean;
  258. protected _renderingQueueLaunched = false;
  259. protected _activeRenderLoops = new Array<() => void>();
  260. // Lost context
  261. /**
  262. * Observable signaled when a context lost event is raised
  263. */
  264. public onContextLostObservable = new Observable<ThinEngine>();
  265. /**
  266. * Observable signaled when a context restored event is raised
  267. */
  268. public onContextRestoredObservable = new Observable<ThinEngine>();
  269. private _onContextLost: (evt: Event) => void;
  270. private _onContextRestored: (evt: Event) => void;
  271. protected _contextWasLost = false;
  272. /** @hidden */
  273. public _doNotHandleContextLost = false;
  274. /**
  275. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  276. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  277. */
  278. public get doNotHandleContextLost(): boolean {
  279. return this._doNotHandleContextLost;
  280. }
  281. public set doNotHandleContextLost(value: boolean) {
  282. this._doNotHandleContextLost = value;
  283. }
  284. /**
  285. * Gets or sets a boolean indicating that vertex array object must be disabled even if they are supported
  286. */
  287. public disableVertexArrayObjects = false;
  288. // States
  289. /** @hidden */
  290. protected _colorWrite = true;
  291. /** @hidden */
  292. protected _colorWriteChanged = true;
  293. /** @hidden */
  294. protected _depthCullingState = new DepthCullingState();
  295. /** @hidden */
  296. protected _stencilState = new StencilState();
  297. /** @hidden */
  298. public _alphaState = new AlphaState();
  299. /** @hidden */
  300. public _alphaMode = Constants.ALPHA_ADD;
  301. /** @hidden */
  302. public _alphaEquation = Constants.ALPHA_DISABLE;
  303. // Cache
  304. /** @hidden */
  305. public _internalTexturesCache = new Array<InternalTexture>();
  306. /** @hidden */
  307. protected _activeChannel = 0;
  308. private _currentTextureChannel = -1;
  309. /** @hidden */
  310. protected _boundTexturesCache: { [key: string]: Nullable<InternalTexture> } = {};
  311. /** @hidden */
  312. protected _currentEffect: Nullable<Effect>;
  313. /** @hidden */
  314. protected _currentProgram: Nullable<WebGLProgram>;
  315. private _compiledEffects: { [key: string]: Effect } = {};
  316. private _vertexAttribArraysEnabled: boolean[] = [];
  317. /** @hidden */
  318. protected _cachedViewport: Nullable<IViewportLike>;
  319. private _cachedVertexArrayObject: Nullable<WebGLVertexArrayObject>;
  320. /** @hidden */
  321. protected _cachedVertexBuffers: any;
  322. /** @hidden */
  323. protected _cachedIndexBuffer: Nullable<DataBuffer>;
  324. /** @hidden */
  325. protected _cachedEffectForVertexBuffers: Nullable<Effect>;
  326. /** @hidden */
  327. public _currentRenderTarget: Nullable<InternalTexture>;
  328. private _uintIndicesCurrentlySet = false;
  329. protected _currentBoundBuffer = new Array<Nullable<WebGLBuffer>>();
  330. /** @hidden */
  331. public _currentFramebuffer: Nullable<WebGLFramebuffer> = null;
  332. /** @hidden */
  333. public _dummyFramebuffer: Nullable<WebGLFramebuffer> = null;
  334. private _currentBufferPointers = new Array<BufferPointer>();
  335. private _currentInstanceLocations = new Array<number>();
  336. private _currentInstanceBuffers = new Array<DataBuffer>();
  337. private _textureUnits: Int32Array;
  338. /** @hidden */
  339. public _workingCanvas: Nullable<HTMLCanvasElement | OffscreenCanvas>;
  340. /** @hidden */
  341. public _workingContext: Nullable<CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D>;
  342. /** @hidden */
  343. public _boundRenderFunction: any;
  344. private _vaoRecordInProgress = false;
  345. private _mustWipeVertexAttributes = false;
  346. private _emptyTexture: Nullable<InternalTexture>;
  347. private _emptyCubeTexture: Nullable<InternalTexture>;
  348. private _emptyTexture3D: Nullable<InternalTexture>;
  349. private _emptyTexture2DArray: Nullable<InternalTexture>;
  350. /** @hidden */
  351. public _frameHandler: number;
  352. private _nextFreeTextureSlots = new Array<number>();
  353. private _maxSimultaneousTextures = 0;
  354. private _activeRequests = new Array<IFileRequest>();
  355. /** @hidden */
  356. public _transformTextureUrl: Nullable<(url: string) => string> = null;
  357. /**
  358. * Gets information about the current host
  359. */
  360. public hostInformation: HostInformation = {
  361. isMobile: false
  362. };
  363. protected get _supportsHardwareTextureRescaling() {
  364. return false;
  365. }
  366. private _framebufferDimensionsObject: Nullable<{framebufferWidth: number, framebufferHeight: number}>;
  367. /**
  368. * sets the object from which width and height will be taken from when getting render width and height
  369. * Will fallback to the gl object
  370. * @param dimensions the framebuffer width and height that will be used.
  371. */
  372. public set framebufferDimensionsObject(dimensions: Nullable<{framebufferWidth: number, framebufferHeight: number}>) {
  373. this._framebufferDimensionsObject = dimensions;
  374. }
  375. /**
  376. * Gets the current viewport
  377. */
  378. public get currentViewport(): Nullable<IViewportLike> {
  379. return this._cachedViewport;
  380. }
  381. /**
  382. * Gets the default empty texture
  383. */
  384. public get emptyTexture(): InternalTexture {
  385. if (!this._emptyTexture) {
  386. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Constants.TEXTUREFORMAT_RGBA, false, false, Constants.TEXTURE_NEAREST_SAMPLINGMODE);
  387. }
  388. return this._emptyTexture;
  389. }
  390. /**
  391. * Gets the default empty 3D texture
  392. */
  393. public get emptyTexture3D(): InternalTexture {
  394. if (!this._emptyTexture3D) {
  395. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Constants.TEXTUREFORMAT_RGBA, false, false, Constants.TEXTURE_NEAREST_SAMPLINGMODE);
  396. }
  397. return this._emptyTexture3D;
  398. }
  399. /**
  400. * Gets the default empty 2D array texture
  401. */
  402. public get emptyTexture2DArray(): InternalTexture {
  403. if (!this._emptyTexture2DArray) {
  404. this._emptyTexture2DArray = this.createRawTexture2DArray(new Uint8Array(4), 1, 1, 1, Constants.TEXTUREFORMAT_RGBA, false, false, Constants.TEXTURE_NEAREST_SAMPLINGMODE);
  405. }
  406. return this._emptyTexture2DArray;
  407. }
  408. /**
  409. * Gets the default empty cube texture
  410. */
  411. public get emptyCubeTexture(): InternalTexture {
  412. if (!this._emptyCubeTexture) {
  413. var faceData = new Uint8Array(4);
  414. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  415. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Constants.TEXTUREFORMAT_RGBA, Constants.TEXTURETYPE_UNSIGNED_INT, false, false, Constants.TEXTURE_NEAREST_SAMPLINGMODE);
  416. }
  417. return this._emptyCubeTexture;
  418. }
  419. /**
  420. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  421. */
  422. public readonly premultipliedAlpha: boolean = true;
  423. /**
  424. * Observable event triggered before each texture is initialized
  425. */
  426. public onBeforeTextureInitObservable = new Observable<Texture>();
  427. /**
  428. * Creates a new engine
  429. * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which alreay used the WebGL context
  430. * @param antialias defines enable antialiasing (default: false)
  431. * @param options defines further options to be sent to the getContext() function
  432. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  433. */
  434. constructor(canvasOrContext: Nullable<HTMLCanvasElement | WebGLRenderingContext | WebGL2RenderingContext>, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio: boolean = false) {
  435. let canvas: Nullable<HTMLCanvasElement> = null;
  436. if (!canvasOrContext) {
  437. return;
  438. }
  439. options = options || {};
  440. PerformanceConfigurator.SetMatrixPrecision(!!options.useHighPrecisionMatrix);
  441. if ((canvasOrContext as any).getContext) {
  442. canvas = <HTMLCanvasElement>canvasOrContext;
  443. this._renderingCanvas = canvas;
  444. if (antialias != null) {
  445. options.antialias = antialias;
  446. }
  447. if (options.deterministicLockstep === undefined) {
  448. options.deterministicLockstep = false;
  449. }
  450. if (options.lockstepMaxSteps === undefined) {
  451. options.lockstepMaxSteps = 4;
  452. }
  453. if (options.timeStep === undefined) {
  454. options.timeStep = 1 / 60;
  455. }
  456. if (options.preserveDrawingBuffer === undefined) {
  457. options.preserveDrawingBuffer = false;
  458. }
  459. if (options.audioEngine === undefined) {
  460. options.audioEngine = true;
  461. }
  462. if (options.stencil === undefined) {
  463. options.stencil = true;
  464. }
  465. if (options.premultipliedAlpha === false) {
  466. this.premultipliedAlpha = false;
  467. }
  468. if (options.xrCompatible === undefined) {
  469. options.xrCompatible = true;
  470. }
  471. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  472. // Exceptions
  473. if (navigator && navigator.userAgent) {
  474. let ua = navigator.userAgent;
  475. this.hostInformation.isMobile = ua.indexOf("Mobile") !== -1;
  476. for (var exception of ThinEngine.ExceptionList) {
  477. let key = exception.key;
  478. let targets = exception.targets;
  479. let check = new RegExp(key);
  480. if (check.test(ua)) {
  481. if (exception.capture && exception.captureConstraint) {
  482. let capture = exception.capture;
  483. let constraint = exception.captureConstraint;
  484. let regex = new RegExp(capture);
  485. let matches = regex.exec(ua);
  486. if (matches && matches.length > 0) {
  487. let capturedValue = parseInt(matches[matches.length - 1]);
  488. if (capturedValue >= constraint) {
  489. continue;
  490. }
  491. }
  492. }
  493. for (var target of targets) {
  494. switch (target) {
  495. case "uniformBuffer":
  496. this.disableUniformBuffers = true;
  497. break;
  498. case "vao":
  499. this.disableVertexArrayObjects = true;
  500. break;
  501. }
  502. }
  503. }
  504. }
  505. }
  506. // Context lost
  507. if (!this._doNotHandleContextLost) {
  508. this._onContextLost = (evt: Event) => {
  509. evt.preventDefault();
  510. this._contextWasLost = true;
  511. Logger.Warn("WebGL context lost.");
  512. this.onContextLostObservable.notifyObservers(this);
  513. };
  514. this._onContextRestored = () => {
  515. // Adding a timeout to avoid race condition at browser level
  516. setTimeout(() => {
  517. // Rebuild gl context
  518. this._initGLContext();
  519. // Rebuild effects
  520. this._rebuildEffects();
  521. // Rebuild textures
  522. this._rebuildInternalTextures();
  523. // Rebuild buffers
  524. this._rebuildBuffers();
  525. // Cache
  526. this.wipeCaches(true);
  527. Logger.Warn("WebGL context successfully restored.");
  528. this.onContextRestoredObservable.notifyObservers(this);
  529. this._contextWasLost = false;
  530. }, 0);
  531. };
  532. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  533. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  534. options.powerPreference = "high-performance";
  535. }
  536. // GL
  537. if (!options.disableWebGL2Support) {
  538. try {
  539. this._gl = <any>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  540. if (this._gl) {
  541. this._webGLVersion = 2.0;
  542. // Prevent weird browsers to lie (yeah that happens!)
  543. if (!this._gl.deleteQuery) {
  544. this._webGLVersion = 1.0;
  545. }
  546. }
  547. } catch (e) {
  548. // Do nothing
  549. }
  550. }
  551. if (!this._gl) {
  552. if (!canvas) {
  553. throw new Error("The provided canvas is null or undefined.");
  554. }
  555. try {
  556. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  557. } catch (e) {
  558. throw new Error("WebGL not supported");
  559. }
  560. }
  561. if (!this._gl) {
  562. throw new Error("WebGL not supported");
  563. }
  564. } else {
  565. this._gl = <WebGLRenderingContext>canvasOrContext;
  566. this._renderingCanvas = this._gl.canvas as HTMLCanvasElement;
  567. if (this._gl.renderbufferStorageMultisample) {
  568. this._webGLVersion = 2.0;
  569. }
  570. const attributes = this._gl.getContextAttributes();
  571. if (attributes) {
  572. options.stencil = attributes.stencil;
  573. }
  574. }
  575. // Ensures a consistent color space unpacking of textures cross browser.
  576. this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, this._gl.NONE);
  577. if (options.useHighPrecisionFloats !== undefined) {
  578. this._highPrecisionShadersAllowed = options.useHighPrecisionFloats;
  579. }
  580. // Viewport
  581. const devicePixelRatio = DomManagement.IsWindowObjectExist() ? (window.devicePixelRatio || 1.0) : 1.0;
  582. var limitDeviceRatio = options.limitDeviceRatio || devicePixelRatio;
  583. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, devicePixelRatio) : 1.0;
  584. this.resize();
  585. this._isStencilEnable = options.stencil ? true : false;
  586. this._initGLContext();
  587. // Prepare buffer pointers
  588. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  589. this._currentBufferPointers[i] = new BufferPointer();
  590. }
  591. // Shader processor
  592. if (this.webGLVersion > 1) {
  593. this._shaderProcessor = new WebGL2ShaderProcessor();
  594. }
  595. // Detect if we are running on a faulty buggy OS.
  596. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  597. // Starting with iOS 14, we can trust the browser
  598. let matches = navigator.userAgent.match(/Version\/(\d+)/);
  599. if (matches && matches.length === 2) {
  600. if (parseInt(matches[1]) >= 14) {
  601. this._badOS = false;
  602. }
  603. }
  604. // Detect if we are running on a faulty buggy desktop OS.
  605. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  606. this._creationOptions = options;
  607. console.log(`Babylon.js v${ThinEngine.Version} - ${this.description}`);
  608. }
  609. private _rebuildInternalTextures(): void {
  610. let currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  611. for (var internalTexture of currentState) {
  612. internalTexture._rebuild();
  613. }
  614. }
  615. private _rebuildEffects(): void {
  616. for (var key in this._compiledEffects) {
  617. let effect = <Effect>this._compiledEffects[key];
  618. effect._prepareEffect();
  619. }
  620. Effect.ResetCache();
  621. }
  622. /**
  623. * Gets a boolean indicating if all created effects are ready
  624. * @returns true if all effects are ready
  625. */
  626. public areAllEffectsReady(): boolean {
  627. for (var key in this._compiledEffects) {
  628. let effect = <Effect>this._compiledEffects[key];
  629. if (!effect.isReady()) {
  630. return false;
  631. }
  632. }
  633. return true;
  634. }
  635. protected _rebuildBuffers(): void {
  636. // Uniforms
  637. for (var uniformBuffer of this._uniformBuffers) {
  638. uniformBuffer._rebuild();
  639. }
  640. }
  641. protected _initGLContext(): void {
  642. // Caps
  643. this._caps = {
  644. maxTexturesImageUnits: this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),
  645. maxCombinedTexturesImageUnits: this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),
  646. maxVertexTextureImageUnits: this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),
  647. maxTextureSize: this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),
  648. maxSamples: this._webGLVersion > 1 ? this._gl.getParameter(this._gl.MAX_SAMPLES) : 1,
  649. maxCubemapTextureSize: this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),
  650. maxRenderTextureSize: this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),
  651. maxVertexAttribs: this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),
  652. maxVaryingVectors: this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),
  653. maxFragmentUniformVectors: this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),
  654. maxVertexUniformVectors: this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),
  655. parallelShaderCompile: this._gl.getExtension('KHR_parallel_shader_compile'),
  656. standardDerivatives: this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null),
  657. maxAnisotropy: 1,
  658. astc: this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc'),
  659. bptc: this._gl.getExtension('EXT_texture_compression_bptc') || this._gl.getExtension('WEBKIT_EXT_texture_compression_bptc'),
  660. s3tc: this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc'),
  661. pvrtc: this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'),
  662. etc1: this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1'),
  663. etc2: this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  664. this._gl.getExtension('WEBGL_compressed_texture_es3_0'), // also a requirement of OpenGL ES 3
  665. textureAnisotropicFilterExtension: this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic'),
  666. uintIndices: this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null,
  667. fragmentDepthSupported: this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null,
  668. highPrecisionShaderSupported: false,
  669. timerQuery: this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query"),
  670. canUseTimestampForTimerQuery: false,
  671. drawBuffersExtension: false,
  672. maxMSAASamples: 1,
  673. colorBufferFloat: this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float'),
  674. textureFloat: (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false,
  675. textureHalfFloat: (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false,
  676. textureHalfFloatRender: false,
  677. textureFloatLinearFiltering: false,
  678. textureFloatRender: false,
  679. textureHalfFloatLinearFiltering: false,
  680. vertexArrayObject: false,
  681. instancedArrays: false,
  682. textureLOD: (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false,
  683. blendMinMax: false,
  684. multiview: this._gl.getExtension('OVR_multiview2'),
  685. oculusMultiview: this._gl.getExtension('OCULUS_multiview'),
  686. depthTextureExtension: false
  687. };
  688. // Infos
  689. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  690. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  691. if (rendererInfo != null) {
  692. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  693. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  694. }
  695. if (!this._glVendor) {
  696. this._glVendor = "Unknown vendor";
  697. }
  698. if (!this._glRenderer) {
  699. this._glRenderer = "Unknown renderer";
  700. }
  701. // Constants
  702. if (this._gl.HALF_FLOAT_OES !== 0x8D61) {
  703. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  704. }
  705. if (this._gl.RGBA16F !== 0x881A) {
  706. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  707. }
  708. if (this._gl.RGBA32F !== 0x8814) {
  709. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  710. }
  711. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  712. this._gl.DEPTH24_STENCIL8 = 35056;
  713. }
  714. // Extensions
  715. if (this._caps.timerQuery) {
  716. if (this._webGLVersion === 1) {
  717. this._gl.getQuery = (<any>this._caps.timerQuery).getQueryEXT.bind(this._caps.timerQuery);
  718. }
  719. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  720. }
  721. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  722. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  723. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  724. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  725. // Checks if some of the format renders first to allow the use of webgl inspector.
  726. if (this._webGLVersion > 1) {
  727. if (this._gl.HALF_FLOAT_OES !== 0x140B) {
  728. this._gl.HALF_FLOAT_OES = 0x140B;
  729. }
  730. }
  731. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  732. // Draw buffers
  733. if (this._webGLVersion > 1) {
  734. this._caps.drawBuffersExtension = true;
  735. this._caps.maxMSAASamples = this._gl.getParameter(this._gl.MAX_SAMPLES);
  736. } else {
  737. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  738. if (drawBuffersExtension !== null) {
  739. this._caps.drawBuffersExtension = true;
  740. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  741. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  742. for (var i = 0; i < 16; i++) {
  743. (<any>this._gl)["COLOR_ATTACHMENT" + i + "_WEBGL"] = (<any>drawBuffersExtension)["COLOR_ATTACHMENT" + i + "_WEBGL"];
  744. }
  745. }
  746. }
  747. // Depth Texture
  748. if (this._webGLVersion > 1) {
  749. this._caps.depthTextureExtension = true;
  750. } else {
  751. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  752. if (depthTextureExtension != null) {
  753. this._caps.depthTextureExtension = true;
  754. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  755. }
  756. }
  757. // Vertex array object
  758. if (this.disableVertexArrayObjects) {
  759. this._caps.vertexArrayObject = false;
  760. } else if (this._webGLVersion > 1) {
  761. this._caps.vertexArrayObject = true;
  762. } else {
  763. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  764. if (vertexArrayObjectExtension != null) {
  765. this._caps.vertexArrayObject = true;
  766. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  767. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  768. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  769. }
  770. }
  771. // Instances count
  772. if (this._webGLVersion > 1) {
  773. this._caps.instancedArrays = true;
  774. } else {
  775. var instanceExtension = <ANGLE_instanced_arrays>this._gl.getExtension('ANGLE_instanced_arrays');
  776. if (instanceExtension != null) {
  777. this._caps.instancedArrays = true;
  778. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  779. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  780. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  781. } else {
  782. this._caps.instancedArrays = false;
  783. }
  784. }
  785. if (this._gl.getShaderPrecisionFormat) {
  786. var vertex_highp = this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER, this._gl.HIGH_FLOAT);
  787. var fragment_highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  788. if (vertex_highp && fragment_highp) {
  789. this._caps.highPrecisionShaderSupported = vertex_highp.precision !== 0 && fragment_highp.precision !== 0;
  790. }
  791. }
  792. if (this._webGLVersion > 1) {
  793. this._caps.blendMinMax = true;
  794. }
  795. else {
  796. const blendMinMaxExtension = this._gl.getExtension('EXT_blend_minmax');
  797. if (blendMinMaxExtension != null) {
  798. this._caps.blendMinMax = true;
  799. this._gl.MAX = blendMinMaxExtension.MAX_EXT;
  800. this._gl.MIN = blendMinMaxExtension.MIN_EXT;
  801. }
  802. }
  803. // Depth buffer
  804. this._depthCullingState.depthTest = true;
  805. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  806. this._depthCullingState.depthMask = true;
  807. // Texture maps
  808. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  809. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  810. this._nextFreeTextureSlots.push(slot);
  811. }
  812. }
  813. /**
  814. * Gets version of the current webGL context
  815. */
  816. public get webGLVersion(): number {
  817. return this._webGLVersion;
  818. }
  819. /**
  820. * Gets a string identifying the name of the class
  821. * @returns "Engine" string
  822. */
  823. public getClassName(): string {
  824. return "ThinEngine";
  825. }
  826. /**
  827. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  828. */
  829. public get isStencilEnable(): boolean {
  830. return this._isStencilEnable;
  831. }
  832. /** @hidden */
  833. public _prepareWorkingCanvas(): void {
  834. if (this._workingCanvas) {
  835. return;
  836. }
  837. this._workingCanvas = CanvasGenerator.CreateCanvas(1, 1);
  838. let context = this._workingCanvas.getContext("2d");
  839. if (context) {
  840. this._workingContext = context;
  841. }
  842. }
  843. /**
  844. * Reset the texture cache to empty state
  845. */
  846. public resetTextureCache() {
  847. for (var key in this._boundTexturesCache) {
  848. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  849. continue;
  850. }
  851. this._boundTexturesCache[key] = null;
  852. }
  853. this._currentTextureChannel = -1;
  854. }
  855. /**
  856. * Gets an object containing information about the current webGL context
  857. * @returns an object containing the vender, the renderer and the version of the current webGL context
  858. */
  859. public getGlInfo() {
  860. return {
  861. vendor: this._glVendor,
  862. renderer: this._glRenderer,
  863. version: this._glVersion
  864. };
  865. }
  866. /**
  867. * Defines the hardware scaling level.
  868. * By default the hardware scaling level is computed from the window device ratio.
  869. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  870. * @param level defines the level to use
  871. */
  872. public setHardwareScalingLevel(level: number): void {
  873. this._hardwareScalingLevel = level;
  874. this.resize();
  875. }
  876. /**
  877. * Gets the current hardware scaling level.
  878. * By default the hardware scaling level is computed from the window device ratio.
  879. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  880. * @returns a number indicating the current hardware scaling level
  881. */
  882. public getHardwareScalingLevel(): number {
  883. return this._hardwareScalingLevel;
  884. }
  885. /**
  886. * Gets the list of loaded textures
  887. * @returns an array containing all loaded textures
  888. */
  889. public getLoadedTexturesCache(): InternalTexture[] {
  890. return this._internalTexturesCache;
  891. }
  892. /**
  893. * Gets the object containing all engine capabilities
  894. * @returns the EngineCapabilities object
  895. */
  896. public getCaps(): EngineCapabilities {
  897. return this._caps;
  898. }
  899. /**
  900. * stop executing a render loop function and remove it from the execution array
  901. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  902. */
  903. public stopRenderLoop(renderFunction?: () => void): void {
  904. if (!renderFunction) {
  905. this._activeRenderLoops = [];
  906. return;
  907. }
  908. var index = this._activeRenderLoops.indexOf(renderFunction);
  909. if (index >= 0) {
  910. this._activeRenderLoops.splice(index, 1);
  911. }
  912. }
  913. /** @hidden */
  914. public _renderLoop(): void {
  915. if (!this._contextWasLost) {
  916. var shouldRender = true;
  917. if (!this.renderEvenInBackground && this._windowIsBackground) {
  918. shouldRender = false;
  919. }
  920. if (shouldRender) {
  921. // Start new frame
  922. this.beginFrame();
  923. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  924. var renderFunction = this._activeRenderLoops[index];
  925. renderFunction();
  926. }
  927. // Present
  928. this.endFrame();
  929. }
  930. }
  931. if (this._activeRenderLoops.length > 0) {
  932. this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow());
  933. } else {
  934. this._renderingQueueLaunched = false;
  935. }
  936. }
  937. /**
  938. * Gets the HTML canvas attached with the current webGL context
  939. * @returns a HTML canvas
  940. */
  941. public getRenderingCanvas(): Nullable<HTMLCanvasElement> {
  942. return this._renderingCanvas;
  943. }
  944. /**
  945. * Gets host window
  946. * @returns the host window object
  947. */
  948. public getHostWindow(): Nullable<Window> {
  949. if (!DomManagement.IsWindowObjectExist()) {
  950. return null;
  951. }
  952. if (this._renderingCanvas && this._renderingCanvas.ownerDocument && this._renderingCanvas.ownerDocument.defaultView) {
  953. return this._renderingCanvas.ownerDocument.defaultView;
  954. }
  955. return window;
  956. }
  957. /**
  958. * Gets the current render width
  959. * @param useScreen defines if screen size must be used (or the current render target if any)
  960. * @returns a number defining the current render width
  961. */
  962. public getRenderWidth(useScreen = false): number {
  963. if (!useScreen && this._currentRenderTarget) {
  964. return this._currentRenderTarget.width;
  965. }
  966. return this._framebufferDimensionsObject ? this._framebufferDimensionsObject.framebufferWidth : this._gl.drawingBufferWidth;
  967. }
  968. /**
  969. * Gets the current render height
  970. * @param useScreen defines if screen size must be used (or the current render target if any)
  971. * @returns a number defining the current render height
  972. */
  973. public getRenderHeight(useScreen = false): number {
  974. if (!useScreen && this._currentRenderTarget) {
  975. return this._currentRenderTarget.height;
  976. }
  977. return this._framebufferDimensionsObject ? this._framebufferDimensionsObject.framebufferHeight : this._gl.drawingBufferHeight;
  978. }
  979. /**
  980. * Can be used to override the current requestAnimationFrame requester.
  981. * @hidden
  982. */
  983. protected _queueNewFrame(bindedRenderFunction: any, requester?: any): number {
  984. return ThinEngine.QueueNewFrame(bindedRenderFunction, requester);
  985. }
  986. /**
  987. * Register and execute a render loop. The engine can have more than one render function
  988. * @param renderFunction defines the function to continuously execute
  989. */
  990. public runRenderLoop(renderFunction: () => void): void {
  991. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  992. return;
  993. }
  994. this._activeRenderLoops.push(renderFunction);
  995. if (!this._renderingQueueLaunched) {
  996. this._renderingQueueLaunched = true;
  997. this._boundRenderFunction = this._renderLoop.bind(this);
  998. this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow());
  999. }
  1000. }
  1001. /**
  1002. * Clear the current render buffer or the current render target (if any is set up)
  1003. * @param color defines the color to use
  1004. * @param backBuffer defines if the back buffer must be cleared
  1005. * @param depth defines if the depth buffer must be cleared
  1006. * @param stencil defines if the stencil buffer must be cleared
  1007. */
  1008. public clear(color: Nullable<IColor4Like>, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  1009. this.applyStates();
  1010. var mode = 0;
  1011. if (backBuffer && color) {
  1012. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  1013. mode |= this._gl.COLOR_BUFFER_BIT;
  1014. }
  1015. if (depth) {
  1016. if (this.useReverseDepthBuffer) {
  1017. this._depthCullingState.depthFunc = this._gl.GREATER;
  1018. this._gl.clearDepth(0.0);
  1019. } else {
  1020. this._gl.clearDepth(1.0);
  1021. }
  1022. mode |= this._gl.DEPTH_BUFFER_BIT;
  1023. }
  1024. if (stencil) {
  1025. this._gl.clearStencil(0);
  1026. mode |= this._gl.STENCIL_BUFFER_BIT;
  1027. }
  1028. this._gl.clear(mode);
  1029. }
  1030. private _viewportCached = { x: 0, y: 0, z: 0, w: 0 };
  1031. /** @hidden */
  1032. public _viewport(x: number, y: number, width: number, height: number): void {
  1033. if (x !== this._viewportCached.x ||
  1034. y !== this._viewportCached.y ||
  1035. width !== this._viewportCached.z ||
  1036. height !== this._viewportCached.w) {
  1037. this._viewportCached.x = x;
  1038. this._viewportCached.y = y;
  1039. this._viewportCached.z = width;
  1040. this._viewportCached.w = height;
  1041. this._gl.viewport(x, y, width, height);
  1042. }
  1043. }
  1044. /**
  1045. * Set the WebGL's viewport
  1046. * @param viewport defines the viewport element to be used
  1047. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  1048. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  1049. */
  1050. public setViewport(viewport: IViewportLike, requiredWidth?: number, requiredHeight?: number): void {
  1051. var width = requiredWidth || this.getRenderWidth();
  1052. var height = requiredHeight || this.getRenderHeight();
  1053. var x = viewport.x || 0;
  1054. var y = viewport.y || 0;
  1055. this._cachedViewport = viewport;
  1056. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  1057. }
  1058. /**
  1059. * Begin a new frame
  1060. */
  1061. public beginFrame(): void {
  1062. }
  1063. /**
  1064. * Enf the current frame
  1065. */
  1066. public endFrame(): void {
  1067. // Force a flush in case we are using a bad OS.
  1068. if (this._badOS) {
  1069. this.flushFramebuffer();
  1070. }
  1071. }
  1072. /**
  1073. * Resize the view according to the canvas' size
  1074. */
  1075. public resize(): void {
  1076. let width: number;
  1077. let height: number;
  1078. if (DomManagement.IsWindowObjectExist()) {
  1079. width = this._renderingCanvas ? (this._renderingCanvas.clientWidth || this._renderingCanvas.width) : window.innerWidth;
  1080. height = this._renderingCanvas ? (this._renderingCanvas.clientHeight || this._renderingCanvas.height) : window.innerHeight;
  1081. } else {
  1082. width = this._renderingCanvas ? this._renderingCanvas.width : 100;
  1083. height = this._renderingCanvas ? this._renderingCanvas.height : 100;
  1084. }
  1085. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  1086. }
  1087. /**
  1088. * Force a specific size of the canvas
  1089. * @param width defines the new canvas' width
  1090. * @param height defines the new canvas' height
  1091. * @returns true if the size was changed
  1092. */
  1093. public setSize(width: number, height: number): boolean {
  1094. if (!this._renderingCanvas) {
  1095. return false;
  1096. }
  1097. width = width | 0;
  1098. height = height | 0;
  1099. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  1100. return false;
  1101. }
  1102. this._renderingCanvas.width = width;
  1103. this._renderingCanvas.height = height;
  1104. return true;
  1105. }
  1106. /**
  1107. * Binds the frame buffer to the specified texture.
  1108. * @param texture The texture to render to or null for the default canvas
  1109. * @param faceIndex The face of the texture to render to in case of cube texture
  1110. * @param requiredWidth The width of the target to render to
  1111. * @param requiredHeight The height of the target to render to
  1112. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  1113. * @param lodLevel defines the lod level to bind to the frame buffer
  1114. * @param layer defines the 2d array index to bind to frame buffer to
  1115. */
  1116. public bindFramebuffer(texture: InternalTexture, faceIndex: number = 0, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean, lodLevel = 0, layer = 0): void {
  1117. if (this._currentRenderTarget) {
  1118. this.unBindFramebuffer(this._currentRenderTarget);
  1119. }
  1120. this._currentRenderTarget = texture;
  1121. this._bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  1122. const gl = this._gl;
  1123. if (texture.is2DArray) {
  1124. gl.framebufferTextureLayer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, texture._webGLTexture, lodLevel, layer);
  1125. }
  1126. else if (texture.isCube) {
  1127. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  1128. }
  1129. const depthStencilTexture = texture._depthStencilTexture;
  1130. if (depthStencilTexture) {
  1131. const attachment = (depthStencilTexture._generateStencilBuffer) ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  1132. if (texture.is2DArray) {
  1133. gl.framebufferTextureLayer(gl.FRAMEBUFFER, attachment, depthStencilTexture._webGLTexture, lodLevel, layer);
  1134. }
  1135. else if (texture.isCube) {
  1136. gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  1137. }
  1138. else {
  1139. gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, lodLevel);
  1140. }
  1141. }
  1142. if (this._cachedViewport && !forceFullscreenViewport) {
  1143. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  1144. } else {
  1145. if (!requiredWidth) {
  1146. requiredWidth = texture.width;
  1147. if (lodLevel) {
  1148. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  1149. }
  1150. }
  1151. if (!requiredHeight) {
  1152. requiredHeight = texture.height;
  1153. if (lodLevel) {
  1154. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  1155. }
  1156. }
  1157. this._viewport(0, 0, requiredWidth, requiredHeight);
  1158. }
  1159. this.wipeCaches();
  1160. }
  1161. /** @hidden */
  1162. public _bindUnboundFramebuffer(framebuffer: Nullable<WebGLFramebuffer>) {
  1163. if (this._currentFramebuffer !== framebuffer) {
  1164. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  1165. this._currentFramebuffer = framebuffer;
  1166. }
  1167. }
  1168. /**
  1169. * Unbind the current render target texture from the webGL context
  1170. * @param texture defines the render target texture to unbind
  1171. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  1172. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  1173. */
  1174. public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1175. this._currentRenderTarget = null;
  1176. // If MSAA, we need to bitblt back to main texture
  1177. var gl = this._gl;
  1178. if (texture._MSAAFramebuffer) {
  1179. if (texture._textureArray) {
  1180. // This texture is part of a MRT texture, we need to treat all attachments
  1181. this.unBindMultiColorAttachmentFramebuffer(texture._textureArray!, disableGenerateMipMaps, onBeforeUnbind);
  1182. return;
  1183. }
  1184. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  1185. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  1186. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  1187. 0, 0, texture.width, texture.height,
  1188. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  1189. }
  1190. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  1191. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  1192. gl.generateMipmap(gl.TEXTURE_2D);
  1193. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1194. }
  1195. if (onBeforeUnbind) {
  1196. if (texture._MSAAFramebuffer) {
  1197. // Bind the correct framebuffer
  1198. this._bindUnboundFramebuffer(texture._framebuffer);
  1199. }
  1200. onBeforeUnbind();
  1201. }
  1202. this._bindUnboundFramebuffer(null);
  1203. }
  1204. /**
  1205. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  1206. */
  1207. public flushFramebuffer(): void {
  1208. this._gl.flush();
  1209. }
  1210. /**
  1211. * Unbind the current render target and bind the default framebuffer
  1212. */
  1213. public restoreDefaultFramebuffer(): void {
  1214. if (this._currentRenderTarget) {
  1215. this.unBindFramebuffer(this._currentRenderTarget);
  1216. } else {
  1217. this._bindUnboundFramebuffer(null);
  1218. }
  1219. if (this._cachedViewport) {
  1220. this.setViewport(this._cachedViewport);
  1221. }
  1222. this.wipeCaches();
  1223. }
  1224. // VBOs
  1225. /** @hidden */
  1226. protected _resetVertexBufferBinding(): void {
  1227. this.bindArrayBuffer(null);
  1228. this._cachedVertexBuffers = null;
  1229. }
  1230. /**
  1231. * Creates a vertex buffer
  1232. * @param data the data for the vertex buffer
  1233. * @returns the new WebGL static buffer
  1234. */
  1235. public createVertexBuffer(data: DataArray): DataBuffer {
  1236. return this._createVertexBuffer(data, this._gl.STATIC_DRAW);
  1237. }
  1238. private _createVertexBuffer(data: DataArray, usage: number): DataBuffer {
  1239. var vbo = this._gl.createBuffer();
  1240. if (!vbo) {
  1241. throw new Error("Unable to create vertex buffer");
  1242. }
  1243. let dataBuffer = new WebGLDataBuffer(vbo);
  1244. this.bindArrayBuffer(dataBuffer);
  1245. if (data instanceof Array) {
  1246. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  1247. } else {
  1248. this._gl.bufferData(this._gl.ARRAY_BUFFER, <ArrayBuffer>data, this._gl.STATIC_DRAW);
  1249. }
  1250. this._resetVertexBufferBinding();
  1251. dataBuffer.references = 1;
  1252. return dataBuffer;
  1253. }
  1254. /**
  1255. * Creates a dynamic vertex buffer
  1256. * @param data the data for the dynamic vertex buffer
  1257. * @returns the new WebGL dynamic buffer
  1258. */
  1259. public createDynamicVertexBuffer(data: DataArray): DataBuffer {
  1260. return this._createVertexBuffer(data, this._gl.DYNAMIC_DRAW);
  1261. }
  1262. protected _resetIndexBufferBinding(): void {
  1263. this.bindIndexBuffer(null);
  1264. this._cachedIndexBuffer = null;
  1265. }
  1266. /**
  1267. * Creates a new index buffer
  1268. * @param indices defines the content of the index buffer
  1269. * @param updatable defines if the index buffer must be updatable
  1270. * @returns a new webGL buffer
  1271. */
  1272. public createIndexBuffer(indices: IndicesArray, updatable?: boolean): DataBuffer {
  1273. var vbo = this._gl.createBuffer();
  1274. let dataBuffer = new WebGLDataBuffer(vbo!);
  1275. if (!vbo) {
  1276. throw new Error("Unable to create index buffer");
  1277. }
  1278. this.bindIndexBuffer(dataBuffer);
  1279. const data = this._normalizeIndexData(indices);
  1280. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, data, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  1281. this._resetIndexBufferBinding();
  1282. dataBuffer.references = 1;
  1283. dataBuffer.is32Bits = (data.BYTES_PER_ELEMENT === 4);
  1284. return dataBuffer;
  1285. }
  1286. protected _normalizeIndexData(indices: IndicesArray): Uint16Array | Uint32Array {
  1287. if (indices instanceof Uint16Array) {
  1288. return indices;
  1289. }
  1290. // Check 32 bit support
  1291. if (this._caps.uintIndices) {
  1292. if (indices instanceof Uint32Array) {
  1293. return indices;
  1294. } else {
  1295. // number[] or Int32Array, check if 32 bit is necessary
  1296. for (var index = 0; index < indices.length; index++) {
  1297. if (indices[index] >= 65535) {
  1298. return new Uint32Array(indices);
  1299. }
  1300. }
  1301. return new Uint16Array(indices);
  1302. }
  1303. }
  1304. // No 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  1305. return new Uint16Array(indices);
  1306. }
  1307. /**
  1308. * Bind a webGL buffer to the webGL context
  1309. * @param buffer defines the buffer to bind
  1310. */
  1311. public bindArrayBuffer(buffer: Nullable<DataBuffer>): void {
  1312. if (!this._vaoRecordInProgress) {
  1313. this._unbindVertexArrayObject();
  1314. }
  1315. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  1316. }
  1317. /**
  1318. * Bind a specific block at a given index in a specific shader program
  1319. * @param pipelineContext defines the pipeline context to use
  1320. * @param blockName defines the block name
  1321. * @param index defines the index where to bind the block
  1322. */
  1323. public bindUniformBlock(pipelineContext: IPipelineContext, blockName: string, index: number): void {
  1324. let program = (pipelineContext as WebGLPipelineContext).program!;
  1325. var uniformLocation = this._gl.getUniformBlockIndex(program, blockName);
  1326. this._gl.uniformBlockBinding(program, uniformLocation, index);
  1327. }
  1328. protected bindIndexBuffer(buffer: Nullable<DataBuffer>): void {
  1329. if (!this._vaoRecordInProgress) {
  1330. this._unbindVertexArrayObject();
  1331. }
  1332. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  1333. }
  1334. private bindBuffer(buffer: Nullable<DataBuffer>, target: number): void {
  1335. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  1336. this._gl.bindBuffer(target, buffer ? buffer.underlyingResource : null);
  1337. this._currentBoundBuffer[target] = buffer;
  1338. }
  1339. }
  1340. /**
  1341. * update the bound buffer with the given data
  1342. * @param data defines the data to update
  1343. */
  1344. public updateArrayBuffer(data: Float32Array): void {
  1345. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1346. }
  1347. private _vertexAttribPointer(buffer: DataBuffer, indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void {
  1348. var pointer = this._currentBufferPointers[indx];
  1349. if (!pointer) {
  1350. return;
  1351. }
  1352. var changed = false;
  1353. if (!pointer.active) {
  1354. changed = true;
  1355. pointer.active = true;
  1356. pointer.index = indx;
  1357. pointer.size = size;
  1358. pointer.type = type;
  1359. pointer.normalized = normalized;
  1360. pointer.stride = stride;
  1361. pointer.offset = offset;
  1362. pointer.buffer = buffer;
  1363. } else {
  1364. if (pointer.buffer !== buffer) { pointer.buffer = buffer; changed = true; }
  1365. if (pointer.size !== size) { pointer.size = size; changed = true; }
  1366. if (pointer.type !== type) { pointer.type = type; changed = true; }
  1367. if (pointer.normalized !== normalized) { pointer.normalized = normalized; changed = true; }
  1368. if (pointer.stride !== stride) { pointer.stride = stride; changed = true; }
  1369. if (pointer.offset !== offset) { pointer.offset = offset; changed = true; }
  1370. }
  1371. if (changed || this._vaoRecordInProgress) {
  1372. this.bindArrayBuffer(buffer);
  1373. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  1374. }
  1375. }
  1376. /** @hidden */
  1377. public _bindIndexBufferWithCache(indexBuffer: Nullable<DataBuffer>): void {
  1378. if (indexBuffer == null) {
  1379. return;
  1380. }
  1381. if (this._cachedIndexBuffer !== indexBuffer) {
  1382. this._cachedIndexBuffer = indexBuffer;
  1383. this.bindIndexBuffer(indexBuffer);
  1384. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  1385. }
  1386. }
  1387. private _bindVertexBuffersAttributes(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, effect: Effect): void {
  1388. var attributes = effect.getAttributesNames();
  1389. if (!this._vaoRecordInProgress) {
  1390. this._unbindVertexArrayObject();
  1391. }
  1392. this.unbindAllAttributes();
  1393. for (var index = 0; index < attributes.length; index++) {
  1394. var order = effect.getAttributeLocation(index);
  1395. if (order >= 0) {
  1396. var vertexBuffer = vertexBuffers[attributes[index]];
  1397. if (!vertexBuffer) {
  1398. continue;
  1399. }
  1400. this._gl.enableVertexAttribArray(order);
  1401. if (!this._vaoRecordInProgress) {
  1402. this._vertexAttribArraysEnabled[order] = true;
  1403. }
  1404. var buffer = vertexBuffer.getBuffer();
  1405. if (buffer) {
  1406. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  1407. if (vertexBuffer.getIsInstanced()) {
  1408. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  1409. if (!this._vaoRecordInProgress) {
  1410. this._currentInstanceLocations.push(order);
  1411. this._currentInstanceBuffers.push(buffer);
  1412. }
  1413. }
  1414. }
  1415. }
  1416. }
  1417. }
  1418. /**
  1419. * Records a vertex array object
  1420. * @see https://doc.babylonjs.com/features/webgl2#vertex-array-objects
  1421. * @param vertexBuffers defines the list of vertex buffers to store
  1422. * @param indexBuffer defines the index buffer to store
  1423. * @param effect defines the effect to store
  1424. * @returns the new vertex array object
  1425. */
  1426. public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: Nullable<DataBuffer>, effect: Effect): WebGLVertexArrayObject {
  1427. var vao = this._gl.createVertexArray();
  1428. this._vaoRecordInProgress = true;
  1429. this._gl.bindVertexArray(vao);
  1430. this._mustWipeVertexAttributes = true;
  1431. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1432. this.bindIndexBuffer(indexBuffer);
  1433. this._vaoRecordInProgress = false;
  1434. this._gl.bindVertexArray(null);
  1435. return vao;
  1436. }
  1437. /**
  1438. * Bind a specific vertex array object
  1439. * @see https://doc.babylonjs.com/features/webgl2#vertex-array-objects
  1440. * @param vertexArrayObject defines the vertex array object to bind
  1441. * @param indexBuffer defines the index buffer to bind
  1442. */
  1443. public bindVertexArrayObject(vertexArrayObject: WebGLVertexArrayObject, indexBuffer: Nullable<DataBuffer>): void {
  1444. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  1445. this._cachedVertexArrayObject = vertexArrayObject;
  1446. this._gl.bindVertexArray(vertexArrayObject);
  1447. this._cachedVertexBuffers = null;
  1448. this._cachedIndexBuffer = null;
  1449. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  1450. this._mustWipeVertexAttributes = true;
  1451. }
  1452. }
  1453. /**
  1454. * Bind webGl buffers directly to the webGL context
  1455. * @param vertexBuffer defines the vertex buffer to bind
  1456. * @param indexBuffer defines the index buffer to bind
  1457. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  1458. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  1459. * @param effect defines the effect associated with the vertex buffer
  1460. */
  1461. public bindBuffersDirectly(vertexBuffer: DataBuffer, indexBuffer: DataBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  1462. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  1463. this._cachedVertexBuffers = vertexBuffer;
  1464. this._cachedEffectForVertexBuffers = effect;
  1465. let attributesCount = effect.getAttributesCount();
  1466. this._unbindVertexArrayObject();
  1467. this.unbindAllAttributes();
  1468. var offset = 0;
  1469. for (var index = 0; index < attributesCount; index++) {
  1470. if (index < vertexDeclaration.length) {
  1471. var order = effect.getAttributeLocation(index);
  1472. if (order >= 0) {
  1473. this._gl.enableVertexAttribArray(order);
  1474. this._vertexAttribArraysEnabled[order] = true;
  1475. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  1476. }
  1477. offset += vertexDeclaration[index] * 4;
  1478. }
  1479. }
  1480. }
  1481. this._bindIndexBufferWithCache(indexBuffer);
  1482. }
  1483. private _unbindVertexArrayObject(): void {
  1484. if (!this._cachedVertexArrayObject) {
  1485. return;
  1486. }
  1487. this._cachedVertexArrayObject = null;
  1488. this._gl.bindVertexArray(null);
  1489. }
  1490. /**
  1491. * Bind a list of vertex buffers to the webGL context
  1492. * @param vertexBuffers defines the list of vertex buffers to bind
  1493. * @param indexBuffer defines the index buffer to bind
  1494. * @param effect defines the effect associated with the vertex buffers
  1495. */
  1496. public bindBuffers(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, indexBuffer: Nullable<DataBuffer>, effect: Effect): void {
  1497. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  1498. this._cachedVertexBuffers = vertexBuffers;
  1499. this._cachedEffectForVertexBuffers = effect;
  1500. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1501. }
  1502. this._bindIndexBufferWithCache(indexBuffer);
  1503. }
  1504. /**
  1505. * Unbind all instance attributes
  1506. */
  1507. public unbindInstanceAttributes() {
  1508. var boundBuffer;
  1509. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  1510. var instancesBuffer = this._currentInstanceBuffers[i];
  1511. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  1512. boundBuffer = instancesBuffer;
  1513. this.bindArrayBuffer(instancesBuffer);
  1514. }
  1515. var offsetLocation = this._currentInstanceLocations[i];
  1516. this._gl.vertexAttribDivisor(offsetLocation, 0);
  1517. }
  1518. this._currentInstanceBuffers.length = 0;
  1519. this._currentInstanceLocations.length = 0;
  1520. }
  1521. /**
  1522. * Release and free the memory of a vertex array object
  1523. * @param vao defines the vertex array object to delete
  1524. */
  1525. public releaseVertexArrayObject(vao: WebGLVertexArrayObject) {
  1526. this._gl.deleteVertexArray(vao);
  1527. }
  1528. /** @hidden */
  1529. public _releaseBuffer(buffer: DataBuffer): boolean {
  1530. buffer.references--;
  1531. if (buffer.references === 0) {
  1532. this._deleteBuffer(buffer);
  1533. return true;
  1534. }
  1535. return false;
  1536. }
  1537. protected _deleteBuffer(buffer: DataBuffer): void {
  1538. this._gl.deleteBuffer(buffer.underlyingResource);
  1539. }
  1540. /**
  1541. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  1542. * @param instancesBuffer defines the webGL buffer to update and bind
  1543. * @param data defines the data to store in the buffer
  1544. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  1545. */
  1546. public updateAndBindInstancesBuffer(instancesBuffer: DataBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  1547. this.bindArrayBuffer(instancesBuffer);
  1548. if (data) {
  1549. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1550. }
  1551. if ((<any>offsetLocations[0]).index !== undefined) {
  1552. this.bindInstancesBuffer(instancesBuffer, offsetLocations as any, true);
  1553. } else {
  1554. for (let index = 0; index < 4; index++) {
  1555. let offsetLocation = <number>offsetLocations[index];
  1556. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  1557. this._gl.enableVertexAttribArray(offsetLocation);
  1558. this._vertexAttribArraysEnabled[offsetLocation] = true;
  1559. }
  1560. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  1561. this._gl.vertexAttribDivisor(offsetLocation, 1);
  1562. this._currentInstanceLocations.push(offsetLocation);
  1563. this._currentInstanceBuffers.push(instancesBuffer);
  1564. }
  1565. }
  1566. }
  1567. /**
  1568. * Bind the content of a webGL buffer used with instantiation
  1569. * @param instancesBuffer defines the webGL buffer to bind
  1570. * @param attributesInfo defines the offsets or attributes information used to determine where data must be stored in the buffer
  1571. * @param computeStride defines Whether to compute the strides from the info or use the default 0
  1572. */
  1573. public bindInstancesBuffer(instancesBuffer: DataBuffer, attributesInfo: InstancingAttributeInfo[], computeStride = true): void {
  1574. this.bindArrayBuffer(instancesBuffer);
  1575. let stride = 0;
  1576. if (computeStride) {
  1577. for (let i = 0; i < attributesInfo.length; i++) {
  1578. let ai = attributesInfo[i];
  1579. stride += ai.attributeSize * 4;
  1580. }
  1581. }
  1582. for (let i = 0; i < attributesInfo.length; i++) {
  1583. let ai = attributesInfo[i];
  1584. if (ai.index === undefined) {
  1585. ai.index = this._currentEffect!.getAttributeLocationByName(ai.attributeName);
  1586. }
  1587. if (ai.index < 0) {
  1588. continue;
  1589. }
  1590. if (!this._vertexAttribArraysEnabled[ai.index]) {
  1591. this._gl.enableVertexAttribArray(ai.index);
  1592. this._vertexAttribArraysEnabled[ai.index] = true;
  1593. }
  1594. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attributeType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  1595. this._gl.vertexAttribDivisor(ai.index, ai.divisor === undefined ? 1 : ai.divisor);
  1596. this._currentInstanceLocations.push(ai.index);
  1597. this._currentInstanceBuffers.push(instancesBuffer);
  1598. }
  1599. }
  1600. /**
  1601. * Disable the instance attribute corresponding to the name in parameter
  1602. * @param name defines the name of the attribute to disable
  1603. */
  1604. public disableInstanceAttributeByName(name: string) {
  1605. if (!this._currentEffect) {
  1606. return;
  1607. }
  1608. const attributeLocation = this._currentEffect.getAttributeLocationByName(name);
  1609. this.disableInstanceAttribute(attributeLocation);
  1610. }
  1611. /**
  1612. * Disable the instance attribute corresponding to the location in parameter
  1613. * @param attributeLocation defines the attribute location of the attribute to disable
  1614. */
  1615. public disableInstanceAttribute(attributeLocation: number) {
  1616. let shouldClean = false;
  1617. let index: number;
  1618. while ((index = this._currentInstanceLocations.indexOf(attributeLocation)) !== -1) {
  1619. this._currentInstanceLocations.splice(index, 1);
  1620. this._currentInstanceBuffers.splice(index, 1);
  1621. shouldClean = true;
  1622. index = this._currentInstanceLocations.indexOf(attributeLocation);
  1623. }
  1624. if (shouldClean) {
  1625. this._gl.vertexAttribDivisor(attributeLocation, 0);
  1626. this.disableAttributeByIndex(attributeLocation);
  1627. }
  1628. }
  1629. /**
  1630. * Disable the attribute corresponding to the location in parameter
  1631. * @param attributeLocation defines the attribute location of the attribute to disable
  1632. */
  1633. public disableAttributeByIndex(attributeLocation: number) {
  1634. this._gl.disableVertexAttribArray(attributeLocation);
  1635. this._vertexAttribArraysEnabled[attributeLocation] = false;
  1636. this._currentBufferPointers[attributeLocation].active = false;
  1637. }
  1638. /**
  1639. * Send a draw order
  1640. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  1641. * @param indexStart defines the starting index
  1642. * @param indexCount defines the number of index to draw
  1643. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  1644. */
  1645. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  1646. this.drawElementsType(useTriangles ? Constants.MATERIAL_TriangleFillMode : Constants.MATERIAL_WireFrameFillMode, indexStart, indexCount, instancesCount);
  1647. }
  1648. /**
  1649. * Draw a list of points
  1650. * @param verticesStart defines the index of first vertex to draw
  1651. * @param verticesCount defines the count of vertices to draw
  1652. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  1653. */
  1654. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1655. this.drawArraysType(Constants.MATERIAL_PointFillMode, verticesStart, verticesCount, instancesCount);
  1656. }
  1657. /**
  1658. * Draw a list of unindexed primitives
  1659. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  1660. * @param verticesStart defines the index of first vertex to draw
  1661. * @param verticesCount defines the count of vertices to draw
  1662. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  1663. */
  1664. public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1665. this.drawArraysType(useTriangles ? Constants.MATERIAL_TriangleFillMode : Constants.MATERIAL_WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  1666. }
  1667. /**
  1668. * Draw a list of indexed primitives
  1669. * @param fillMode defines the primitive to use
  1670. * @param indexStart defines the starting index
  1671. * @param indexCount defines the number of index to draw
  1672. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  1673. */
  1674. public drawElementsType(fillMode: number, indexStart: number, indexCount: number, instancesCount?: number): void {
  1675. // Apply states
  1676. this.applyStates();
  1677. this._reportDrawCall();
  1678. // Render
  1679. const drawMode = this._drawMode(fillMode);
  1680. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  1681. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  1682. if (instancesCount) {
  1683. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  1684. } else {
  1685. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  1686. }
  1687. }
  1688. /**
  1689. * Draw a list of unindexed primitives
  1690. * @param fillMode defines the primitive to use
  1691. * @param verticesStart defines the index of first vertex to draw
  1692. * @param verticesCount defines the count of vertices to draw
  1693. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  1694. */
  1695. public drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1696. // Apply states
  1697. this.applyStates();
  1698. this._reportDrawCall();
  1699. const drawMode = this._drawMode(fillMode);
  1700. if (instancesCount) {
  1701. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  1702. } else {
  1703. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  1704. }
  1705. }
  1706. private _drawMode(fillMode: number): number {
  1707. switch (fillMode) {
  1708. // Triangle views
  1709. case Constants.MATERIAL_TriangleFillMode:
  1710. return this._gl.TRIANGLES;
  1711. case Constants.MATERIAL_PointFillMode:
  1712. return this._gl.POINTS;
  1713. case Constants.MATERIAL_WireFrameFillMode:
  1714. return this._gl.LINES;
  1715. // Draw modes
  1716. case Constants.MATERIAL_PointListDrawMode:
  1717. return this._gl.POINTS;
  1718. case Constants.MATERIAL_LineListDrawMode:
  1719. return this._gl.LINES;
  1720. case Constants.MATERIAL_LineLoopDrawMode:
  1721. return this._gl.LINE_LOOP;
  1722. case Constants.MATERIAL_LineStripDrawMode:
  1723. return this._gl.LINE_STRIP;
  1724. case Constants.MATERIAL_TriangleStripDrawMode:
  1725. return this._gl.TRIANGLE_STRIP;
  1726. case Constants.MATERIAL_TriangleFanDrawMode:
  1727. return this._gl.TRIANGLE_FAN;
  1728. default:
  1729. return this._gl.TRIANGLES;
  1730. }
  1731. }
  1732. /** @hidden */
  1733. protected _reportDrawCall() {
  1734. // Will be implemented by children
  1735. }
  1736. // Shaders
  1737. /** @hidden */
  1738. public _releaseEffect(effect: Effect): void {
  1739. if (this._compiledEffects[effect._key]) {
  1740. delete this._compiledEffects[effect._key];
  1741. this._deletePipelineContext(effect.getPipelineContext() as WebGLPipelineContext);
  1742. }
  1743. }
  1744. /** @hidden */
  1745. public _deletePipelineContext(pipelineContext: IPipelineContext): void {
  1746. let webGLPipelineContext = pipelineContext as WebGLPipelineContext;
  1747. if (webGLPipelineContext && webGLPipelineContext.program) {
  1748. webGLPipelineContext.program.__SPECTOR_rebuildProgram = null;
  1749. this._gl.deleteProgram(webGLPipelineContext.program);
  1750. }
  1751. }
  1752. /**
  1753. * Create a new effect (used to store vertex/fragment shaders)
  1754. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  1755. * @param attributesNamesOrOptions defines either a list of attribute names or an IEffectCreationOptions object
  1756. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  1757. * @param samplers defines an array of string used to represent textures
  1758. * @param defines defines the string containing the defines to use to compile the shaders
  1759. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  1760. * @param onCompiled defines a function to call when the effect creation is successful
  1761. * @param onError defines a function to call when the effect creation has failed
  1762. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  1763. * @returns the new Effect
  1764. */
  1765. public createEffect(baseName: any, attributesNamesOrOptions: string[] | IEffectCreationOptions, uniformsNamesOrEngine: string[] | ThinEngine, samplers?: string[], defines?: string,
  1766. fallbacks?: IEffectFallbacks,
  1767. onCompiled?: Nullable<(effect: Effect) => void>, onError?: Nullable<(effect: Effect, errors: string) => void>, indexParameters?: any): Effect {
  1768. var vertex = baseName.vertexElement || baseName.vertex || baseName.vertexToken || baseName.vertexSource || baseName;
  1769. var fragment = baseName.fragmentElement || baseName.fragment || baseName.fragmentToken || baseName.fragmentSource || baseName;
  1770. var name = vertex + "+" + fragment + "@" + (defines ? defines : (<IEffectCreationOptions>attributesNamesOrOptions).defines);
  1771. if (this._compiledEffects[name]) {
  1772. var compiledEffect = <Effect>this._compiledEffects[name];
  1773. if (onCompiled && compiledEffect.isReady()) {
  1774. onCompiled(compiledEffect);
  1775. }
  1776. return compiledEffect;
  1777. }
  1778. var effect = new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  1779. effect._key = name;
  1780. this._compiledEffects[name] = effect;
  1781. return effect;
  1782. }
  1783. protected static _ConcatenateShader(source: string, defines: Nullable<string>, shaderVersion: string = ""): string {
  1784. return shaderVersion + (defines ? defines + "\n" : "") + source;
  1785. }
  1786. private _compileShader(source: string, type: string, defines: Nullable<string>, shaderVersion: string): WebGLShader {
  1787. return this._compileRawShader(ThinEngine._ConcatenateShader(source, defines, shaderVersion), type);
  1788. }
  1789. private _compileRawShader(source: string, type: string): WebGLShader {
  1790. var gl = this._gl;
  1791. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  1792. if (!shader) {
  1793. throw new Error("Something went wrong while compile the shader.");
  1794. }
  1795. gl.shaderSource(shader, source);
  1796. gl.compileShader(shader);
  1797. return shader;
  1798. }
  1799. /** @hidden */
  1800. public _getShaderSource(shader: WebGLShader): Nullable<string> {
  1801. return this._gl.getShaderSource(shader);
  1802. }
  1803. /**
  1804. * Directly creates a webGL program
  1805. * @param pipelineContext defines the pipeline context to attach to
  1806. * @param vertexCode defines the vertex shader code to use
  1807. * @param fragmentCode defines the fragment shader code to use
  1808. * @param context defines the webGL context to use (if not set, the current one will be used)
  1809. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  1810. * @returns the new webGL program
  1811. */
  1812. public createRawShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  1813. context = context || this._gl;
  1814. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  1815. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  1816. return this._createShaderProgram(pipelineContext as WebGLPipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings);
  1817. }
  1818. /**
  1819. * Creates a webGL program
  1820. * @param pipelineContext defines the pipeline context to attach to
  1821. * @param vertexCode defines the vertex shader code to use
  1822. * @param fragmentCode defines the fragment shader code to use
  1823. * @param defines defines the string containing the defines to use to compile the shaders
  1824. * @param context defines the webGL context to use (if not set, the current one will be used)
  1825. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  1826. * @returns the new webGL program
  1827. */
  1828. public createShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, defines: Nullable<string>, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  1829. context = context || this._gl;
  1830. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  1831. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  1832. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  1833. return this._createShaderProgram(pipelineContext as WebGLPipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings);
  1834. }
  1835. /**
  1836. * Creates a new pipeline context
  1837. * @returns the new pipeline
  1838. */
  1839. public createPipelineContext(): IPipelineContext {
  1840. var pipelineContext = new WebGLPipelineContext();
  1841. pipelineContext.engine = this;
  1842. if (this._caps.parallelShaderCompile) {
  1843. pipelineContext.isParallelCompiled = true;
  1844. }
  1845. return pipelineContext;
  1846. }
  1847. protected _createShaderProgram(pipelineContext: WebGLPipelineContext, vertexShader: WebGLShader, fragmentShader: WebGLShader, context: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  1848. var shaderProgram = context.createProgram();
  1849. pipelineContext.program = shaderProgram;
  1850. if (!shaderProgram) {
  1851. throw new Error("Unable to create program");
  1852. }
  1853. context.attachShader(shaderProgram, vertexShader);
  1854. context.attachShader(shaderProgram, fragmentShader);
  1855. context.linkProgram(shaderProgram);
  1856. pipelineContext.context = context;
  1857. pipelineContext.vertexShader = vertexShader;
  1858. pipelineContext.fragmentShader = fragmentShader;
  1859. if (!pipelineContext.isParallelCompiled) {
  1860. this._finalizePipelineContext(pipelineContext);
  1861. }
  1862. return shaderProgram;
  1863. }
  1864. protected _finalizePipelineContext(pipelineContext: WebGLPipelineContext) {
  1865. const context = pipelineContext.context!;
  1866. const vertexShader = pipelineContext.vertexShader!;
  1867. const fragmentShader = pipelineContext.fragmentShader!;
  1868. const program = pipelineContext.program!;
  1869. var linked = context.getProgramParameter(program, context.LINK_STATUS);
  1870. if (!linked) { // Get more info
  1871. // Vertex
  1872. if (!this._gl.getShaderParameter(vertexShader, this._gl.COMPILE_STATUS)) {
  1873. const log = this._gl.getShaderInfoLog(vertexShader);
  1874. if (log) {
  1875. pipelineContext.vertexCompilationError = log;
  1876. throw new Error("VERTEX SHADER " + log);
  1877. }
  1878. }
  1879. // Fragment
  1880. if (!this._gl.getShaderParameter(fragmentShader, this._gl.COMPILE_STATUS)) {
  1881. const log = this._gl.getShaderInfoLog(fragmentShader);
  1882. if (log) {
  1883. pipelineContext.fragmentCompilationError = log;
  1884. throw new Error("FRAGMENT SHADER " + log);
  1885. }
  1886. }
  1887. var error = context.getProgramInfoLog(program);
  1888. if (error) {
  1889. pipelineContext.programLinkError = error;
  1890. throw new Error(error);
  1891. }
  1892. }
  1893. if (this.validateShaderPrograms) {
  1894. context.validateProgram(program);
  1895. var validated = context.getProgramParameter(program, context.VALIDATE_STATUS);
  1896. if (!validated) {
  1897. var error = context.getProgramInfoLog(program);
  1898. if (error) {
  1899. pipelineContext.programValidationError = error;
  1900. throw new Error(error);
  1901. }
  1902. }
  1903. }
  1904. context.deleteShader(vertexShader);
  1905. context.deleteShader(fragmentShader);
  1906. pipelineContext.vertexShader = undefined;
  1907. pipelineContext.fragmentShader = undefined;
  1908. if (pipelineContext.onCompiled) {
  1909. pipelineContext.onCompiled();
  1910. pipelineContext.onCompiled = undefined;
  1911. }
  1912. }
  1913. /** @hidden */
  1914. public _preparePipelineContext(pipelineContext: IPipelineContext, vertexSourceCode: string, fragmentSourceCode: string, createAsRaw: boolean,
  1915. rebuildRebind: any,
  1916. defines: Nullable<string>,
  1917. transformFeedbackVaryings: Nullable<string[]>) {
  1918. let webGLRenderingState = pipelineContext as WebGLPipelineContext;
  1919. if (createAsRaw) {
  1920. webGLRenderingState.program = this.createRawShaderProgram(webGLRenderingState, vertexSourceCode, fragmentSourceCode, undefined, transformFeedbackVaryings);
  1921. }
  1922. else {
  1923. webGLRenderingState.program = this.createShaderProgram(webGLRenderingState, vertexSourceCode, fragmentSourceCode, defines, undefined, transformFeedbackVaryings);
  1924. }
  1925. webGLRenderingState.program.__SPECTOR_rebuildProgram = rebuildRebind;
  1926. }
  1927. /** @hidden */
  1928. public _isRenderingStateCompiled(pipelineContext: IPipelineContext): boolean {
  1929. let webGLPipelineContext = pipelineContext as WebGLPipelineContext;
  1930. if (this._gl.getProgramParameter(webGLPipelineContext.program!, this._caps.parallelShaderCompile!.COMPLETION_STATUS_KHR)) {
  1931. this._finalizePipelineContext(webGLPipelineContext);
  1932. return true;
  1933. }
  1934. return false;
  1935. }
  1936. /** @hidden */
  1937. public _executeWhenRenderingStateIsCompiled(pipelineContext: IPipelineContext, action: () => void) {
  1938. let webGLPipelineContext = pipelineContext as WebGLPipelineContext;
  1939. if (!webGLPipelineContext.isParallelCompiled) {
  1940. action();
  1941. return;
  1942. }
  1943. let oldHandler = webGLPipelineContext.onCompiled;
  1944. if (oldHandler) {
  1945. webGLPipelineContext.onCompiled = () => {
  1946. oldHandler!();
  1947. action();
  1948. };
  1949. } else {
  1950. webGLPipelineContext.onCompiled = action;
  1951. }
  1952. }
  1953. /**
  1954. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  1955. * @param pipelineContext defines the pipeline context to use
  1956. * @param uniformsNames defines the list of uniform names
  1957. * @returns an array of webGL uniform locations
  1958. */
  1959. public getUniforms(pipelineContext: IPipelineContext, uniformsNames: string[]): Nullable<WebGLUniformLocation>[] {
  1960. var results = new Array<Nullable<WebGLUniformLocation>>();
  1961. let webGLPipelineContext = pipelineContext as WebGLPipelineContext;
  1962. for (var index = 0; index < uniformsNames.length; index++) {
  1963. results.push(this._gl.getUniformLocation(webGLPipelineContext.program!, uniformsNames[index]));
  1964. }
  1965. return results;
  1966. }
  1967. /**
  1968. * Gets the lsit of active attributes for a given webGL program
  1969. * @param pipelineContext defines the pipeline context to use
  1970. * @param attributesNames defines the list of attribute names to get
  1971. * @returns an array of indices indicating the offset of each attribute
  1972. */
  1973. public getAttributes(pipelineContext: IPipelineContext, attributesNames: string[]): number[] {
  1974. var results = [];
  1975. let webGLPipelineContext = pipelineContext as WebGLPipelineContext;
  1976. for (var index = 0; index < attributesNames.length; index++) {
  1977. try {
  1978. results.push(this._gl.getAttribLocation(webGLPipelineContext.program!, attributesNames[index]));
  1979. } catch (e) {
  1980. results.push(-1);
  1981. }
  1982. }
  1983. return results;
  1984. }
  1985. /**
  1986. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  1987. * @param effect defines the effect to activate
  1988. */
  1989. public enableEffect(effect: Nullable<Effect>): void {
  1990. if (!effect || effect === this._currentEffect) {
  1991. return;
  1992. }
  1993. // Use program
  1994. this.bindSamplers(effect);
  1995. this._currentEffect = effect;
  1996. if (effect.onBind) {
  1997. effect.onBind(effect);
  1998. }
  1999. if (effect._onBindObservable) {
  2000. effect._onBindObservable.notifyObservers(effect);
  2001. }
  2002. }
  2003. /**
  2004. * Set the value of an uniform to a number (int)
  2005. * @param uniform defines the webGL uniform location where to store the value
  2006. * @param value defines the int number to store
  2007. * @returns true if the value was set
  2008. */
  2009. public setInt(uniform: Nullable<WebGLUniformLocation>, value: number): boolean {
  2010. if (!uniform) {
  2011. return false;
  2012. }
  2013. this._gl.uniform1i(uniform, value);
  2014. return true;
  2015. }
  2016. /**
  2017. * Set the value of an uniform to an array of int32
  2018. * @param uniform defines the webGL uniform location where to store the value
  2019. * @param array defines the array of int32 to store
  2020. * @returns true if the value was set
  2021. */
  2022. public setIntArray(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): boolean {
  2023. if (!uniform) {
  2024. return false;
  2025. }
  2026. this._gl.uniform1iv(uniform, array);
  2027. return true;
  2028. }
  2029. /**
  2030. * Set the value of an uniform to an array of int32 (stored as vec2)
  2031. * @param uniform defines the webGL uniform location where to store the value
  2032. * @param array defines the array of int32 to store
  2033. * @returns true if the value was set
  2034. */
  2035. public setIntArray2(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): boolean {
  2036. if (!uniform || array.length % 2 !== 0) {
  2037. return false;
  2038. }
  2039. this._gl.uniform2iv(uniform, array);
  2040. return true;
  2041. }
  2042. /**
  2043. * Set the value of an uniform to an array of int32 (stored as vec3)
  2044. * @param uniform defines the webGL uniform location where to store the value
  2045. * @param array defines the array of int32 to store
  2046. * @returns true if the value was set
  2047. */
  2048. public setIntArray3(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): boolean {
  2049. if (!uniform || array.length % 3 !== 0) {
  2050. return false;
  2051. }
  2052. this._gl.uniform3iv(uniform, array);
  2053. return true;
  2054. }
  2055. /**
  2056. * Set the value of an uniform to an array of int32 (stored as vec4)
  2057. * @param uniform defines the webGL uniform location where to store the value
  2058. * @param array defines the array of int32 to store
  2059. * @returns true if the value was set
  2060. */
  2061. public setIntArray4(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): boolean {
  2062. if (!uniform || array.length % 4 !== 0) {
  2063. return false;
  2064. }
  2065. this._gl.uniform4iv(uniform, array);
  2066. return true;
  2067. }
  2068. /**
  2069. * Set the value of an uniform to an array of number
  2070. * @param uniform defines the webGL uniform location where to store the value
  2071. * @param array defines the array of number to store
  2072. * @returns true if the value was set
  2073. */
  2074. public setArray(uniform: Nullable<WebGLUniformLocation>, array: number[] | Float32Array): boolean {
  2075. if (!uniform) {
  2076. return false;
  2077. }
  2078. this._gl.uniform1fv(uniform, array);
  2079. return true;
  2080. }
  2081. /**
  2082. * Set the value of an uniform to an array of number (stored as vec2)
  2083. * @param uniform defines the webGL uniform location where to store the value
  2084. * @param array defines the array of number to store
  2085. * @returns true if the value was set
  2086. */
  2087. public setArray2(uniform: Nullable<WebGLUniformLocation>, array: number[] | Float32Array): boolean {
  2088. if (!uniform || array.length % 2 !== 0) {
  2089. return false;
  2090. }
  2091. this._gl.uniform2fv(uniform, <any>array);
  2092. return true;
  2093. }
  2094. /**
  2095. * Set the value of an uniform to an array of number (stored as vec3)
  2096. * @param uniform defines the webGL uniform location where to store the value
  2097. * @param array defines the array of number to store
  2098. * @returns true if the value was set
  2099. */
  2100. public setArray3(uniform: Nullable<WebGLUniformLocation>, array: number[] | Float32Array): boolean {
  2101. if (!uniform || array.length % 3 !== 0) {
  2102. return false;
  2103. }
  2104. this._gl.uniform3fv(uniform, <any>array);
  2105. return true;
  2106. }
  2107. /**
  2108. * Set the value of an uniform to an array of number (stored as vec4)
  2109. * @param uniform defines the webGL uniform location where to store the value
  2110. * @param array defines the array of number to store
  2111. * @returns true if the value was set
  2112. */
  2113. public setArray4(uniform: Nullable<WebGLUniformLocation>, array: number[] | Float32Array): boolean {
  2114. if (!uniform || array.length % 4 !== 0) {
  2115. return false;
  2116. }
  2117. this._gl.uniform4fv(uniform, <any>array);
  2118. return true;
  2119. }
  2120. /**
  2121. * Set the value of an uniform to an array of float32 (stored as matrices)
  2122. * @param uniform defines the webGL uniform location where to store the value
  2123. * @param matrices defines the array of float32 to store
  2124. * @returns true if the value was set
  2125. */
  2126. public setMatrices(uniform: Nullable<WebGLUniformLocation>, matrices: Float32Array): boolean {
  2127. if (!uniform) {
  2128. return false;
  2129. }
  2130. this._gl.uniformMatrix4fv(uniform, false, matrices);
  2131. return true;
  2132. }
  2133. /**
  2134. * Set the value of an uniform to a matrix (3x3)
  2135. * @param uniform defines the webGL uniform location where to store the value
  2136. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  2137. * @returns true if the value was set
  2138. */
  2139. public setMatrix3x3(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): boolean {
  2140. if (!uniform) {
  2141. return false;
  2142. }
  2143. this._gl.uniformMatrix3fv(uniform, false, matrix);
  2144. return true;
  2145. }
  2146. /**
  2147. * Set the value of an uniform to a matrix (2x2)
  2148. * @param uniform defines the webGL uniform location where to store the value
  2149. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  2150. * @returns true if the value was set
  2151. */
  2152. public setMatrix2x2(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): boolean {
  2153. if (!uniform) {
  2154. return false;
  2155. }
  2156. this._gl.uniformMatrix2fv(uniform, false, matrix);
  2157. return true;
  2158. }
  2159. /**
  2160. * Set the value of an uniform to a number (float)
  2161. * @param uniform defines the webGL uniform location where to store the value
  2162. * @param value defines the float number to store
  2163. * @returns true if the value was transfered
  2164. */
  2165. public setFloat(uniform: Nullable<WebGLUniformLocation>, value: number): boolean {
  2166. if (!uniform) {
  2167. return false;
  2168. }
  2169. this._gl.uniform1f(uniform, value);
  2170. return true;
  2171. }
  2172. /**
  2173. * Set the value of an uniform to a vec2
  2174. * @param uniform defines the webGL uniform location where to store the value
  2175. * @param x defines the 1st component of the value
  2176. * @param y defines the 2nd component of the value
  2177. * @returns true if the value was set
  2178. */
  2179. public setFloat2(uniform: Nullable<WebGLUniformLocation>, x: number, y: number): boolean {
  2180. if (!uniform) {
  2181. return false;
  2182. }
  2183. this._gl.uniform2f(uniform, x, y);
  2184. return true;
  2185. }
  2186. /**
  2187. * Set the value of an uniform to a vec3
  2188. * @param uniform defines the webGL uniform location where to store the value
  2189. * @param x defines the 1st component of the value
  2190. * @param y defines the 2nd component of the value
  2191. * @param z defines the 3rd component of the value
  2192. * @returns true if the value was set
  2193. */
  2194. public setFloat3(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number): boolean {
  2195. if (!uniform) {
  2196. return false;
  2197. }
  2198. this._gl.uniform3f(uniform, x, y, z);
  2199. return true;
  2200. }
  2201. /**
  2202. * Set the value of an uniform to a vec4
  2203. * @param uniform defines the webGL uniform location where to store the value
  2204. * @param x defines the 1st component of the value
  2205. * @param y defines the 2nd component of the value
  2206. * @param z defines the 3rd component of the value
  2207. * @param w defines the 4th component of the value
  2208. * @returns true if the value was set
  2209. */
  2210. public setFloat4(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number, w: number): boolean {
  2211. if (!uniform) {
  2212. return false;
  2213. }
  2214. this._gl.uniform4f(uniform, x, y, z, w);
  2215. return true;
  2216. }
  2217. // States
  2218. /**
  2219. * Apply all cached states (depth, culling, stencil and alpha)
  2220. */
  2221. public applyStates() {
  2222. this._depthCullingState.apply(this._gl);
  2223. this._stencilState.apply(this._gl);
  2224. this._alphaState.apply(this._gl);
  2225. if (this._colorWriteChanged) {
  2226. this._colorWriteChanged = false;
  2227. const enable = this._colorWrite;
  2228. this._gl.colorMask(enable, enable, enable, enable);
  2229. }
  2230. }
  2231. /**
  2232. * Enable or disable color writing
  2233. * @param enable defines the state to set
  2234. */
  2235. public setColorWrite(enable: boolean): void {
  2236. if (enable !== this._colorWrite) {
  2237. this._colorWriteChanged = true;
  2238. this._colorWrite = enable;
  2239. }
  2240. }
  2241. /**
  2242. * Gets a boolean indicating if color writing is enabled
  2243. * @returns the current color writing state
  2244. */
  2245. public getColorWrite(): boolean {
  2246. return this._colorWrite;
  2247. }
  2248. /**
  2249. * Gets the depth culling state manager
  2250. */
  2251. public get depthCullingState(): DepthCullingState {
  2252. return this._depthCullingState;
  2253. }
  2254. /**
  2255. * Gets the alpha state manager
  2256. */
  2257. public get alphaState(): AlphaState {
  2258. return this._alphaState;
  2259. }
  2260. /**
  2261. * Gets the stencil state manager
  2262. */
  2263. public get stencilState(): StencilState {
  2264. return this._stencilState;
  2265. }
  2266. // Textures
  2267. /**
  2268. * Clears the list of texture accessible through engine.
  2269. * This can help preventing texture load conflict due to name collision.
  2270. */
  2271. public clearInternalTexturesCache() {
  2272. this._internalTexturesCache = [];
  2273. }
  2274. /**
  2275. * Force the entire cache to be cleared
  2276. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  2277. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  2278. */
  2279. public wipeCaches(bruteForce?: boolean): void {
  2280. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  2281. return;
  2282. }
  2283. this._currentEffect = null;
  2284. this._viewportCached.x = 0;
  2285. this._viewportCached.y = 0;
  2286. this._viewportCached.z = 0;
  2287. this._viewportCached.w = 0;
  2288. // Done before in case we clean the attributes
  2289. this._unbindVertexArrayObject();
  2290. if (bruteForce) {
  2291. this._currentProgram = null;
  2292. this.resetTextureCache();
  2293. this._stencilState.reset();
  2294. this._depthCullingState.reset();
  2295. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  2296. this._alphaState.reset();
  2297. this._alphaMode = Constants.ALPHA_ADD;
  2298. this._alphaEquation = Constants.ALPHA_DISABLE;
  2299. this._colorWrite = true;
  2300. this._colorWriteChanged = true;
  2301. this._unpackFlipYCached = null;
  2302. this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, this._gl.NONE);
  2303. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  2304. this._mustWipeVertexAttributes = true;
  2305. this.unbindAllAttributes();
  2306. }
  2307. this._resetVertexBufferBinding();
  2308. this._cachedIndexBuffer = null;
  2309. this._cachedEffectForVertexBuffers = null;
  2310. this.bindIndexBuffer(null);
  2311. }
  2312. /** @hidden */
  2313. public _getSamplingParameters(samplingMode: number, generateMipMaps: boolean): { min: number; mag: number } {
  2314. var gl = this._gl;
  2315. var magFilter = gl.NEAREST;
  2316. var minFilter = gl.NEAREST;
  2317. switch (samplingMode) {
  2318. case Constants.TEXTURE_LINEAR_LINEAR_MIPNEAREST:
  2319. magFilter = gl.LINEAR;
  2320. if (generateMipMaps) {
  2321. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2322. } else {
  2323. minFilter = gl.LINEAR;
  2324. }
  2325. break;
  2326. case Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR:
  2327. magFilter = gl.LINEAR;
  2328. if (generateMipMaps) {
  2329. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2330. } else {
  2331. minFilter = gl.LINEAR;
  2332. }
  2333. break;
  2334. case Constants.TEXTURE_NEAREST_NEAREST_MIPLINEAR:
  2335. magFilter = gl.NEAREST;
  2336. if (generateMipMaps) {
  2337. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2338. } else {
  2339. minFilter = gl.NEAREST;
  2340. }
  2341. break;
  2342. case Constants.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  2343. magFilter = gl.NEAREST;
  2344. if (generateMipMaps) {
  2345. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  2346. } else {
  2347. minFilter = gl.NEAREST;
  2348. }
  2349. break;
  2350. case Constants.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  2351. magFilter = gl.NEAREST;
  2352. if (generateMipMaps) {
  2353. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2354. } else {
  2355. minFilter = gl.LINEAR;
  2356. }
  2357. break;
  2358. case Constants.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  2359. magFilter = gl.NEAREST;
  2360. if (generateMipMaps) {
  2361. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2362. } else {
  2363. minFilter = gl.LINEAR;
  2364. }
  2365. break;
  2366. case Constants.TEXTURE_NEAREST_LINEAR:
  2367. magFilter = gl.NEAREST;
  2368. minFilter = gl.LINEAR;
  2369. break;
  2370. case Constants.TEXTURE_NEAREST_NEAREST:
  2371. magFilter = gl.NEAREST;
  2372. minFilter = gl.NEAREST;
  2373. break;
  2374. case Constants.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  2375. magFilter = gl.LINEAR;
  2376. if (generateMipMaps) {
  2377. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  2378. } else {
  2379. minFilter = gl.NEAREST;
  2380. }
  2381. break;
  2382. case Constants.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  2383. magFilter = gl.LINEAR;
  2384. if (generateMipMaps) {
  2385. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2386. } else {
  2387. minFilter = gl.NEAREST;
  2388. }
  2389. break;
  2390. case Constants.TEXTURE_LINEAR_LINEAR:
  2391. magFilter = gl.LINEAR;
  2392. minFilter = gl.LINEAR;
  2393. break;
  2394. case Constants.TEXTURE_LINEAR_NEAREST:
  2395. magFilter = gl.LINEAR;
  2396. minFilter = gl.NEAREST;
  2397. break;
  2398. }
  2399. return {
  2400. min: minFilter,
  2401. mag: magFilter
  2402. };
  2403. }
  2404. /** @hidden */
  2405. public _createTexture(): WebGLTexture {
  2406. let texture = this._gl.createTexture();
  2407. if (!texture) {
  2408. throw new Error("Unable to create texture");
  2409. }
  2410. return texture;
  2411. }
  2412. /**
  2413. * Usually called from Texture.ts.
  2414. * Passed information to create a WebGLTexture
  2415. * @param url defines a value which contains one of the following:
  2416. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  2417. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  2418. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  2419. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  2420. * @param invertY when true, image is flipped when loaded. You probably want true. Certain compressed textures may invert this if their default is inverted (eg. ktx)
  2421. * @param scene needed for loading to the correct scene
  2422. * @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE)
  2423. * @param onLoad optional callback to be called upon successful completion
  2424. * @param onError optional callback to be called upon failure
  2425. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  2426. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  2427. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  2428. * @param forcedExtension defines the extension to use to pick the right loader
  2429. * @param mimeType defines an optional mime type
  2430. * @returns a InternalTexture for assignment back into BABYLON.Texture
  2431. */
  2432. public createTexture(url: Nullable<string>, noMipmap: boolean, invertY: boolean, scene: Nullable<ISceneLike>, samplingMode: number = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE,
  2433. onLoad: Nullable<() => void> = null, onError: Nullable<(message: string, exception: any) => void> = null,
  2434. buffer: Nullable<string | ArrayBuffer | ArrayBufferView | HTMLImageElement | Blob | ImageBitmap> = null, fallback: Nullable<InternalTexture> = null, format: Nullable<number> = null,
  2435. forcedExtension: Nullable<string> = null, mimeType?: string): InternalTexture {
  2436. url = url || "";
  2437. const fromData = url.substr(0, 5) === "data:";
  2438. const fromBlob = url.substr(0, 5) === "blob:";
  2439. const isBase64 = fromData && url.indexOf(";base64,") !== -1;
  2440. let texture = fallback ? fallback : new InternalTexture(this, InternalTextureSource.Url);
  2441. const originalUrl = url;
  2442. if (this._transformTextureUrl && !isBase64 && !fallback && !buffer) {
  2443. url = this._transformTextureUrl(url);
  2444. }
  2445. // establish the file extension, if possible
  2446. const lastDot = url.lastIndexOf('.');
  2447. let extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  2448. let loader: Nullable<IInternalTextureLoader> = null;
  2449. // Remove query string
  2450. let queryStringIndex = extension.indexOf("?");
  2451. if (queryStringIndex > -1) {
  2452. extension = extension.split("?")[0];
  2453. }
  2454. for (const availableLoader of ThinEngine._TextureLoaders) {
  2455. if (availableLoader.canLoad(extension, mimeType)) {
  2456. loader = availableLoader;
  2457. break;
  2458. }
  2459. }
  2460. if (scene) {
  2461. scene._addPendingData(texture);
  2462. }
  2463. texture.url = url;
  2464. texture.generateMipMaps = !noMipmap;
  2465. texture.samplingMode = samplingMode;
  2466. texture.invertY = invertY;
  2467. if (!this._doNotHandleContextLost) {
  2468. // Keep a link to the buffer only if we plan to handle context lost
  2469. texture._buffer = buffer;
  2470. }
  2471. let onLoadObserver: Nullable<Observer<InternalTexture>> = null;
  2472. if (onLoad && !fallback) {
  2473. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  2474. }
  2475. if (!fallback) { this._internalTexturesCache.push(texture); }
  2476. const onInternalError = (message?: string, exception?: any) => {
  2477. if (scene) {
  2478. scene._removePendingData(texture);
  2479. }
  2480. if (url === originalUrl) {
  2481. if (onLoadObserver) {
  2482. texture.onLoadedObservable.remove(onLoadObserver);
  2483. }
  2484. if (EngineStore.UseFallbackTexture) {
  2485. this.createTexture(EngineStore.FallbackTexture, noMipmap, texture.invertY, scene, samplingMode, null, onError, buffer, texture);
  2486. }
  2487. if (onError) {
  2488. onError((message || "Unknown error") + (EngineStore.UseFallbackTexture ? " - Fallback texture was used" : ""), exception);
  2489. }
  2490. }
  2491. else {
  2492. // fall back to the original url if the transformed url fails to load
  2493. Logger.Warn(`Failed to load ${url}, falling back to ${originalUrl}`);
  2494. this.createTexture(originalUrl, noMipmap, texture.invertY, scene, samplingMode, onLoad, onError, buffer, texture, format, forcedExtension, mimeType);
  2495. }
  2496. };
  2497. // processing for non-image formats
  2498. if (loader) {
  2499. const callback = (data: ArrayBufferView) => {
  2500. loader!.loadData(data, texture, (width: number, height: number, loadMipmap: boolean, isCompressed: boolean, done: () => void, loadFailed) => {
  2501. if (loadFailed) {
  2502. onInternalError("TextureLoader failed to load data");
  2503. } else {
  2504. this._prepareWebGLTexture(texture, scene, width, height, texture.invertY, !loadMipmap, isCompressed, () => {
  2505. done();
  2506. return false;
  2507. }, samplingMode);
  2508. }
  2509. });
  2510. };
  2511. if (!buffer) {
  2512. this._loadFile(url, (data) => callback(new Uint8Array(data as ArrayBuffer)), undefined, scene ? scene.offlineProvider : undefined, true, (request?: IWebRequest, exception?: any) => {
  2513. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  2514. });
  2515. } else {
  2516. if (buffer instanceof ArrayBuffer) {
  2517. callback(new Uint8Array(buffer));
  2518. }
  2519. else if (ArrayBuffer.isView(buffer)) {
  2520. callback(buffer);
  2521. }
  2522. else {
  2523. if (onError) {
  2524. onError("Unable to load: only ArrayBuffer or ArrayBufferView is supported", null);
  2525. }
  2526. }
  2527. }
  2528. } else {
  2529. const onload = (img: HTMLImageElement | ImageBitmap) => {
  2530. if (fromBlob && !this._doNotHandleContextLost) {
  2531. // We need to store the image if we need to rebuild the texture
  2532. // in case of a webgl context lost
  2533. texture._buffer = img;
  2534. }
  2535. this._prepareWebGLTexture(texture, scene, img.width, img.height, texture.invertY, noMipmap, false, (potWidth, potHeight, continuationCallback) => {
  2536. let gl = this._gl;
  2537. var isPot = (img.width === potWidth && img.height === potHeight);
  2538. let internalFormat = format ? this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  2539. if (isPot) {
  2540. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  2541. return false;
  2542. }
  2543. let maxTextureSize = this._caps.maxTextureSize;
  2544. if (img.width > maxTextureSize || img.height > maxTextureSize || !this._supportsHardwareTextureRescaling) {
  2545. this._prepareWorkingCanvas();
  2546. if (!this._workingCanvas || !this._workingContext) {
  2547. return false;
  2548. }
  2549. this._workingCanvas.width = potWidth;
  2550. this._workingCanvas.height = potHeight;
  2551. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  2552. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  2553. texture.width = potWidth;
  2554. texture.height = potHeight;
  2555. return false;
  2556. } else {
  2557. // Using shaders when possible to rescale because canvas.drawImage is lossy
  2558. let source = new InternalTexture(this, InternalTextureSource.Temp);
  2559. this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  2560. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  2561. this._rescaleTexture(source, texture, scene, internalFormat, () => {
  2562. this._releaseTexture(source);
  2563. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  2564. continuationCallback();
  2565. });
  2566. }
  2567. return true;
  2568. }, samplingMode);
  2569. };
  2570. if (!fromData || isBase64) {
  2571. if (buffer && ((<HTMLImageElement>buffer).decoding || (<ImageBitmap>buffer).close)) {
  2572. onload(<HTMLImageElement>buffer);
  2573. } else {
  2574. ThinEngine._FileToolsLoadImage(url, onload, onInternalError, scene ? scene.offlineProvider : null, mimeType);
  2575. }
  2576. }
  2577. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || ArrayBuffer.isView(buffer) || buffer instanceof Blob) {
  2578. ThinEngine._FileToolsLoadImage(buffer, onload, onInternalError, scene ? scene.offlineProvider : null, mimeType);
  2579. }
  2580. else if (buffer) {
  2581. onload(buffer);
  2582. }
  2583. }
  2584. return texture;
  2585. }
  2586. /**
  2587. * Loads an image as an HTMLImageElement.
  2588. * @param input url string, ArrayBuffer, or Blob to load
  2589. * @param onLoad callback called when the image successfully loads
  2590. * @param onError callback called when the image fails to load
  2591. * @param offlineProvider offline provider for caching
  2592. * @param mimeType optional mime type
  2593. * @returns the HTMLImageElement of the loaded image
  2594. * @hidden
  2595. */
  2596. public static _FileToolsLoadImage(input: string | ArrayBuffer | ArrayBufferView | Blob, onLoad: (img: HTMLImageElement | ImageBitmap) => void, onError: (message?: string, exception?: any) => void, offlineProvider: Nullable<IOfflineProvider>, mimeType?: string): Nullable<HTMLImageElement> {
  2597. throw _DevTools.WarnImport("FileTools");
  2598. }
  2599. /**
  2600. * @hidden
  2601. */
  2602. public _rescaleTexture(source: InternalTexture, destination: InternalTexture, scene: Nullable<any>, internalFormat: number, onComplete: () => void): void {
  2603. }
  2604. /**
  2605. * Creates a raw texture
  2606. * @param data defines the data to store in the texture
  2607. * @param width defines the width of the texture
  2608. * @param height defines the height of the texture
  2609. * @param format defines the format of the data
  2610. * @param generateMipMaps defines if the engine should generate the mip levels
  2611. * @param invertY defines if data must be stored with Y axis inverted
  2612. * @param samplingMode defines the required sampling mode (Texture.NEAREST_SAMPLINGMODE by default)
  2613. * @param compression defines the compression used (null by default)
  2614. * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default)
  2615. * @returns the raw texture inside an InternalTexture
  2616. */
  2617. public createRawTexture(data: Nullable<ArrayBufferView>, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null, type: number = Constants.TEXTURETYPE_UNSIGNED_INT): InternalTexture {
  2618. throw _DevTools.WarnImport("Engine.RawTexture");
  2619. }
  2620. /**
  2621. * Creates a new raw cube texture
  2622. * @param data defines the array of data to use to create each face
  2623. * @param size defines the size of the textures
  2624. * @param format defines the format of the data
  2625. * @param type defines the type of the data (like Engine.TEXTURETYPE_UNSIGNED_INT)
  2626. * @param generateMipMaps defines if the engine should generate the mip levels
  2627. * @param invertY defines if data must be stored with Y axis inverted
  2628. * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
  2629. * @param compression defines the compression used (null by default)
  2630. * @returns the cube texture as an InternalTexture
  2631. */
  2632. public createRawCubeTexture(data: Nullable<ArrayBufferView[]>, size: number, format: number, type: number,
  2633. generateMipMaps: boolean, invertY: boolean, samplingMode: number,
  2634. compression: Nullable<string> = null): InternalTexture {
  2635. throw _DevTools.WarnImport("Engine.RawTexture");
  2636. }
  2637. /**
  2638. * Creates a new raw 3D texture
  2639. * @param data defines the data used to create the texture
  2640. * @param width defines the width of the texture
  2641. * @param height defines the height of the texture
  2642. * @param depth defines the depth of the texture
  2643. * @param format defines the format of the texture
  2644. * @param generateMipMaps defines if the engine must generate mip levels
  2645. * @param invertY defines if data must be stored with Y axis inverted
  2646. * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
  2647. * @param compression defines the compressed used (can be null)
  2648. * @param textureType defines the compressed used (can be null)
  2649. * @returns a new raw 3D texture (stored in an InternalTexture)
  2650. */
  2651. public createRawTexture3D(data: Nullable<ArrayBufferView>, width: number, height: number, depth: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null, textureType = Constants.TEXTURETYPE_UNSIGNED_INT): InternalTexture {
  2652. throw _DevTools.WarnImport("Engine.RawTexture");
  2653. }
  2654. /**
  2655. * Creates a new raw 2D array texture
  2656. * @param data defines the data used to create the texture
  2657. * @param width defines the width of the texture
  2658. * @param height defines the height of the texture
  2659. * @param depth defines the number of layers of the texture
  2660. * @param format defines the format of the texture
  2661. * @param generateMipMaps defines if the engine must generate mip levels
  2662. * @param invertY defines if data must be stored with Y axis inverted
  2663. * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
  2664. * @param compression defines the compressed used (can be null)
  2665. * @param textureType defines the compressed used (can be null)
  2666. * @returns a new raw 2D array texture (stored in an InternalTexture)
  2667. */
  2668. public createRawTexture2DArray(data: Nullable<ArrayBufferView>, width: number, height: number, depth: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null, textureType = Constants.TEXTURETYPE_UNSIGNED_INT): InternalTexture {
  2669. throw _DevTools.WarnImport("Engine.RawTexture");
  2670. }
  2671. private _unpackFlipYCached: Nullable<boolean> = null;
  2672. /**
  2673. * In case you are sharing the context with other applications, it might
  2674. * be interested to not cache the unpack flip y state to ensure a consistent
  2675. * value would be set.
  2676. */
  2677. public enableUnpackFlipYCached = true;
  2678. /** @hidden */
  2679. public _unpackFlipY(value: boolean): void {
  2680. if (this._unpackFlipYCached !== value) {
  2681. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  2682. if (this.enableUnpackFlipYCached) {
  2683. this._unpackFlipYCached = value;
  2684. }
  2685. }
  2686. }
  2687. /** @hidden */
  2688. public _getUnpackAlignement(): number {
  2689. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  2690. }
  2691. private _getTextureTarget(texture: InternalTexture): number {
  2692. if (texture.isCube) {
  2693. return this._gl.TEXTURE_CUBE_MAP;
  2694. } else if (texture.is3D) {
  2695. return this._gl.TEXTURE_3D;
  2696. } else if (texture.is2DArray || texture.isMultiview) {
  2697. return this._gl.TEXTURE_2D_ARRAY;
  2698. }
  2699. return this._gl.TEXTURE_2D;
  2700. }
  2701. /**
  2702. * Update the sampling mode of a given texture
  2703. * @param samplingMode defines the required sampling mode
  2704. * @param texture defines the texture to update
  2705. * @param generateMipMaps defines whether to generate mipmaps for the texture
  2706. */
  2707. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture, generateMipMaps: boolean = false): void {
  2708. const target = this._getTextureTarget(texture);
  2709. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps || generateMipMaps);
  2710. this._setTextureParameterInteger(target, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  2711. this._setTextureParameterInteger(target, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2712. if (generateMipMaps) {
  2713. texture.generateMipMaps = true;
  2714. this._gl.generateMipmap(target);
  2715. }
  2716. this._bindTextureDirectly(target, null);
  2717. texture.samplingMode = samplingMode;
  2718. }
  2719. /**
  2720. * Update the sampling mode of a given texture
  2721. * @param texture defines the texture to update
  2722. * @param wrapU defines the texture wrap mode of the u coordinates
  2723. * @param wrapV defines the texture wrap mode of the v coordinates
  2724. * @param wrapR defines the texture wrap mode of the r coordinates
  2725. */
  2726. public updateTextureWrappingMode(texture: InternalTexture, wrapU: Nullable<number>, wrapV: Nullable<number> = null, wrapR: Nullable<number> = null): void {
  2727. const target = this._getTextureTarget(texture);
  2728. if (wrapU !== null) {
  2729. this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(wrapU), texture);
  2730. texture._cachedWrapU = wrapU;
  2731. }
  2732. if (wrapV !== null) {
  2733. this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(wrapV), texture);
  2734. texture._cachedWrapV = wrapV;
  2735. }
  2736. if ((texture.is2DArray || texture.is3D) && (wrapR !== null)) {
  2737. this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(wrapR), texture);
  2738. texture._cachedWrapR = wrapR;
  2739. }
  2740. this._bindTextureDirectly(target, null);
  2741. }
  2742. /** @hidden */
  2743. public _setupDepthStencilTexture(internalTexture: InternalTexture, size: number | { width: number, height: number, layers?: number }, generateStencil: boolean, bilinearFiltering: boolean, comparisonFunction: number): void {
  2744. const width = (<{ width: number, height: number, layers?: number }>size).width || <number>size;
  2745. const height = (<{ width: number, height: number, layers?: number }>size).height || <number>size;
  2746. const layers = (<{ width: number, height: number, layers?: number }>size).layers || 0;
  2747. internalTexture.baseWidth = width;
  2748. internalTexture.baseHeight = height;
  2749. internalTexture.width = width;
  2750. internalTexture.height = height;
  2751. internalTexture.is2DArray = layers > 0;
  2752. internalTexture.depth = layers;
  2753. internalTexture.isReady = true;
  2754. internalTexture.samples = 1;
  2755. internalTexture.generateMipMaps = false;
  2756. internalTexture._generateDepthBuffer = true;
  2757. internalTexture._generateStencilBuffer = generateStencil;
  2758. internalTexture.samplingMode = bilinearFiltering ? Constants.TEXTURE_BILINEAR_SAMPLINGMODE : Constants.TEXTURE_NEAREST_SAMPLINGMODE;
  2759. internalTexture.type = Constants.TEXTURETYPE_UNSIGNED_INT;
  2760. internalTexture._comparisonFunction = comparisonFunction;
  2761. const gl = this._gl;
  2762. const target = this._getTextureTarget(internalTexture);
  2763. const samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  2764. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  2765. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  2766. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2767. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2768. if (comparisonFunction === 0) {
  2769. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Constants.LEQUAL);
  2770. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  2771. }
  2772. else {
  2773. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  2774. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  2775. }
  2776. }
  2777. /** @hidden */
  2778. public _uploadCompressedDataToTextureDirectly(texture: InternalTexture, internalFormat: number, width: number, height: number, data: ArrayBufferView, faceIndex: number = 0, lod: number = 0) {
  2779. var gl = this._gl;
  2780. var target = gl.TEXTURE_2D;
  2781. if (texture.isCube) {
  2782. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  2783. }
  2784. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, <DataView>data);
  2785. }
  2786. /** @hidden */
  2787. public _uploadDataToTextureDirectly(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0, babylonInternalFormat?: number, useTextureWidthAndHeight = false): void {
  2788. var gl = this._gl;
  2789. var textureType = this._getWebGLTextureType(texture.type);
  2790. var format = this._getInternalFormat(texture.format);
  2791. var internalFormat = babylonInternalFormat === undefined ? this._getRGBABufferInternalSizedFormat(texture.type, texture.format) : this._getInternalFormat(babylonInternalFormat);
  2792. this._unpackFlipY(texture.invertY);
  2793. var target = gl.TEXTURE_2D;
  2794. if (texture.isCube) {
  2795. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  2796. }
  2797. const lodMaxWidth = Math.round(Math.log(texture.width) * Math.LOG2E);
  2798. const lodMaxHeight = Math.round(Math.log(texture.height) * Math.LOG2E);
  2799. const width = useTextureWidthAndHeight ? texture.width : Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  2800. const height = useTextureWidthAndHeight ? texture.height : Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  2801. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  2802. }
  2803. /**
  2804. * Update a portion of an internal texture
  2805. * @param texture defines the texture to update
  2806. * @param imageData defines the data to store into the texture
  2807. * @param xOffset defines the x coordinates of the update rectangle
  2808. * @param yOffset defines the y coordinates of the update rectangle
  2809. * @param width defines the width of the update rectangle
  2810. * @param height defines the height of the update rectangle
  2811. * @param faceIndex defines the face index if texture is a cube (0 by default)
  2812. * @param lod defines the lod level to update (0 by default)
  2813. */
  2814. public updateTextureData(texture: InternalTexture, imageData: ArrayBufferView, xOffset: number, yOffset: number, width: number, height: number, faceIndex: number = 0, lod: number = 0): void {
  2815. var gl = this._gl;
  2816. var textureType = this._getWebGLTextureType(texture.type);
  2817. var format = this._getInternalFormat(texture.format);
  2818. this._unpackFlipY(texture.invertY);
  2819. var target = gl.TEXTURE_2D;
  2820. if (texture.isCube) {
  2821. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  2822. }
  2823. gl.texSubImage2D(target, lod, xOffset, yOffset, width, height, format, textureType, imageData);
  2824. }
  2825. /** @hidden */
  2826. public _uploadArrayBufferViewToTexture(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  2827. var gl = this._gl;
  2828. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  2829. this._bindTextureDirectly(bindTarget, texture, true);
  2830. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  2831. this._bindTextureDirectly(bindTarget, null, true);
  2832. }
  2833. protected _prepareWebGLTextureContinuation(texture: InternalTexture, scene: Nullable<ISceneLike>, noMipmap: boolean, isCompressed: boolean, samplingMode: number): void {
  2834. var gl = this._gl;
  2835. if (!gl) {
  2836. return;
  2837. }
  2838. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  2839. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2840. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2841. if (!noMipmap && !isCompressed) {
  2842. gl.generateMipmap(gl.TEXTURE_2D);
  2843. }
  2844. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2845. // this.resetTextureCache();
  2846. if (scene) {
  2847. scene._removePendingData(texture);
  2848. }
  2849. texture.onLoadedObservable.notifyObservers(texture);
  2850. texture.onLoadedObservable.clear();
  2851. }
  2852. private _prepareWebGLTexture(texture: InternalTexture, scene: Nullable<ISceneLike>, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  2853. processFunction: (width: number, height: number, continuationCallback: () => void) => boolean, samplingMode: number = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE): void {
  2854. var maxTextureSize = this.getCaps().maxTextureSize;
  2855. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? ThinEngine.GetExponentOfTwo(width, maxTextureSize) : width);
  2856. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? ThinEngine.GetExponentOfTwo(height, maxTextureSize) : height);
  2857. var gl = this._gl;
  2858. if (!gl) {
  2859. return;
  2860. }
  2861. if (!texture._webGLTexture) {
  2862. // this.resetTextureCache();
  2863. if (scene) {
  2864. scene._removePendingData(texture);
  2865. }
  2866. return;
  2867. }
  2868. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  2869. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  2870. texture.baseWidth = width;
  2871. texture.baseHeight = height;
  2872. texture.width = potWidth;
  2873. texture.height = potHeight;
  2874. texture.isReady = true;
  2875. if (processFunction(potWidth, potHeight, () => {
  2876. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  2877. })) {
  2878. // Returning as texture needs extra async steps
  2879. return;
  2880. }
  2881. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  2882. }
  2883. /** @hidden */
  2884. public _setupFramebufferDepthAttachments(generateStencilBuffer: boolean, generateDepthBuffer: boolean, width: number, height: number, samples = 1): Nullable<WebGLRenderbuffer> {
  2885. var gl = this._gl;
  2886. // Create the depth/stencil buffer
  2887. if (generateStencilBuffer && generateDepthBuffer) {
  2888. return this._getDepthStencilBuffer(width, height, samples, gl.DEPTH_STENCIL, gl.DEPTH24_STENCIL8, gl.DEPTH_STENCIL_ATTACHMENT);
  2889. }
  2890. if (generateDepthBuffer) {
  2891. let depthFormat = gl.DEPTH_COMPONENT16;
  2892. if (this._webGLVersion > 1) {
  2893. depthFormat = gl.DEPTH_COMPONENT32F;
  2894. }
  2895. return this._getDepthStencilBuffer(width, height, samples, depthFormat, depthFormat, gl.DEPTH_ATTACHMENT);
  2896. }
  2897. if (generateStencilBuffer) {
  2898. return this._getDepthStencilBuffer(width, height, samples, gl.STENCIL_INDEX8, gl.STENCIL_INDEX8, gl.STENCIL_ATTACHMENT);
  2899. }
  2900. return null;
  2901. }
  2902. private _getDepthStencilBuffer = (width: number, height: number, samples: number, internalFormat: number, msInternalFormat: number, attachment: number) => {
  2903. var gl = this._gl;
  2904. const depthStencilBuffer = gl.createRenderbuffer();
  2905. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  2906. if (samples > 1 && gl.renderbufferStorageMultisample) {
  2907. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, msInternalFormat, width, height);
  2908. } else {
  2909. gl.renderbufferStorage(gl.RENDERBUFFER, internalFormat, width, height);
  2910. }
  2911. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, depthStencilBuffer);
  2912. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2913. return depthStencilBuffer;
  2914. }
  2915. /** @hidden */
  2916. public _releaseFramebufferObjects(texture: InternalTexture): void {
  2917. var gl = this._gl;
  2918. if (texture._framebuffer) {
  2919. gl.deleteFramebuffer(texture._framebuffer);
  2920. texture._framebuffer = null;
  2921. }
  2922. if (texture._depthStencilBuffer) {
  2923. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  2924. texture._depthStencilBuffer = null;
  2925. }
  2926. if (texture._MSAAFramebuffer) {
  2927. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  2928. texture._MSAAFramebuffer = null;
  2929. }
  2930. if (texture._MSAARenderBuffer) {
  2931. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  2932. texture._MSAARenderBuffer = null;
  2933. }
  2934. }
  2935. /** @hidden */
  2936. public _releaseTexture(texture: InternalTexture): void {
  2937. this._releaseFramebufferObjects(texture);
  2938. this._deleteTexture(texture._webGLTexture);
  2939. // Unbind channels
  2940. this.unbindAllTextures();
  2941. var index = this._internalTexturesCache.indexOf(texture);
  2942. if (index !== -1) {
  2943. this._internalTexturesCache.splice(index, 1);
  2944. }
  2945. // Integrated fixed lod samplers.
  2946. if (texture._lodTextureHigh) {
  2947. texture._lodTextureHigh.dispose();
  2948. }
  2949. if (texture._lodTextureMid) {
  2950. texture._lodTextureMid.dispose();
  2951. }
  2952. if (texture._lodTextureLow) {
  2953. texture._lodTextureLow.dispose();
  2954. }
  2955. // Integrated irradiance map.
  2956. if (texture._irradianceTexture) {
  2957. texture._irradianceTexture.dispose();
  2958. }
  2959. }
  2960. protected _deleteTexture(texture: Nullable<WebGLTexture>): void {
  2961. this._gl.deleteTexture(texture);
  2962. }
  2963. protected _setProgram(program: WebGLProgram): void {
  2964. if (this._currentProgram !== program) {
  2965. this._gl.useProgram(program);
  2966. this._currentProgram = program;
  2967. }
  2968. }
  2969. protected _boundUniforms: { [key: number]: WebGLUniformLocation } = {};
  2970. /**
  2971. * Binds an effect to the webGL context
  2972. * @param effect defines the effect to bind
  2973. */
  2974. public bindSamplers(effect: Effect): void {
  2975. let webGLPipelineContext = effect.getPipelineContext() as WebGLPipelineContext;
  2976. this._setProgram(webGLPipelineContext.program!);
  2977. var samplers = effect.getSamplers();
  2978. for (var index = 0; index < samplers.length; index++) {
  2979. var uniform = effect.getUniform(samplers[index]);
  2980. if (uniform) {
  2981. this._boundUniforms[index] = uniform;
  2982. }
  2983. }
  2984. this._currentEffect = null;
  2985. }
  2986. private _activateCurrentTexture() {
  2987. if (this._currentTextureChannel !== this._activeChannel) {
  2988. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  2989. this._currentTextureChannel = this._activeChannel;
  2990. }
  2991. }
  2992. /** @hidden */
  2993. public _bindTextureDirectly(target: number, texture: Nullable<InternalTexture>, forTextureDataUpdate = false, force = false): boolean {
  2994. var wasPreviouslyBound = false;
  2995. let isTextureForRendering = texture && texture._associatedChannel > -1;
  2996. if (forTextureDataUpdate && isTextureForRendering) {
  2997. this._activeChannel = texture!._associatedChannel;
  2998. }
  2999. let currentTextureBound = this._boundTexturesCache[this._activeChannel];
  3000. if (currentTextureBound !== texture || force) {
  3001. this._activateCurrentTexture();
  3002. if (texture && texture.isMultiview) {
  3003. this._gl.bindTexture(target, texture ? texture._colorTextureArray : null);
  3004. } else {
  3005. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  3006. }
  3007. this._boundTexturesCache[this._activeChannel] = texture;
  3008. if (texture) {
  3009. texture._associatedChannel = this._activeChannel;
  3010. }
  3011. } else if (forTextureDataUpdate) {
  3012. wasPreviouslyBound = true;
  3013. this._activateCurrentTexture();
  3014. }
  3015. if (isTextureForRendering && !forTextureDataUpdate) {
  3016. this._bindSamplerUniformToChannel(texture!._associatedChannel, this._activeChannel);
  3017. }
  3018. return wasPreviouslyBound;
  3019. }
  3020. /** @hidden */
  3021. public _bindTexture(channel: number, texture: Nullable<InternalTexture>): void {
  3022. if (channel === undefined) {
  3023. return;
  3024. }
  3025. if (texture) {
  3026. texture._associatedChannel = channel;
  3027. }
  3028. this._activeChannel = channel;
  3029. const target = texture ? this._getTextureTarget(texture) : this._gl.TEXTURE_2D;
  3030. this._bindTextureDirectly(target, texture);
  3031. }
  3032. /**
  3033. * Unbind all textures from the webGL context
  3034. */
  3035. public unbindAllTextures(): void {
  3036. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  3037. this._activeChannel = channel;
  3038. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3039. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3040. if (this.webGLVersion > 1) {
  3041. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  3042. this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY, null);
  3043. }
  3044. }
  3045. }
  3046. /**
  3047. * Sets a texture to the according uniform.
  3048. * @param channel The texture channel
  3049. * @param uniform The uniform to set
  3050. * @param texture The texture to apply
  3051. */
  3052. public setTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<BaseTexture>): void {
  3053. if (channel === undefined) {
  3054. return;
  3055. }
  3056. if (uniform) {
  3057. this._boundUniforms[channel] = uniform;
  3058. }
  3059. this._setTexture(channel, texture);
  3060. }
  3061. private _bindSamplerUniformToChannel(sourceSlot: number, destination: number) {
  3062. let uniform = this._boundUniforms[sourceSlot];
  3063. if (!uniform || uniform._currentState === destination) {
  3064. return;
  3065. }
  3066. this._gl.uniform1i(uniform, destination);
  3067. uniform._currentState = destination;
  3068. }
  3069. private _getTextureWrapMode(mode: number): number {
  3070. switch (mode) {
  3071. case Constants.TEXTURE_WRAP_ADDRESSMODE:
  3072. return this._gl.REPEAT;
  3073. case Constants.TEXTURE_CLAMP_ADDRESSMODE:
  3074. return this._gl.CLAMP_TO_EDGE;
  3075. case Constants.TEXTURE_MIRROR_ADDRESSMODE:
  3076. return this._gl.MIRRORED_REPEAT;
  3077. }
  3078. return this._gl.REPEAT;
  3079. }
  3080. protected _setTexture(channel: number, texture: Nullable<BaseTexture>, isPartOfTextureArray = false, depthStencilTexture = false): boolean {
  3081. // Not ready?
  3082. if (!texture) {
  3083. if (this._boundTexturesCache[channel] != null) {
  3084. this._activeChannel = channel;
  3085. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3086. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3087. if (this.webGLVersion > 1) {
  3088. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  3089. this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY, null);
  3090. }
  3091. }
  3092. return false;
  3093. }
  3094. // Video
  3095. if ((<VideoTexture>texture).video) {
  3096. this._activeChannel = channel;
  3097. (<VideoTexture>texture).update();
  3098. } else if (texture.delayLoadState === Constants.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  3099. texture.delayLoad();
  3100. return false;
  3101. }
  3102. let internalTexture: InternalTexture;
  3103. if (depthStencilTexture) {
  3104. internalTexture = (<RenderTargetTexture>texture).depthStencilTexture!;
  3105. }
  3106. else if (texture.isReady()) {
  3107. internalTexture = <InternalTexture>texture.getInternalTexture();
  3108. }
  3109. else if (texture.isCube) {
  3110. internalTexture = this.emptyCubeTexture;
  3111. }
  3112. else if (texture.is3D) {
  3113. internalTexture = this.emptyTexture3D;
  3114. }
  3115. else if (texture.is2DArray) {
  3116. internalTexture = this.emptyTexture2DArray;
  3117. }
  3118. else {
  3119. internalTexture = this.emptyTexture;
  3120. }
  3121. if (!isPartOfTextureArray && internalTexture) {
  3122. internalTexture._associatedChannel = channel;
  3123. }
  3124. let needToBind = true;
  3125. if (this._boundTexturesCache[channel] === internalTexture) {
  3126. if (!isPartOfTextureArray) {
  3127. this._bindSamplerUniformToChannel(internalTexture._associatedChannel, channel);
  3128. }
  3129. needToBind = false;
  3130. }
  3131. this._activeChannel = channel;
  3132. const target = this._getTextureTarget(internalTexture);
  3133. if (needToBind) {
  3134. this._bindTextureDirectly(target, internalTexture, isPartOfTextureArray);
  3135. }
  3136. if (internalTexture && !internalTexture.isMultiview) {
  3137. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  3138. if (internalTexture.isCube && internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3139. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3140. var textureWrapMode = (texture.coordinatesMode !== Constants.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Constants.TEXTURE_SKYBOX_MODE) ? Constants.TEXTURE_WRAP_ADDRESSMODE : Constants.TEXTURE_CLAMP_ADDRESSMODE;
  3141. texture.wrapU = textureWrapMode;
  3142. texture.wrapV = textureWrapMode;
  3143. }
  3144. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3145. internalTexture._cachedWrapU = texture.wrapU;
  3146. this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  3147. }
  3148. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3149. internalTexture._cachedWrapV = texture.wrapV;
  3150. this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  3151. }
  3152. if (internalTexture.is3D && internalTexture._cachedWrapR !== texture.wrapR) {
  3153. internalTexture._cachedWrapR = texture.wrapR;
  3154. this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  3155. }
  3156. this._setAnisotropicLevel(target, internalTexture, texture.anisotropicFilteringLevel);
  3157. }
  3158. return true;
  3159. }
  3160. /**
  3161. * Sets an array of texture to the webGL context
  3162. * @param channel defines the channel where the texture array must be set
  3163. * @param uniform defines the associated uniform location
  3164. * @param textures defines the array of textures to bind
  3165. */
  3166. public setTextureArray(channel: number, uniform: Nullable<WebGLUniformLocation>, textures: BaseTexture[]): void {
  3167. if (channel === undefined || !uniform) {
  3168. return;
  3169. }
  3170. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  3171. this._textureUnits = new Int32Array(textures.length);
  3172. }
  3173. for (let i = 0; i < textures.length; i++) {
  3174. let texture = textures[i].getInternalTexture();
  3175. if (texture) {
  3176. this._textureUnits[i] = channel + i;
  3177. texture._associatedChannel = channel + i;
  3178. } else {
  3179. this._textureUnits[i] = -1;
  3180. }
  3181. }
  3182. this._gl.uniform1iv(uniform, this._textureUnits);
  3183. for (var index = 0; index < textures.length; index++) {
  3184. this._setTexture(this._textureUnits[index], textures[index], true);
  3185. }
  3186. }
  3187. /** @hidden */
  3188. public _setAnisotropicLevel(target: number, internalTexture: InternalTexture, anisotropicFilteringLevel: number) {
  3189. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3190. if (internalTexture.samplingMode !== Constants.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  3191. && internalTexture.samplingMode !== Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  3192. && internalTexture.samplingMode !== Constants.TEXTURE_LINEAR_LINEAR) {
  3193. anisotropicFilteringLevel = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  3194. }
  3195. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== anisotropicFilteringLevel) {
  3196. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(anisotropicFilteringLevel, this._caps.maxAnisotropy), internalTexture);
  3197. internalTexture._cachedAnisotropicFilteringLevel = anisotropicFilteringLevel;
  3198. }
  3199. }
  3200. private _setTextureParameterFloat(target: number, parameter: number, value: number, texture: InternalTexture): void {
  3201. this._bindTextureDirectly(target, texture, true, true);
  3202. this._gl.texParameterf(target, parameter, value);
  3203. }
  3204. private _setTextureParameterInteger(target: number, parameter: number, value: number, texture?: InternalTexture) {
  3205. if (texture) {
  3206. this._bindTextureDirectly(target, texture, true, true);
  3207. }
  3208. this._gl.texParameteri(target, parameter, value);
  3209. }
  3210. /**
  3211. * Unbind all vertex attributes from the webGL context
  3212. */
  3213. public unbindAllAttributes() {
  3214. if (this._mustWipeVertexAttributes) {
  3215. this._mustWipeVertexAttributes = false;
  3216. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  3217. this.disableAttributeByIndex(i);
  3218. }
  3219. return;
  3220. }
  3221. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  3222. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  3223. continue;
  3224. }
  3225. this.disableAttributeByIndex(i);
  3226. }
  3227. }
  3228. /**
  3229. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  3230. */
  3231. public releaseEffects() {
  3232. for (var name in this._compiledEffects) {
  3233. let webGLPipelineContext = this._compiledEffects[name].getPipelineContext() as WebGLPipelineContext;
  3234. this._deletePipelineContext(webGLPipelineContext);
  3235. }
  3236. this._compiledEffects = {};
  3237. }
  3238. /**
  3239. * Dispose and release all associated resources
  3240. */
  3241. public dispose(): void {
  3242. this.stopRenderLoop();
  3243. // Clear observables
  3244. if (this.onBeforeTextureInitObservable) {
  3245. this.onBeforeTextureInitObservable.clear();
  3246. }
  3247. // Empty texture
  3248. if (this._emptyTexture) {
  3249. this._releaseTexture(this._emptyTexture);
  3250. this._emptyTexture = null;
  3251. }
  3252. if (this._emptyCubeTexture) {
  3253. this._releaseTexture(this._emptyCubeTexture);
  3254. this._emptyCubeTexture = null;
  3255. }
  3256. if (this._dummyFramebuffer) {
  3257. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  3258. }
  3259. // Release effects
  3260. this.releaseEffects();
  3261. // Unbind
  3262. this.unbindAllAttributes();
  3263. this._boundUniforms = [];
  3264. // Events
  3265. if (DomManagement.IsWindowObjectExist()) {
  3266. if (this._renderingCanvas) {
  3267. if (!this._doNotHandleContextLost) {
  3268. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  3269. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  3270. }
  3271. }
  3272. }
  3273. this._workingCanvas = null;
  3274. this._workingContext = null;
  3275. this._currentBufferPointers = [];
  3276. this._renderingCanvas = null;
  3277. this._currentProgram = null;
  3278. this._boundRenderFunction = null;
  3279. Effect.ResetCache();
  3280. // Abort active requests
  3281. for (let request of this._activeRequests) {
  3282. request.abort();
  3283. }
  3284. }
  3285. /**
  3286. * Attach a new callback raised when context lost event is fired
  3287. * @param callback defines the callback to call
  3288. */
  3289. public attachContextLostEvent(callback: ((event: WebGLContextEvent) => void)): void {
  3290. if (this._renderingCanvas) {
  3291. this._renderingCanvas.addEventListener("webglcontextlost", <any>callback, false);
  3292. }
  3293. }
  3294. /**
  3295. * Attach a new callback raised when context restored event is fired
  3296. * @param callback defines the callback to call
  3297. */
  3298. public attachContextRestoredEvent(callback: ((event: WebGLContextEvent) => void)): void {
  3299. if (this._renderingCanvas) {
  3300. this._renderingCanvas.addEventListener("webglcontextrestored", <any>callback, false);
  3301. }
  3302. }
  3303. /**
  3304. * Get the current error code of the webGL context
  3305. * @returns the error code
  3306. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  3307. */
  3308. public getError(): number {
  3309. return this._gl.getError();
  3310. }
  3311. private _canRenderToFloatFramebuffer(): boolean {
  3312. if (this._webGLVersion > 1) {
  3313. return this._caps.colorBufferFloat;
  3314. }
  3315. return this._canRenderToFramebuffer(Constants.TEXTURETYPE_FLOAT);
  3316. }
  3317. private _canRenderToHalfFloatFramebuffer(): boolean {
  3318. if (this._webGLVersion > 1) {
  3319. return this._caps.colorBufferFloat;
  3320. }
  3321. return this._canRenderToFramebuffer(Constants.TEXTURETYPE_HALF_FLOAT);
  3322. }
  3323. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  3324. private _canRenderToFramebuffer(type: number): boolean {
  3325. let gl = this._gl;
  3326. //clear existing errors
  3327. while (gl.getError() !== gl.NO_ERROR) { }
  3328. let successful = true;
  3329. let texture = gl.createTexture();
  3330. gl.bindTexture(gl.TEXTURE_2D, texture);
  3331. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  3332. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3333. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3334. let fb = gl.createFramebuffer();
  3335. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  3336. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3337. let status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  3338. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  3339. successful = successful && (gl.getError() === gl.NO_ERROR);
  3340. //try render by clearing frame buffer's color buffer
  3341. if (successful) {
  3342. gl.clear(gl.COLOR_BUFFER_BIT);
  3343. successful = successful && (gl.getError() === gl.NO_ERROR);
  3344. }
  3345. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  3346. if (successful) {
  3347. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  3348. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3349. let readFormat = gl.RGBA;
  3350. let readType = gl.UNSIGNED_BYTE;
  3351. let buffer = new Uint8Array(4);
  3352. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  3353. successful = successful && (gl.getError() === gl.NO_ERROR);
  3354. }
  3355. //clean up
  3356. gl.deleteTexture(texture);
  3357. gl.deleteFramebuffer(fb);
  3358. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3359. //clear accumulated errors
  3360. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  3361. return successful;
  3362. }
  3363. /** @hidden */
  3364. public _getWebGLTextureType(type: number): number {
  3365. if (this._webGLVersion === 1) {
  3366. switch (type) {
  3367. case Constants.TEXTURETYPE_FLOAT:
  3368. return this._gl.FLOAT;
  3369. case Constants.TEXTURETYPE_HALF_FLOAT:
  3370. return this._gl.HALF_FLOAT_OES;
  3371. case Constants.TEXTURETYPE_UNSIGNED_BYTE:
  3372. return this._gl.UNSIGNED_BYTE;
  3373. case Constants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  3374. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  3375. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  3376. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  3377. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  3378. return this._gl.UNSIGNED_SHORT_5_6_5;
  3379. }
  3380. return this._gl.UNSIGNED_BYTE;
  3381. }
  3382. switch (type) {
  3383. case Constants.TEXTURETYPE_BYTE:
  3384. return this._gl.BYTE;
  3385. case Constants.TEXTURETYPE_UNSIGNED_BYTE:
  3386. return this._gl.UNSIGNED_BYTE;
  3387. case Constants.TEXTURETYPE_SHORT:
  3388. return this._gl.SHORT;
  3389. case Constants.TEXTURETYPE_UNSIGNED_SHORT:
  3390. return this._gl.UNSIGNED_SHORT;
  3391. case Constants.TEXTURETYPE_INT:
  3392. return this._gl.INT;
  3393. case Constants.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  3394. return this._gl.UNSIGNED_INT;
  3395. case Constants.TEXTURETYPE_FLOAT:
  3396. return this._gl.FLOAT;
  3397. case Constants.TEXTURETYPE_HALF_FLOAT:
  3398. return this._gl.HALF_FLOAT;
  3399. case Constants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  3400. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  3401. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  3402. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  3403. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  3404. return this._gl.UNSIGNED_SHORT_5_6_5;
  3405. case Constants.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  3406. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  3407. case Constants.TEXTURETYPE_UNSIGNED_INT_24_8:
  3408. return this._gl.UNSIGNED_INT_24_8;
  3409. case Constants.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  3410. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  3411. case Constants.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  3412. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  3413. case Constants.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  3414. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  3415. }
  3416. return this._gl.UNSIGNED_BYTE;
  3417. }
  3418. /** @hidden */
  3419. public _getInternalFormat(format: number): number {
  3420. var internalFormat = this._gl.RGBA;
  3421. switch (format) {
  3422. case Constants.TEXTUREFORMAT_ALPHA:
  3423. internalFormat = this._gl.ALPHA;
  3424. break;
  3425. case Constants.TEXTUREFORMAT_LUMINANCE:
  3426. internalFormat = this._gl.LUMINANCE;
  3427. break;
  3428. case Constants.TEXTUREFORMAT_LUMINANCE_ALPHA:
  3429. internalFormat = this._gl.LUMINANCE_ALPHA;
  3430. break;
  3431. case Constants.TEXTUREFORMAT_RED:
  3432. internalFormat = this._gl.RED;
  3433. break;
  3434. case Constants.TEXTUREFORMAT_RG:
  3435. internalFormat = this._gl.RG;
  3436. break;
  3437. case Constants.TEXTUREFORMAT_RGB:
  3438. internalFormat = this._gl.RGB;
  3439. break;
  3440. case Constants.TEXTUREFORMAT_RGBA:
  3441. internalFormat = this._gl.RGBA;
  3442. break;
  3443. }
  3444. if (this._webGLVersion > 1) {
  3445. switch (format) {
  3446. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3447. internalFormat = this._gl.RED_INTEGER;
  3448. break;
  3449. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3450. internalFormat = this._gl.RG_INTEGER;
  3451. break;
  3452. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3453. internalFormat = this._gl.RGB_INTEGER;
  3454. break;
  3455. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3456. internalFormat = this._gl.RGBA_INTEGER;
  3457. break;
  3458. }
  3459. }
  3460. return internalFormat;
  3461. }
  3462. /** @hidden */
  3463. public _getRGBABufferInternalSizedFormat(type: number, format?: number): number {
  3464. if (this._webGLVersion === 1) {
  3465. if (format !== undefined) {
  3466. switch (format) {
  3467. case Constants.TEXTUREFORMAT_ALPHA:
  3468. return this._gl.ALPHA;
  3469. case Constants.TEXTUREFORMAT_LUMINANCE:
  3470. return this._gl.LUMINANCE;
  3471. case Constants.TEXTUREFORMAT_LUMINANCE_ALPHA:
  3472. return this._gl.LUMINANCE_ALPHA;
  3473. case Constants.TEXTUREFORMAT_RGB:
  3474. return this._gl.RGB;
  3475. }
  3476. }
  3477. return this._gl.RGBA;
  3478. }
  3479. switch (type) {
  3480. case Constants.TEXTURETYPE_BYTE:
  3481. switch (format) {
  3482. case Constants.TEXTUREFORMAT_RED:
  3483. return this._gl.R8_SNORM;
  3484. case Constants.TEXTUREFORMAT_RG:
  3485. return this._gl.RG8_SNORM;
  3486. case Constants.TEXTUREFORMAT_RGB:
  3487. return this._gl.RGB8_SNORM;
  3488. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3489. return this._gl.R8I;
  3490. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3491. return this._gl.RG8I;
  3492. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3493. return this._gl.RGB8I;
  3494. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3495. return this._gl.RGBA8I;
  3496. default:
  3497. return this._gl.RGBA8_SNORM;
  3498. }
  3499. case Constants.TEXTURETYPE_UNSIGNED_BYTE:
  3500. switch (format) {
  3501. case Constants.TEXTUREFORMAT_RED:
  3502. return this._gl.R8;
  3503. case Constants.TEXTUREFORMAT_RG:
  3504. return this._gl.RG8;
  3505. case Constants.TEXTUREFORMAT_RGB:
  3506. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  3507. case Constants.TEXTUREFORMAT_RGBA:
  3508. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  3509. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3510. return this._gl.R8UI;
  3511. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3512. return this._gl.RG8UI;
  3513. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3514. return this._gl.RGB8UI;
  3515. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3516. return this._gl.RGBA8UI;
  3517. case Constants.TEXTUREFORMAT_ALPHA:
  3518. return this._gl.ALPHA;
  3519. case Constants.TEXTUREFORMAT_LUMINANCE:
  3520. return this._gl.LUMINANCE;
  3521. case Constants.TEXTUREFORMAT_LUMINANCE_ALPHA:
  3522. return this._gl.LUMINANCE_ALPHA;
  3523. default:
  3524. return this._gl.RGBA8;
  3525. }
  3526. case Constants.TEXTURETYPE_SHORT:
  3527. switch (format) {
  3528. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3529. return this._gl.R16I;
  3530. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3531. return this._gl.RG16I;
  3532. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3533. return this._gl.RGB16I;
  3534. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3535. return this._gl.RGBA16I;
  3536. default:
  3537. return this._gl.RGBA16I;
  3538. }
  3539. case Constants.TEXTURETYPE_UNSIGNED_SHORT:
  3540. switch (format) {
  3541. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3542. return this._gl.R16UI;
  3543. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3544. return this._gl.RG16UI;
  3545. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3546. return this._gl.RGB16UI;
  3547. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3548. return this._gl.RGBA16UI;
  3549. default:
  3550. return this._gl.RGBA16UI;
  3551. }
  3552. case Constants.TEXTURETYPE_INT:
  3553. switch (format) {
  3554. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3555. return this._gl.R32I;
  3556. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3557. return this._gl.RG32I;
  3558. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3559. return this._gl.RGB32I;
  3560. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3561. return this._gl.RGBA32I;
  3562. default:
  3563. return this._gl.RGBA32I;
  3564. }
  3565. case Constants.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  3566. switch (format) {
  3567. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3568. return this._gl.R32UI;
  3569. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3570. return this._gl.RG32UI;
  3571. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3572. return this._gl.RGB32UI;
  3573. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3574. return this._gl.RGBA32UI;
  3575. default:
  3576. return this._gl.RGBA32UI;
  3577. }
  3578. case Constants.TEXTURETYPE_FLOAT:
  3579. switch (format) {
  3580. case Constants.TEXTUREFORMAT_RED:
  3581. return this._gl.R32F; // By default. Other possibility is R16F.
  3582. case Constants.TEXTUREFORMAT_RG:
  3583. return this._gl.RG32F; // By default. Other possibility is RG16F.
  3584. case Constants.TEXTUREFORMAT_RGB:
  3585. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  3586. case Constants.TEXTUREFORMAT_RGBA:
  3587. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  3588. default:
  3589. return this._gl.RGBA32F;
  3590. }
  3591. case Constants.TEXTURETYPE_HALF_FLOAT:
  3592. switch (format) {
  3593. case Constants.TEXTUREFORMAT_RED:
  3594. return this._gl.R16F;
  3595. case Constants.TEXTUREFORMAT_RG:
  3596. return this._gl.RG16F;
  3597. case Constants.TEXTUREFORMAT_RGB:
  3598. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  3599. case Constants.TEXTUREFORMAT_RGBA:
  3600. return this._gl.RGBA16F;
  3601. default:
  3602. return this._gl.RGBA16F;
  3603. }
  3604. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  3605. return this._gl.RGB565;
  3606. case Constants.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  3607. return this._gl.R11F_G11F_B10F;
  3608. case Constants.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  3609. return this._gl.RGB9_E5;
  3610. case Constants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  3611. return this._gl.RGBA4;
  3612. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  3613. return this._gl.RGB5_A1;
  3614. case Constants.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  3615. switch (format) {
  3616. case Constants.TEXTUREFORMAT_RGBA:
  3617. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  3618. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3619. return this._gl.RGB10_A2UI;
  3620. default:
  3621. return this._gl.RGB10_A2;
  3622. }
  3623. }
  3624. return this._gl.RGBA8;
  3625. }
  3626. /** @hidden */
  3627. public _getRGBAMultiSampleBufferFormat(type: number): number {
  3628. if (type === Constants.TEXTURETYPE_FLOAT) {
  3629. return this._gl.RGBA32F;
  3630. }
  3631. else if (type === Constants.TEXTURETYPE_HALF_FLOAT) {
  3632. return this._gl.RGBA16F;
  3633. }
  3634. return this._gl.RGBA8;
  3635. }
  3636. /** @hidden */
  3637. public _loadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (data: any) => void,
  3638. offlineProvider?: IOfflineProvider, useArrayBuffer?: boolean, onError?: (request?: IWebRequest, exception?: any) => void): IFileRequest {
  3639. let request = ThinEngine._FileToolsLoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);
  3640. this._activeRequests.push(request);
  3641. request.onCompleteObservable.add((request) => {
  3642. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  3643. });
  3644. return request;
  3645. }
  3646. /**
  3647. * Loads a file from a url
  3648. * @param url url to load
  3649. * @param onSuccess callback called when the file successfully loads
  3650. * @param onProgress callback called while file is loading (if the server supports this mode)
  3651. * @param offlineProvider defines the offline provider for caching
  3652. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  3653. * @param onError callback called when the file fails to load
  3654. * @returns a file request object
  3655. * @hidden
  3656. */
  3657. public static _FileToolsLoadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (ev: ProgressEvent) => void, offlineProvider?: IOfflineProvider, useArrayBuffer?: boolean, onError?: (request?: WebRequest, exception?: LoadFileError) => void): IFileRequest {
  3658. throw _DevTools.WarnImport("FileTools");
  3659. }
  3660. /**
  3661. * Reads pixels from the current frame buffer. Please note that this function can be slow
  3662. * @param x defines the x coordinate of the rectangle where pixels must be read
  3663. * @param y defines the y coordinate of the rectangle where pixels must be read
  3664. * @param width defines the width of the rectangle where pixels must be read
  3665. * @param height defines the height of the rectangle where pixels must be read
  3666. * @param hasAlpha defines whether the output should have alpha or not (defaults to true)
  3667. * @returns a Uint8Array containing RGBA colors
  3668. */
  3669. public readPixels(x: number, y: number, width: number, height: number, hasAlpha = true): Uint8Array {
  3670. const numChannels = hasAlpha ? 4 : 3;
  3671. const format = hasAlpha ? this._gl.RGBA : this._gl.RGB;
  3672. const data = new Uint8Array(height * width * numChannels);
  3673. this._gl.readPixels(x, y, width, height, format, this._gl.UNSIGNED_BYTE, data);
  3674. return data;
  3675. }
  3676. // Statics
  3677. private static _IsSupported: Nullable<boolean> = null;
  3678. private static _HasMajorPerformanceCaveat : Nullable<boolean> = null;
  3679. /**
  3680. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  3681. */
  3682. public static get IsSupported(): boolean {
  3683. return this.isSupported(); // Backward compat
  3684. }
  3685. /**
  3686. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  3687. * @returns true if the engine can be created
  3688. * @ignorenaming
  3689. */
  3690. public static isSupported(): boolean {
  3691. if (this._HasMajorPerformanceCaveat !== null) {
  3692. return !this._HasMajorPerformanceCaveat; // We know it is performant so WebGL is supported
  3693. }
  3694. if (this._IsSupported === null) {
  3695. try {
  3696. var tempcanvas = CanvasGenerator.CreateCanvas(1, 1);
  3697. var gl = tempcanvas.getContext("webgl") || (tempcanvas as any).getContext("experimental-webgl");
  3698. this._IsSupported = gl != null && !!window.WebGLRenderingContext;
  3699. } catch (e) {
  3700. this._IsSupported = false;
  3701. }
  3702. }
  3703. return this._IsSupported;
  3704. }
  3705. /**
  3706. * Gets a boolean indicating if the engine can be instanciated on a performant device (ie. if a webGL context can be found and it does not use a slow implementation)
  3707. */
  3708. public static get HasMajorPerformanceCaveat(): boolean {
  3709. if (this._HasMajorPerformanceCaveat === null) {
  3710. try {
  3711. var tempcanvas = CanvasGenerator.CreateCanvas(1, 1);
  3712. var gl = tempcanvas.getContext("webgl", { failIfMajorPerformanceCaveat: true }) || (tempcanvas as any).getContext("experimental-webgl", { failIfMajorPerformanceCaveat: true });
  3713. this._HasMajorPerformanceCaveat = !gl;
  3714. } catch (e) {
  3715. this._HasMajorPerformanceCaveat = false;
  3716. }
  3717. }
  3718. return this._HasMajorPerformanceCaveat;
  3719. }
  3720. /**
  3721. * Find the next highest power of two.
  3722. * @param x Number to start search from.
  3723. * @return Next highest power of two.
  3724. */
  3725. public static CeilingPOT(x: number): number {
  3726. x--;
  3727. x |= x >> 1;
  3728. x |= x >> 2;
  3729. x |= x >> 4;
  3730. x |= x >> 8;
  3731. x |= x >> 16;
  3732. x++;
  3733. return x;
  3734. }
  3735. /**
  3736. * Find the next lowest power of two.
  3737. * @param x Number to start search from.
  3738. * @return Next lowest power of two.
  3739. */
  3740. public static FloorPOT(x: number): number {
  3741. x = x | (x >> 1);
  3742. x = x | (x >> 2);
  3743. x = x | (x >> 4);
  3744. x = x | (x >> 8);
  3745. x = x | (x >> 16);
  3746. return x - (x >> 1);
  3747. }
  3748. /**
  3749. * Find the nearest power of two.
  3750. * @param x Number to start search from.
  3751. * @return Next nearest power of two.
  3752. */
  3753. public static NearestPOT(x: number): number {
  3754. var c = ThinEngine.CeilingPOT(x);
  3755. var f = ThinEngine.FloorPOT(x);
  3756. return (c - x) > (x - f) ? f : c;
  3757. }
  3758. /**
  3759. * Get the closest exponent of two
  3760. * @param value defines the value to approximate
  3761. * @param max defines the maximum value to return
  3762. * @param mode defines how to define the closest value
  3763. * @returns closest exponent of two of the given value
  3764. */
  3765. public static GetExponentOfTwo(value: number, max: number, mode = Constants.SCALEMODE_NEAREST): number {
  3766. let pot;
  3767. switch (mode) {
  3768. case Constants.SCALEMODE_FLOOR:
  3769. pot = ThinEngine.FloorPOT(value);
  3770. break;
  3771. case Constants.SCALEMODE_NEAREST:
  3772. pot = ThinEngine.NearestPOT(value);
  3773. break;
  3774. case Constants.SCALEMODE_CEILING:
  3775. default:
  3776. pot = ThinEngine.CeilingPOT(value);
  3777. break;
  3778. }
  3779. return Math.min(pot, max);
  3780. }
  3781. /**
  3782. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  3783. * @param func - the function to be called
  3784. * @param requester - the object that will request the next frame. Falls back to window.
  3785. * @returns frame number
  3786. */
  3787. public static QueueNewFrame(func: () => void, requester?: any): number {
  3788. if (!DomManagement.IsWindowObjectExist()) {
  3789. if (typeof requestAnimationFrame !== "undefined") {
  3790. return requestAnimationFrame(func);
  3791. }
  3792. return setTimeout(func, 16);
  3793. }
  3794. if (!requester) {
  3795. requester = window;
  3796. }
  3797. if (requester.requestPostAnimationFrame) {
  3798. return requester.requestPostAnimationFrame(func);
  3799. }
  3800. else if (requester.requestAnimationFrame) {
  3801. return requester.requestAnimationFrame(func);
  3802. }
  3803. else if (requester.msRequestAnimationFrame) {
  3804. return requester.msRequestAnimationFrame(func);
  3805. }
  3806. else if (requester.webkitRequestAnimationFrame) {
  3807. return requester.webkitRequestAnimationFrame(func);
  3808. }
  3809. else if (requester.mozRequestAnimationFrame) {
  3810. return requester.mozRequestAnimationFrame(func);
  3811. }
  3812. else if (requester.oRequestAnimationFrame) {
  3813. return requester.oRequestAnimationFrame(func);
  3814. }
  3815. else {
  3816. return window.setTimeout(func, 16);
  3817. }
  3818. }
  3819. /**
  3820. * Gets host document
  3821. * @returns the host document object
  3822. */
  3823. public getHostDocument(): Nullable<Document> {
  3824. if (this._renderingCanvas && this._renderingCanvas.ownerDocument) {
  3825. return this._renderingCanvas.ownerDocument;
  3826. }
  3827. return document;
  3828. }
  3829. }