shaderMaterial.ts 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235
  1. import { SerializationHelper } from "../Misc/decorators";
  2. import { Nullable } from "../types";
  3. import { Scene } from "../scene";
  4. import { Matrix, Vector3, Vector2, Vector4 } from "../Maths/math.vector";
  5. import { AbstractMesh } from "../Meshes/abstractMesh";
  6. import { Mesh } from "../Meshes/mesh";
  7. import { SubMesh } from "../Meshes/subMesh";
  8. import { VertexBuffer } from "../Meshes/buffer";
  9. import { BaseTexture } from "../Materials/Textures/baseTexture";
  10. import { Texture } from "../Materials/Textures/texture";
  11. import { MaterialHelper } from "./materialHelper";
  12. import { Effect, IEffectCreationOptions } from "./effect";
  13. import { Material } from "./material";
  14. import { _TypeStore } from '../Misc/typeStore';
  15. import { Color3, Color4 } from '../Maths/math.color';
  16. import { EffectFallbacks } from './effectFallbacks';
  17. const onCreatedEffectParameters = { effect: null as unknown as Effect, subMesh: null as unknown as Nullable<SubMesh> };
  18. /**
  19. * Defines the options associated with the creation of a shader material.
  20. */
  21. export interface IShaderMaterialOptions {
  22. /**
  23. * Does the material work in alpha blend mode
  24. */
  25. needAlphaBlending: boolean;
  26. /**
  27. * Does the material work in alpha test mode
  28. */
  29. needAlphaTesting: boolean;
  30. /**
  31. * The list of attribute names used in the shader
  32. */
  33. attributes: string[];
  34. /**
  35. * The list of unifrom names used in the shader
  36. */
  37. uniforms: string[];
  38. /**
  39. * The list of UBO names used in the shader
  40. */
  41. uniformBuffers: string[];
  42. /**
  43. * The list of sampler names used in the shader
  44. */
  45. samplers: string[];
  46. /**
  47. * The list of defines used in the shader
  48. */
  49. defines: string[];
  50. }
  51. /**
  52. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
  53. *
  54. * This returned material effects how the mesh will look based on the code in the shaders.
  55. *
  56. * @see http://doc.babylonjs.com/how_to/shader_material
  57. */
  58. export class ShaderMaterial extends Material {
  59. private _shaderPath: any;
  60. private _options: IShaderMaterialOptions;
  61. private _textures: { [name: string]: BaseTexture } = {};
  62. private _textureArrays: { [name: string]: BaseTexture[] } = {};
  63. private _floats: { [name: string]: number } = {};
  64. private _ints: { [name: string]: number } = {};
  65. private _floatsArrays: { [name: string]: number[] } = {};
  66. private _colors3: { [name: string]: Color3 } = {};
  67. private _colors3Arrays: { [name: string]: number[] } = {};
  68. private _colors4: { [name: string]: Color4 } = {};
  69. private _colors4Arrays: { [name: string]: number[] } = {};
  70. private _vectors2: { [name: string]: Vector2 } = {};
  71. private _vectors3: { [name: string]: Vector3 } = {};
  72. private _vectors4: { [name: string]: Vector4 } = {};
  73. private _matrices: { [name: string]: Matrix } = {};
  74. private _matrixArrays: { [name: string]: Float32Array } = {};
  75. private _matrices3x3: { [name: string]: Float32Array } = {};
  76. private _matrices2x2: { [name: string]: Float32Array } = {};
  77. private _vectors2Arrays: { [name: string]: number[] } = {};
  78. private _vectors3Arrays: { [name: string]: number[] } = {};
  79. private _vectors4Arrays: { [name: string]: number[] } = {};
  80. private _cachedWorldViewMatrix = new Matrix();
  81. private _cachedWorldViewProjectionMatrix = new Matrix();
  82. private _renderId: number;
  83. private _multiview: boolean = false;
  84. private _cachedDefines: string;
  85. /**
  86. * Instantiate a new shader material.
  87. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
  88. * This returned material effects how the mesh will look based on the code in the shaders.
  89. * @see http://doc.babylonjs.com/how_to/shader_material
  90. * @param name Define the name of the material in the scene
  91. * @param scene Define the scene the material belongs to
  92. * @param shaderPath Defines the route to the shader code in one of three ways:
  93. * * object: { vertex: "custom", fragment: "custom" }, used with Effect.ShadersStore["customVertexShader"] and Effect.ShadersStore["customFragmentShader"]
  94. * * object: { vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }, used with shader code in script tags
  95. * * object: { vertexSource: "vertex shader code string", fragmentSource: "fragment shader code string" } using with strings containing the shaders code
  96. * * string: "./COMMON_NAME", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.
  97. * @param options Define the options used to create the shader
  98. */
  99. constructor(name: string, scene: Scene, shaderPath: any, options: Partial<IShaderMaterialOptions> = {}) {
  100. super(name, scene);
  101. this._shaderPath = shaderPath;
  102. this._options = {
  103. needAlphaBlending: false,
  104. needAlphaTesting: false,
  105. attributes: ["position", "normal", "uv"],
  106. uniforms: ["worldViewProjection"],
  107. uniformBuffers: [],
  108. samplers: [],
  109. defines: [],
  110. ...options
  111. };
  112. }
  113. /**
  114. * Gets the shader path used to define the shader code
  115. * It can be modified to trigger a new compilation
  116. */
  117. public get shaderPath(): any {
  118. return this._shaderPath;
  119. }
  120. /**
  121. * Sets the shader path used to define the shader code
  122. * It can be modified to trigger a new compilation
  123. */
  124. public set shaderPath(shaderPath: any) {
  125. this._shaderPath = shaderPath;
  126. }
  127. /**
  128. * Gets the options used to compile the shader.
  129. * They can be modified to trigger a new compilation
  130. */
  131. public get options(): IShaderMaterialOptions {
  132. return this._options;
  133. }
  134. /**
  135. * Gets the current class name of the material e.g. "ShaderMaterial"
  136. * Mainly use in serialization.
  137. * @returns the class name
  138. */
  139. public getClassName(): string {
  140. return "ShaderMaterial";
  141. }
  142. /**
  143. * Specifies if the material will require alpha blending
  144. * @returns a boolean specifying if alpha blending is needed
  145. */
  146. public needAlphaBlending(): boolean {
  147. return (this.alpha < 1.0) || this._options.needAlphaBlending;
  148. }
  149. /**
  150. * Specifies if this material should be rendered in alpha test mode
  151. * @returns a boolean specifying if an alpha test is needed.
  152. */
  153. public needAlphaTesting(): boolean {
  154. return this._options.needAlphaTesting;
  155. }
  156. private _checkUniform(uniformName: string): void {
  157. if (this._options.uniforms.indexOf(uniformName) === -1) {
  158. this._options.uniforms.push(uniformName);
  159. }
  160. }
  161. /**
  162. * Set a texture in the shader.
  163. * @param name Define the name of the uniform samplers as defined in the shader
  164. * @param texture Define the texture to bind to this sampler
  165. * @return the material itself allowing "fluent" like uniform updates
  166. */
  167. public setTexture(name: string, texture: BaseTexture): ShaderMaterial {
  168. if (this._options.samplers.indexOf(name) === -1) {
  169. this._options.samplers.push(name);
  170. }
  171. this._textures[name] = texture;
  172. return this;
  173. }
  174. /**
  175. * Set a texture array in the shader.
  176. * @param name Define the name of the uniform sampler array as defined in the shader
  177. * @param textures Define the list of textures to bind to this sampler
  178. * @return the material itself allowing "fluent" like uniform updates
  179. */
  180. public setTextureArray(name: string, textures: BaseTexture[]): ShaderMaterial {
  181. if (this._options.samplers.indexOf(name) === -1) {
  182. this._options.samplers.push(name);
  183. }
  184. this._checkUniform(name);
  185. this._textureArrays[name] = textures;
  186. return this;
  187. }
  188. /**
  189. * Set a float in the shader.
  190. * @param name Define the name of the uniform as defined in the shader
  191. * @param value Define the value to give to the uniform
  192. * @return the material itself allowing "fluent" like uniform updates
  193. */
  194. public setFloat(name: string, value: number): ShaderMaterial {
  195. this._checkUniform(name);
  196. this._floats[name] = value;
  197. return this;
  198. }
  199. /**
  200. * Set a int in the shader.
  201. * @param name Define the name of the uniform as defined in the shader
  202. * @param value Define the value to give to the uniform
  203. * @return the material itself allowing "fluent" like uniform updates
  204. */
  205. public setInt(name: string, value: number): ShaderMaterial {
  206. this._checkUniform(name);
  207. this._ints[name] = value;
  208. return this;
  209. }
  210. /**
  211. * Set an array of floats in the shader.
  212. * @param name Define the name of the uniform as defined in the shader
  213. * @param value Define the value to give to the uniform
  214. * @return the material itself allowing "fluent" like uniform updates
  215. */
  216. public setFloats(name: string, value: number[]): ShaderMaterial {
  217. this._checkUniform(name);
  218. this._floatsArrays[name] = value;
  219. return this;
  220. }
  221. /**
  222. * Set a vec3 in the shader from a Color3.
  223. * @param name Define the name of the uniform as defined in the shader
  224. * @param value Define the value to give to the uniform
  225. * @return the material itself allowing "fluent" like uniform updates
  226. */
  227. public setColor3(name: string, value: Color3): ShaderMaterial {
  228. this._checkUniform(name);
  229. this._colors3[name] = value;
  230. return this;
  231. }
  232. /**
  233. * Set a vec3 array in the shader from a Color3 array.
  234. * @param name Define the name of the uniform as defined in the shader
  235. * @param value Define the value to give to the uniform
  236. * @return the material itself allowing "fluent" like uniform updates
  237. */
  238. public setColor3Array(name: string, value: Color3[]): ShaderMaterial {
  239. this._checkUniform(name);
  240. this._colors3Arrays[name] = value.reduce((arr, color) => {
  241. color.toArray(arr, arr.length);
  242. return arr;
  243. }, []);
  244. return this;
  245. }
  246. /**
  247. * Set a vec4 in the shader from a Color4.
  248. * @param name Define the name of the uniform as defined in the shader
  249. * @param value Define the value to give to the uniform
  250. * @return the material itself allowing "fluent" like uniform updates
  251. */
  252. public setColor4(name: string, value: Color4): ShaderMaterial {
  253. this._checkUniform(name);
  254. this._colors4[name] = value;
  255. return this;
  256. }
  257. /**
  258. * Set a vec4 array in the shader from a Color4 array.
  259. * @param name Define the name of the uniform as defined in the shader
  260. * @param value Define the value to give to the uniform
  261. * @return the material itself allowing "fluent" like uniform updates
  262. */
  263. public setColor4Array(name: string, value: Color4[]): ShaderMaterial {
  264. this._checkUniform(name);
  265. this._colors4Arrays[name] = value.reduce((arr, color) => {
  266. color.toArray(arr, arr.length);
  267. return arr;
  268. }, []);
  269. return this;
  270. }
  271. /**
  272. * Set a vec2 in the shader from a Vector2.
  273. * @param name Define the name of the uniform as defined in the shader
  274. * @param value Define the value to give to the uniform
  275. * @return the material itself allowing "fluent" like uniform updates
  276. */
  277. public setVector2(name: string, value: Vector2): ShaderMaterial {
  278. this._checkUniform(name);
  279. this._vectors2[name] = value;
  280. return this;
  281. }
  282. /**
  283. * Set a vec3 in the shader from a Vector3.
  284. * @param name Define the name of the uniform as defined in the shader
  285. * @param value Define the value to give to the uniform
  286. * @return the material itself allowing "fluent" like uniform updates
  287. */
  288. public setVector3(name: string, value: Vector3): ShaderMaterial {
  289. this._checkUniform(name);
  290. this._vectors3[name] = value;
  291. return this;
  292. }
  293. /**
  294. * Set a vec4 in the shader from a Vector4.
  295. * @param name Define the name of the uniform as defined in the shader
  296. * @param value Define the value to give to the uniform
  297. * @return the material itself allowing "fluent" like uniform updates
  298. */
  299. public setVector4(name: string, value: Vector4): ShaderMaterial {
  300. this._checkUniform(name);
  301. this._vectors4[name] = value;
  302. return this;
  303. }
  304. /**
  305. * Set a mat4 in the shader from a Matrix.
  306. * @param name Define the name of the uniform as defined in the shader
  307. * @param value Define the value to give to the uniform
  308. * @return the material itself allowing "fluent" like uniform updates
  309. */
  310. public setMatrix(name: string, value: Matrix): ShaderMaterial {
  311. this._checkUniform(name);
  312. this._matrices[name] = value;
  313. return this;
  314. }
  315. /**
  316. * Set a float32Array in the shader from a matrix array.
  317. * @param name Define the name of the uniform as defined in the shader
  318. * @param value Define the value to give to the uniform
  319. * @return the material itself allowing "fluent" like uniform updates
  320. */
  321. public setMatrices(name: string, value: Matrix[]): ShaderMaterial {
  322. this._checkUniform(name);
  323. let float32Array = new Float32Array(value.length * 16);
  324. for (var index = 0; index < value.length; index++) {
  325. let matrix = value[index];
  326. matrix.copyToArray(float32Array, index * 16);
  327. }
  328. this._matrixArrays[name] = float32Array;
  329. return this;
  330. }
  331. /**
  332. * Set a mat3 in the shader from a Float32Array.
  333. * @param name Define the name of the uniform as defined in the shader
  334. * @param value Define the value to give to the uniform
  335. * @return the material itself allowing "fluent" like uniform updates
  336. */
  337. public setMatrix3x3(name: string, value: Float32Array): ShaderMaterial {
  338. this._checkUniform(name);
  339. this._matrices3x3[name] = value;
  340. return this;
  341. }
  342. /**
  343. * Set a mat2 in the shader from a Float32Array.
  344. * @param name Define the name of the uniform as defined in the shader
  345. * @param value Define the value to give to the uniform
  346. * @return the material itself allowing "fluent" like uniform updates
  347. */
  348. public setMatrix2x2(name: string, value: Float32Array): ShaderMaterial {
  349. this._checkUniform(name);
  350. this._matrices2x2[name] = value;
  351. return this;
  352. }
  353. /**
  354. * Set a vec2 array in the shader from a number array.
  355. * @param name Define the name of the uniform as defined in the shader
  356. * @param value Define the value to give to the uniform
  357. * @return the material itself allowing "fluent" like uniform updates
  358. */
  359. public setArray2(name: string, value: number[]): ShaderMaterial {
  360. this._checkUniform(name);
  361. this._vectors2Arrays[name] = value;
  362. return this;
  363. }
  364. /**
  365. * Set a vec3 array in the shader from a number array.
  366. * @param name Define the name of the uniform as defined in the shader
  367. * @param value Define the value to give to the uniform
  368. * @return the material itself allowing "fluent" like uniform updates
  369. */
  370. public setArray3(name: string, value: number[]): ShaderMaterial {
  371. this._checkUniform(name);
  372. this._vectors3Arrays[name] = value;
  373. return this;
  374. }
  375. /**
  376. * Set a vec4 array in the shader from a number array.
  377. * @param name Define the name of the uniform as defined in the shader
  378. * @param value Define the value to give to the uniform
  379. * @return the material itself allowing "fluent" like uniform updates
  380. */
  381. public setArray4(name: string, value: number[]): ShaderMaterial {
  382. this._checkUniform(name);
  383. this._vectors4Arrays[name] = value;
  384. return this;
  385. }
  386. private _checkCache(mesh?: AbstractMesh, useInstances?: boolean): boolean {
  387. if (!mesh) {
  388. return true;
  389. }
  390. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  391. return false;
  392. }
  393. return true;
  394. }
  395. /**
  396. * Specifies that the submesh is ready to be used
  397. * @param mesh defines the mesh to check
  398. * @param subMesh defines which submesh to check
  399. * @param useInstances specifies that instances should be used
  400. * @returns a boolean indicating that the submesh is ready or not
  401. */
  402. public isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances?: boolean): boolean {
  403. return this.isReady(mesh, useInstances);
  404. }
  405. /**
  406. * Checks if the material is ready to render the requested mesh
  407. * @param mesh Define the mesh to render
  408. * @param useInstances Define whether or not the material is used with instances
  409. * @returns true if ready, otherwise false
  410. */
  411. public isReady(mesh?: AbstractMesh, useInstances?: boolean): boolean {
  412. if (this._effect && this.isFrozen) {
  413. if (this._effect._wasPreviouslyReady) {
  414. return true;
  415. }
  416. }
  417. var scene = this.getScene();
  418. var engine = scene.getEngine();
  419. if (!this.checkReadyOnEveryCall) {
  420. if (this._renderId === scene.getRenderId()) {
  421. if (this._checkCache(mesh, useInstances)) {
  422. return true;
  423. }
  424. }
  425. }
  426. // Instances
  427. var defines = [];
  428. var attribs = [];
  429. var fallbacks = new EffectFallbacks();
  430. // global multiview
  431. if (engine.getCaps().multiview &&
  432. scene.activeCamera &&
  433. scene.activeCamera.outputRenderTarget &&
  434. scene.activeCamera.outputRenderTarget.getViewCount() > 1) {
  435. this._multiview = true;
  436. defines.push("#define MULTIVIEW");
  437. if (this._options.uniforms.indexOf("viewProjection") !== -1 &&
  438. this._options.uniforms.push("viewProjectionR") === -1) {
  439. this._options.uniforms.push("viewProjectionR");
  440. }
  441. }
  442. for (var index = 0; index < this._options.defines.length; index++) {
  443. defines.push(this._options.defines[index]);
  444. }
  445. for (var index = 0; index < this._options.attributes.length; index++) {
  446. attribs.push(this._options.attributes[index]);
  447. }
  448. if (mesh && mesh.isVerticesDataPresent(VertexBuffer.ColorKind)) {
  449. attribs.push(VertexBuffer.ColorKind);
  450. defines.push("#define VERTEXCOLOR");
  451. }
  452. if (useInstances) {
  453. defines.push("#define INSTANCES");
  454. MaterialHelper.PushAttributesForInstances(attribs);
  455. if (mesh?.hasThinInstances) {
  456. defines.push("#define THIN_INSTANCES");
  457. }
  458. }
  459. // Bones
  460. let numInfluencers = 0;
  461. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  462. attribs.push(VertexBuffer.MatricesIndicesKind);
  463. attribs.push(VertexBuffer.MatricesWeightsKind);
  464. if (mesh.numBoneInfluencers > 4) {
  465. attribs.push(VertexBuffer.MatricesIndicesExtraKind);
  466. attribs.push(VertexBuffer.MatricesWeightsExtraKind);
  467. }
  468. const skeleton = mesh.skeleton;
  469. numInfluencers = mesh.numBoneInfluencers;
  470. defines.push("#define NUM_BONE_INFLUENCERS " + numInfluencers);
  471. fallbacks.addCPUSkinningFallback(0, mesh);
  472. if (skeleton.isUsingTextureForMatrices) {
  473. defines.push("#define BONETEXTURE");
  474. if (this._options.uniforms.indexOf("boneTextureWidth") === -1) {
  475. this._options.uniforms.push("boneTextureWidth");
  476. }
  477. if (this._options.samplers.indexOf("boneSampler") === -1) {
  478. this._options.samplers.push("boneSampler");
  479. }
  480. } else {
  481. defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1));
  482. if (this._options.uniforms.indexOf("mBones") === -1) {
  483. this._options.uniforms.push("mBones");
  484. }
  485. }
  486. } else {
  487. defines.push("#define NUM_BONE_INFLUENCERS 0");
  488. }
  489. // Textures
  490. for (var name in this._textures) {
  491. if (!this._textures[name].isReady()) {
  492. return false;
  493. }
  494. }
  495. // Alpha test
  496. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  497. defines.push("#define ALPHATEST");
  498. }
  499. let shaderName = this._shaderPath,
  500. uniforms = this._options.uniforms,
  501. uniformBuffers = this._options.uniformBuffers,
  502. samplers = this._options.samplers;
  503. if (this.customShaderNameResolve) {
  504. uniforms = uniforms.slice();
  505. uniformBuffers = uniformBuffers.slice();
  506. samplers = samplers.slice();
  507. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines, attribs);
  508. }
  509. var previousEffect = this._effect;
  510. var join = defines.join("\n");
  511. if (this._cachedDefines !== join) {
  512. this._cachedDefines = join;
  513. this._effect = engine.createEffect(shaderName, <IEffectCreationOptions>{
  514. attributes: attribs,
  515. uniformsNames: uniforms,
  516. uniformBuffersNames: uniformBuffers,
  517. samplers: samplers,
  518. defines: join,
  519. fallbacks: fallbacks,
  520. onCompiled: this.onCompiled,
  521. onError: this.onError,
  522. indexParameters: { maxSimultaneousMorphTargets: numInfluencers }
  523. }, engine);
  524. if (this._onEffectCreatedObservable) {
  525. onCreatedEffectParameters.effect = this._effect;
  526. this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters);
  527. }
  528. }
  529. if (!this._effect?.isReady() ?? true) {
  530. return false;
  531. }
  532. if (previousEffect !== this._effect) {
  533. scene.resetCachedMaterial();
  534. }
  535. this._renderId = scene.getRenderId();
  536. this._effect._wasPreviouslyReady = true;
  537. return true;
  538. }
  539. /**
  540. * Binds the world matrix to the material
  541. * @param world defines the world transformation matrix
  542. * @param effectOverride - If provided, use this effect instead of internal effect
  543. */
  544. public bindOnlyWorldMatrix(world: Matrix, effectOverride?: Nullable<Effect>): void {
  545. var scene = this.getScene();
  546. const effect = effectOverride ?? this._effect;
  547. if (!effect) {
  548. return;
  549. }
  550. if (this._options.uniforms.indexOf("world") !== -1) {
  551. effect.setMatrix("world", world);
  552. }
  553. if (this._options.uniforms.indexOf("worldView") !== -1) {
  554. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  555. effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  556. }
  557. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  558. world.multiplyToRef(scene.getTransformMatrix(), this._cachedWorldViewProjectionMatrix);
  559. effect.setMatrix("worldViewProjection", this._cachedWorldViewProjectionMatrix);
  560. }
  561. }
  562. /**
  563. * Binds the submesh to this material by preparing the effect and shader to draw
  564. * @param world defines the world transformation matrix
  565. * @param mesh defines the mesh containing the submesh
  566. * @param subMesh defines the submesh to bind the material to
  567. */
  568. public bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void {
  569. this.bind(world, mesh, subMesh._effectOverride);
  570. }
  571. /**
  572. * Binds the material to the mesh
  573. * @param world defines the world transformation matrix
  574. * @param mesh defines the mesh to bind the material to
  575. * @param effectOverride - If provided, use this effect instead of internal effect
  576. */
  577. public bind(world: Matrix, mesh?: Mesh, effectOverride?: Nullable<Effect>): void {
  578. // Std values
  579. this.bindOnlyWorldMatrix(world, effectOverride);
  580. const effect = effectOverride ?? this._effect;
  581. if (effect && this.getScene().getCachedMaterial() !== this) {
  582. if (this._options.uniforms.indexOf("view") !== -1) {
  583. effect.setMatrix("view", this.getScene().getViewMatrix());
  584. }
  585. if (this._options.uniforms.indexOf("projection") !== -1) {
  586. effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  587. }
  588. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  589. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  590. if (this._multiview) {
  591. effect.setMatrix("viewProjectionR", this.getScene()._transformMatrixR);
  592. }
  593. }
  594. if (this.getScene().activeCamera && this._options.uniforms.indexOf("cameraPosition") !== -1) {
  595. effect.setVector3("cameraPosition", this.getScene().activeCamera!.globalPosition);
  596. }
  597. // Bones
  598. MaterialHelper.BindBonesParameters(mesh, effect);
  599. var name: string;
  600. // Texture
  601. for (name in this._textures) {
  602. effect.setTexture(name, this._textures[name]);
  603. }
  604. // Texture arrays
  605. for (name in this._textureArrays) {
  606. effect.setTextureArray(name, this._textureArrays[name]);
  607. }
  608. // Int
  609. for (name in this._ints) {
  610. effect.setInt(name, this._ints[name]);
  611. }
  612. // Float
  613. for (name in this._floats) {
  614. effect.setFloat(name, this._floats[name]);
  615. }
  616. // Floats
  617. for (name in this._floatsArrays) {
  618. effect.setArray(name, this._floatsArrays[name]);
  619. }
  620. // Color3
  621. for (name in this._colors3) {
  622. effect.setColor3(name, this._colors3[name]);
  623. }
  624. // Color3Array
  625. for (name in this._colors3Arrays) {
  626. effect.setArray3(name, this._colors3Arrays[name]);
  627. }
  628. // Color4
  629. for (name in this._colors4) {
  630. var color = this._colors4[name];
  631. effect.setFloat4(name, color.r, color.g, color.b, color.a);
  632. }
  633. // Color4Array
  634. for (name in this._colors4Arrays) {
  635. effect.setArray4(name, this._colors4Arrays[name]);
  636. }
  637. // Vector2
  638. for (name in this._vectors2) {
  639. effect.setVector2(name, this._vectors2[name]);
  640. }
  641. // Vector3
  642. for (name in this._vectors3) {
  643. effect.setVector3(name, this._vectors3[name]);
  644. }
  645. // Vector4
  646. for (name in this._vectors4) {
  647. effect.setVector4(name, this._vectors4[name]);
  648. }
  649. // Matrix
  650. for (name in this._matrices) {
  651. effect.setMatrix(name, this._matrices[name]);
  652. }
  653. // MatrixArray
  654. for (name in this._matrixArrays) {
  655. effect.setMatrices(name, this._matrixArrays[name]);
  656. }
  657. // Matrix 3x3
  658. for (name in this._matrices3x3) {
  659. effect.setMatrix3x3(name, this._matrices3x3[name]);
  660. }
  661. // Matrix 2x2
  662. for (name in this._matrices2x2) {
  663. effect.setMatrix2x2(name, this._matrices2x2[name]);
  664. }
  665. // Vector2Array
  666. for (name in this._vectors2Arrays) {
  667. effect.setArray2(name, this._vectors2Arrays[name]);
  668. }
  669. // Vector3Array
  670. for (name in this._vectors3Arrays) {
  671. effect.setArray3(name, this._vectors3Arrays[name]);
  672. }
  673. // Vector4Array
  674. for (name in this._vectors4Arrays) {
  675. effect.setArray4(name, this._vectors4Arrays[name]);
  676. }
  677. }
  678. const seffect = this._effect;
  679. this._effect = effect; // make sure the active effect is the right one if there are some observers for onBind that would need to get the current effect
  680. this._afterBind(mesh);
  681. this._effect = seffect;
  682. }
  683. protected _afterBind(mesh?: Mesh): void {
  684. super._afterBind(mesh);
  685. this.getScene()._cachedEffect = this._effect;
  686. }
  687. /**
  688. * Gets the active textures from the material
  689. * @returns an array of textures
  690. */
  691. public getActiveTextures(): BaseTexture[] {
  692. var activeTextures = super.getActiveTextures();
  693. for (var name in this._textures) {
  694. activeTextures.push(this._textures[name]);
  695. }
  696. for (var name in this._textureArrays) {
  697. var array = this._textureArrays[name];
  698. for (var index = 0; index < array.length; index++) {
  699. activeTextures.push(array[index]);
  700. }
  701. }
  702. return activeTextures;
  703. }
  704. /**
  705. * Specifies if the material uses a texture
  706. * @param texture defines the texture to check against the material
  707. * @returns a boolean specifying if the material uses the texture
  708. */
  709. public hasTexture(texture: BaseTexture): boolean {
  710. if (super.hasTexture(texture)) {
  711. return true;
  712. }
  713. for (var name in this._textures) {
  714. if (this._textures[name] === texture) {
  715. return true;
  716. }
  717. }
  718. for (var name in this._textureArrays) {
  719. var array = this._textureArrays[name];
  720. for (var index = 0; index < array.length; index++) {
  721. if (array[index] === texture) {
  722. return true;
  723. }
  724. }
  725. }
  726. return false;
  727. }
  728. /**
  729. * Makes a duplicate of the material, and gives it a new name
  730. * @param name defines the new name for the duplicated material
  731. * @returns the cloned material
  732. */
  733. public clone(name: string): ShaderMaterial {
  734. var result = SerializationHelper.Clone(() => new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options), this);
  735. result.name = name;
  736. result.id = name;
  737. // Shader code path
  738. if (typeof result._shaderPath === 'object') {
  739. result._shaderPath = { ...result._shaderPath };
  740. }
  741. // Options
  742. this._options = { ...this._options };
  743. (Object.keys(this._options) as Array<keyof IShaderMaterialOptions>).forEach((propName) => {
  744. const propValue = this._options[propName];
  745. if (Array.isArray(propValue)) {
  746. (<string[]>this._options[propName]) = propValue.slice(0);
  747. }
  748. });
  749. // Texture
  750. for (var key in this._textures) {
  751. result.setTexture(key, this._textures[key]);
  752. }
  753. // Float
  754. for (var key in this._floats) {
  755. result.setFloat(key, this._floats[key]);
  756. }
  757. // Floats
  758. for (var key in this._floatsArrays) {
  759. result.setFloats(key, this._floatsArrays[key]);
  760. }
  761. // Color3
  762. for (var key in this._colors3) {
  763. result.setColor3(key, this._colors3[key]);
  764. }
  765. // Color4
  766. for (var key in this._colors4) {
  767. result.setColor4(key, this._colors4[key]);
  768. }
  769. // Vector2
  770. for (var key in this._vectors2) {
  771. result.setVector2(key, this._vectors2[key]);
  772. }
  773. // Vector3
  774. for (var key in this._vectors3) {
  775. result.setVector3(key, this._vectors3[key]);
  776. }
  777. // Vector4
  778. for (var key in this._vectors4) {
  779. result.setVector4(key, this._vectors4[key]);
  780. }
  781. // Matrix
  782. for (var key in this._matrices) {
  783. result.setMatrix(key, this._matrices[key]);
  784. }
  785. // Matrix 3x3
  786. for (var key in this._matrices3x3) {
  787. result.setMatrix3x3(key, this._matrices3x3[key]);
  788. }
  789. // Matrix 2x2
  790. for (var key in this._matrices2x2) {
  791. result.setMatrix2x2(key, this._matrices2x2[key]);
  792. }
  793. return result;
  794. }
  795. /**
  796. * Disposes the material
  797. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  798. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  799. * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
  800. */
  801. public dispose(forceDisposeEffect?: boolean, forceDisposeTextures?: boolean, notBoundToMesh?: boolean): void {
  802. if (forceDisposeTextures) {
  803. var name: string;
  804. for (name in this._textures) {
  805. this._textures[name].dispose();
  806. }
  807. for (name in this._textureArrays) {
  808. var array = this._textureArrays[name];
  809. for (var index = 0; index < array.length; index++) {
  810. array[index].dispose();
  811. }
  812. }
  813. }
  814. this._textures = {};
  815. super.dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh);
  816. }
  817. /**
  818. * Serializes this material in a JSON representation
  819. * @returns the serialized material object
  820. */
  821. public serialize(): any {
  822. var serializationObject = SerializationHelper.Serialize(this);
  823. serializationObject.customType = "BABYLON.ShaderMaterial";
  824. serializationObject.options = this._options;
  825. serializationObject.shaderPath = this._shaderPath;
  826. var name: string;
  827. // Texture
  828. serializationObject.textures = {};
  829. for (name in this._textures) {
  830. serializationObject.textures[name] = this._textures[name].serialize();
  831. }
  832. // Texture arrays
  833. serializationObject.textureArrays = {};
  834. for (name in this._textureArrays) {
  835. serializationObject.textureArrays[name] = [];
  836. var array = this._textureArrays[name];
  837. for (var index = 0; index < array.length; index++) {
  838. serializationObject.textureArrays[name].push(array[index].serialize());
  839. }
  840. }
  841. // Float
  842. serializationObject.floats = {};
  843. for (name in this._floats) {
  844. serializationObject.floats[name] = this._floats[name];
  845. }
  846. // Floats
  847. serializationObject.FloatArrays = {};
  848. for (name in this._floatsArrays) {
  849. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  850. }
  851. // Color3
  852. serializationObject.colors3 = {};
  853. for (name in this._colors3) {
  854. serializationObject.colors3[name] = this._colors3[name].asArray();
  855. }
  856. // Color3 array
  857. serializationObject.colors3Arrays = {};
  858. for (name in this._colors3Arrays) {
  859. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  860. }
  861. // Color4
  862. serializationObject.colors4 = {};
  863. for (name in this._colors4) {
  864. serializationObject.colors4[name] = this._colors4[name].asArray();
  865. }
  866. // Color4 array
  867. serializationObject.colors4Arrays = {};
  868. for (name in this._colors4Arrays) {
  869. serializationObject.colors4Arrays[name] = this._colors4Arrays[name];
  870. }
  871. // Vector2
  872. serializationObject.vectors2 = {};
  873. for (name in this._vectors2) {
  874. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  875. }
  876. // Vector3
  877. serializationObject.vectors3 = {};
  878. for (name in this._vectors3) {
  879. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  880. }
  881. // Vector4
  882. serializationObject.vectors4 = {};
  883. for (name in this._vectors4) {
  884. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  885. }
  886. // Matrix
  887. serializationObject.matrices = {};
  888. for (name in this._matrices) {
  889. serializationObject.matrices[name] = this._matrices[name].asArray();
  890. }
  891. // MatrixArray
  892. serializationObject.matrixArray = {};
  893. for (name in this._matrixArrays) {
  894. serializationObject.matrixArray[name] = this._matrixArrays[name];
  895. }
  896. // Matrix 3x3
  897. serializationObject.matrices3x3 = {};
  898. for (name in this._matrices3x3) {
  899. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  900. }
  901. // Matrix 2x2
  902. serializationObject.matrices2x2 = {};
  903. for (name in this._matrices2x2) {
  904. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  905. }
  906. // Vector2Array
  907. serializationObject.vectors2Arrays = {};
  908. for (name in this._vectors2Arrays) {
  909. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  910. }
  911. // Vector3Array
  912. serializationObject.vectors3Arrays = {};
  913. for (name in this._vectors3Arrays) {
  914. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  915. }
  916. // Vector4Array
  917. serializationObject.vectors4Arrays = {};
  918. for (name in this._vectors4Arrays) {
  919. serializationObject.vectors4Arrays[name] = this._vectors4Arrays[name];
  920. }
  921. return serializationObject;
  922. }
  923. /**
  924. * Creates a shader material from parsed shader material data
  925. * @param source defines the JSON represnetation of the material
  926. * @param scene defines the hosting scene
  927. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  928. * @returns a new material
  929. */
  930. public static Parse(source: any, scene: Scene, rootUrl: string): ShaderMaterial {
  931. var material = SerializationHelper.Parse(() => new ShaderMaterial(source.name, scene, source.shaderPath, source.options), source, scene, rootUrl);
  932. var name: string;
  933. // Texture
  934. for (name in source.textures) {
  935. material.setTexture(name, <Texture>Texture.Parse(source.textures[name], scene, rootUrl));
  936. }
  937. // Texture arrays
  938. for (name in source.textureArrays) {
  939. var array = source.textureArrays[name];
  940. var textureArray = new Array<Texture>();
  941. for (var index = 0; index < array.length; index++) {
  942. textureArray.push(<Texture>Texture.Parse(array[index], scene, rootUrl));
  943. }
  944. material.setTextureArray(name, textureArray);
  945. }
  946. // Float
  947. for (name in source.floats) {
  948. material.setFloat(name, source.floats[name]);
  949. }
  950. // Float s
  951. for (name in source.floatsArrays) {
  952. material.setFloats(name, source.floatsArrays[name]);
  953. }
  954. // Color3
  955. for (name in source.colors3) {
  956. material.setColor3(name, Color3.FromArray(source.colors3[name]));
  957. }
  958. // Color3 arrays
  959. for (name in source.colors3Arrays) {
  960. const colors: Color3[] = source.colors3Arrays[name].reduce((arr: Array<Array<number>>, num: number, i: number) => {
  961. if (i % 3 === 0) {
  962. arr.push([num]);
  963. } else {
  964. arr[arr.length - 1].push(num);
  965. }
  966. return arr;
  967. }, []).map((color: ArrayLike<number>) => Color3.FromArray(color));
  968. material.setColor3Array(name, colors);
  969. }
  970. // Color4
  971. for (name in source.colors4) {
  972. material.setColor4(name, Color4.FromArray(source.colors4[name]));
  973. }
  974. // Color4 arrays
  975. for (name in source.colors4Arrays) {
  976. const colors: Color4[] = source.colors4Arrays[name].reduce((arr: Array<Array<number>>, num: number, i: number) => {
  977. if (i % 4 === 0) {
  978. arr.push([num]);
  979. } else {
  980. arr[arr.length - 1].push(num);
  981. }
  982. return arr;
  983. }, []).map((color: ArrayLike<number>) => Color4.FromArray(color));
  984. material.setColor4Array(name, colors);
  985. }
  986. // Vector2
  987. for (name in source.vectors2) {
  988. material.setVector2(name, Vector2.FromArray(source.vectors2[name]));
  989. }
  990. // Vector3
  991. for (name in source.vectors3) {
  992. material.setVector3(name, Vector3.FromArray(source.vectors3[name]));
  993. }
  994. // Vector4
  995. for (name in source.vectors4) {
  996. material.setVector4(name, Vector4.FromArray(source.vectors4[name]));
  997. }
  998. // Matrix
  999. for (name in source.matrices) {
  1000. material.setMatrix(name, Matrix.FromArray(source.matrices[name]));
  1001. }
  1002. // MatrixArray
  1003. for (name in source.matrixArray) {
  1004. material._matrixArrays[name] = new Float32Array(source.matrixArray[name]);
  1005. }
  1006. // Matrix 3x3
  1007. for (name in source.matrices3x3) {
  1008. material.setMatrix3x3(name, source.matrices3x3[name]);
  1009. }
  1010. // Matrix 2x2
  1011. for (name in source.matrices2x2) {
  1012. material.setMatrix2x2(name, source.matrices2x2[name]);
  1013. }
  1014. // Vector2Array
  1015. for (name in source.vectors2Arrays) {
  1016. material.setArray2(name, source.vectors2Arrays[name]);
  1017. }
  1018. // Vector3Array
  1019. for (name in source.vectors3Arrays) {
  1020. material.setArray3(name, source.vectors3Arrays[name]);
  1021. }
  1022. // Vector4Array
  1023. for (name in source.vectors4Arrays) {
  1024. material.setArray4(name, source.vectors4Arrays[name]);
  1025. }
  1026. return material;
  1027. }
  1028. }
  1029. _TypeStore.RegisteredTypes["BABYLON.ShaderMaterial"] = ShaderMaterial;