thinEngine.ts 177 KB

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