thinEngine.ts 174 KB

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