thinEngine.ts 176 KB

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