materialHelper.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  1. import { Logger } from "../Misc/logger";
  2. import { Nullable } from "../types";
  3. import { Camera } from "../Cameras/camera";
  4. import { Scene } from "../scene";
  5. import { Engine } from "../Engines/engine";
  6. import { EngineStore } from "../Engines/engineStore";
  7. import { AbstractMesh } from "../Meshes/abstractMesh";
  8. import { Mesh } from "../Meshes/mesh";
  9. import { VertexBuffer } from "../Meshes/buffer";
  10. import { Light } from "../Lights/light";
  11. import { UniformBuffer } from "./uniformBuffer";
  12. import { Effect, IEffectCreationOptions } from "./effect";
  13. import { BaseTexture } from "../Materials/Textures/baseTexture";
  14. import { WebVRFreeCamera } from '../Cameras/VR/webVRCamera';
  15. import { MaterialDefines } from "./materialDefines";
  16. import { Color3, TmpColors } from '../Maths/math.color';
  17. import { EffectFallbacks } from './effectFallbacks';
  18. /**
  19. * "Static Class" containing the most commonly used helper while dealing with material for
  20. * rendering purpose.
  21. *
  22. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  23. *
  24. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  25. */
  26. export class MaterialHelper {
  27. /**
  28. * Bind the current view position to an effect.
  29. * @param effect The effect to be bound
  30. * @param scene The scene the eyes position is used from
  31. */
  32. public static BindEyePosition(effect: Effect, scene: Scene): void {
  33. if (scene._forcedViewPosition) {
  34. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  35. return;
  36. }
  37. var globalPosition = scene.activeCamera!.globalPosition;
  38. if (!globalPosition) {
  39. // Use WebVRFreecamera's device position as global position is not it's actual position in babylon space
  40. globalPosition = (scene.activeCamera! as WebVRFreeCamera).devicePosition;
  41. }
  42. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : globalPosition);
  43. }
  44. /**
  45. * Helps preparing the defines values about the UVs in used in the effect.
  46. * UVs are shared as much as we can accross channels in the shaders.
  47. * @param texture The texture we are preparing the UVs for
  48. * @param defines The defines to update
  49. * @param key The channel key "diffuse", "specular"... used in the shader
  50. */
  51. public static PrepareDefinesForMergedUV(texture: BaseTexture, defines: any, key: string): void {
  52. defines._needUVs = true;
  53. defines[key] = true;
  54. if (texture.getTextureMatrix().isIdentityAs3x2()) {
  55. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  56. if (texture.coordinatesIndex === 0) {
  57. defines["MAINUV1"] = true;
  58. } else {
  59. defines["MAINUV2"] = true;
  60. }
  61. } else {
  62. defines[key + "DIRECTUV"] = 0;
  63. }
  64. }
  65. /**
  66. * Binds a texture matrix value to its corrsponding uniform
  67. * @param texture The texture to bind the matrix for
  68. * @param uniformBuffer The uniform buffer receivin the data
  69. * @param key The channel key "diffuse", "specular"... used in the shader
  70. */
  71. public static BindTextureMatrix(texture: BaseTexture, uniformBuffer: UniformBuffer, key: string): void {
  72. var matrix = texture.getTextureMatrix();
  73. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  74. }
  75. /**
  76. * Gets the current status of the fog (should it be enabled?)
  77. * @param mesh defines the mesh to evaluate for fog support
  78. * @param scene defines the hosting scene
  79. * @returns true if fog must be enabled
  80. */
  81. public static GetFogState(mesh: AbstractMesh, scene: Scene) {
  82. return (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE);
  83. }
  84. /**
  85. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  86. * @param mesh defines the current mesh
  87. * @param scene defines the current scene
  88. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  89. * @param pointsCloud defines if point cloud rendering has to be turned on
  90. * @param fogEnabled defines if fog has to be turned on
  91. * @param alphaTest defines if alpha testing has to be turned on
  92. * @param defines defines the current list of defines
  93. */
  94. public static PrepareDefinesForMisc(mesh: AbstractMesh, scene: Scene, useLogarithmicDepth: boolean, pointsCloud: boolean, fogEnabled: boolean, alphaTest: boolean, defines: any): void {
  95. if (defines._areMiscDirty) {
  96. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  97. defines["POINTSIZE"] = pointsCloud;
  98. defines["FOG"] = fogEnabled && this.GetFogState(mesh, scene);
  99. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  100. defines["ALPHATEST"] = alphaTest;
  101. }
  102. }
  103. /**
  104. * Helper used to prepare the list of defines associated with frame values for shader compilation
  105. * @param scene defines the current scene
  106. * @param engine defines the current engine
  107. * @param defines specifies the list of active defines
  108. * @param useInstances defines if instances have to be turned on
  109. * @param useClipPlane defines if clip plane have to be turned on
  110. */
  111. public static PrepareDefinesForFrameBoundValues(scene: Scene, engine: Engine, defines: any, useInstances: boolean, useClipPlane: Nullable<boolean> = null): void {
  112. var changed = false;
  113. let useClipPlane1 = false;
  114. let useClipPlane2 = false;
  115. let useClipPlane3 = false;
  116. let useClipPlane4 = false;
  117. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  118. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  119. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  120. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  121. if (defines["CLIPPLANE"] !== useClipPlane1) {
  122. defines["CLIPPLANE"] = useClipPlane1;
  123. changed = true;
  124. }
  125. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  126. defines["CLIPPLANE2"] = useClipPlane2;
  127. changed = true;
  128. }
  129. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  130. defines["CLIPPLANE3"] = useClipPlane3;
  131. changed = true;
  132. }
  133. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  134. defines["CLIPPLANE4"] = useClipPlane4;
  135. changed = true;
  136. }
  137. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  138. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  139. changed = true;
  140. }
  141. if (defines["INSTANCES"] !== useInstances) {
  142. defines["INSTANCES"] = useInstances;
  143. changed = true;
  144. }
  145. if (changed) {
  146. defines.markAsUnprocessed();
  147. }
  148. }
  149. /**
  150. * Prepares the defines for bones
  151. * @param mesh The mesh containing the geometry data we will draw
  152. * @param defines The defines to update
  153. */
  154. public static PrepareDefinesForBones(mesh: AbstractMesh, defines: any) {
  155. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  156. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  157. const materialSupportsBoneTexture = defines["BONETEXTURE"] !== undefined;
  158. if (mesh.skeleton.isUsingTextureForMatrices && materialSupportsBoneTexture) {
  159. defines["BONETEXTURE"] = true;
  160. } else {
  161. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  162. defines["BONETEXTURE"] = materialSupportsBoneTexture ? false : undefined;
  163. }
  164. } else {
  165. defines["NUM_BONE_INFLUENCERS"] = 0;
  166. defines["BonesPerMesh"] = 0;
  167. }
  168. }
  169. /**
  170. * Prepares the defines for morph targets
  171. * @param mesh The mesh containing the geometry data we will draw
  172. * @param defines The defines to update
  173. */
  174. public static PrepareDefinesForMorphTargets(mesh: AbstractMesh, defines: any) {
  175. var manager = (<Mesh>mesh).morphTargetManager;
  176. if (manager) {
  177. defines["MORPHTARGETS_UV"] = manager.supportsUVs && defines["UV1"];
  178. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  179. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  180. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  181. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  182. } else {
  183. defines["MORPHTARGETS_UV"] = false;
  184. defines["MORPHTARGETS_TANGENT"] = false;
  185. defines["MORPHTARGETS_NORMAL"] = false;
  186. defines["MORPHTARGETS"] = false;
  187. defines["NUM_MORPH_INFLUENCERS"] = 0;
  188. }
  189. }
  190. /**
  191. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  192. * @param mesh The mesh containing the geometry data we will draw
  193. * @param defines The defines to update
  194. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  195. * @param useBones Precise whether bones should be used or not (override mesh info)
  196. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  197. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  198. * @returns false if defines are considered not dirty and have not been checked
  199. */
  200. public static PrepareDefinesForAttributes(mesh: AbstractMesh, defines: any, useVertexColor: boolean, useBones: boolean, useMorphTargets = false, useVertexAlpha = true): boolean {
  201. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  202. return false;
  203. }
  204. defines._normals = defines._needNormals;
  205. defines._uvs = defines._needUVs;
  206. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(VertexBuffer.NormalKind));
  207. if (defines._needNormals && mesh.isVerticesDataPresent(VertexBuffer.TangentKind)) {
  208. defines["TANGENT"] = true;
  209. }
  210. if (defines._needUVs) {
  211. defines["UV1"] = mesh.isVerticesDataPresent(VertexBuffer.UVKind);
  212. defines["UV2"] = mesh.isVerticesDataPresent(VertexBuffer.UV2Kind);
  213. } else {
  214. defines["UV1"] = false;
  215. defines["UV2"] = false;
  216. }
  217. if (useVertexColor) {
  218. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(VertexBuffer.ColorKind);
  219. defines["VERTEXCOLOR"] = hasVertexColors;
  220. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  221. }
  222. if (useBones) {
  223. this.PrepareDefinesForBones(mesh, defines);
  224. }
  225. if (useMorphTargets) {
  226. this.PrepareDefinesForMorphTargets(mesh, defines);
  227. }
  228. return true;
  229. }
  230. /**
  231. * Prepares the defines related to multiview
  232. * @param scene The scene we are intending to draw
  233. * @param defines The defines to update
  234. */
  235. public static PrepareDefinesForMultiview(scene: Scene, defines: any) {
  236. if (scene.activeCamera) {
  237. var previousMultiview = defines.MULTIVIEW;
  238. defines.MULTIVIEW = (scene.activeCamera.outputRenderTarget !== null && scene.activeCamera.outputRenderTarget.getViewCount() > 1);
  239. if (defines.MULTIVIEW != previousMultiview) {
  240. defines.markAsUnprocessed();
  241. }
  242. }
  243. }
  244. /**
  245. * Prepares the defines related to the light information passed in parameter
  246. * @param scene The scene we are intending to draw
  247. * @param mesh The mesh the effect is compiling for
  248. * @param light The light the effect is compiling for
  249. * @param lightIndex The index of the light
  250. * @param defines The defines to update
  251. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  252. * @param state Defines the current state regarding what is needed (normals, etc...)
  253. */
  254. public static PrepareDefinesForLight(scene: Scene, mesh: AbstractMesh, light: Light, lightIndex: number, defines: any, specularSupported: boolean, state: {
  255. needNormals: boolean,
  256. needRebuild: boolean,
  257. shadowEnabled: boolean,
  258. specularEnabled: boolean,
  259. lightmapMode: boolean
  260. }) {
  261. state.needNormals = true;
  262. if (defines["LIGHT" + lightIndex] === undefined) {
  263. state.needRebuild = true;
  264. }
  265. defines["LIGHT" + lightIndex] = true;
  266. defines["SPOTLIGHT" + lightIndex] = false;
  267. defines["HEMILIGHT" + lightIndex] = false;
  268. defines["POINTLIGHT" + lightIndex] = false;
  269. defines["DIRLIGHT" + lightIndex] = false;
  270. light.prepareLightSpecificDefines(defines, lightIndex);
  271. // FallOff.
  272. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  273. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  274. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  275. switch (light.falloffType) {
  276. case Light.FALLOFF_GLTF:
  277. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  278. break;
  279. case Light.FALLOFF_PHYSICAL:
  280. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  281. break;
  282. case Light.FALLOFF_STANDARD:
  283. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  284. break;
  285. }
  286. // Specular
  287. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  288. state.specularEnabled = true;
  289. }
  290. // Shadows
  291. defines["SHADOW" + lightIndex] = false;
  292. defines["SHADOWPCF" + lightIndex] = false;
  293. defines["SHADOWPCSS" + lightIndex] = false;
  294. defines["SHADOWPOISSON" + lightIndex] = false;
  295. defines["SHADOWESM" + lightIndex] = false;
  296. defines["SHADOWCUBE" + lightIndex] = false;
  297. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  298. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  299. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  300. var shadowGenerator = light.getShadowGenerator();
  301. if (shadowGenerator) {
  302. const shadowMap = shadowGenerator.getShadowMap();
  303. if (shadowMap) {
  304. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  305. state.shadowEnabled = true;
  306. shadowGenerator.prepareDefines(defines, lightIndex);
  307. }
  308. }
  309. }
  310. }
  311. if (light.lightmapMode != Light.LIGHTMAP_DEFAULT) {
  312. state.lightmapMode = true;
  313. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  314. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == Light.LIGHTMAP_SHADOWSONLY);
  315. } else {
  316. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  317. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  318. }
  319. }
  320. /**
  321. * Prepares the defines related to the light information passed in parameter
  322. * @param scene The scene we are intending to draw
  323. * @param mesh The mesh the effect is compiling for
  324. * @param defines The defines to update
  325. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  326. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  327. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  328. * @returns true if normals will be required for the rest of the effect
  329. */
  330. public static PrepareDefinesForLights(scene: Scene, mesh: AbstractMesh, defines: any, specularSupported: boolean, maxSimultaneousLights = 4, disableLighting = false): boolean {
  331. if (!defines._areLightsDirty) {
  332. return defines._needNormals;
  333. }
  334. var lightIndex = 0;
  335. let state = {
  336. needNormals: false,
  337. needRebuild: false,
  338. lightmapMode: false,
  339. shadowEnabled: false,
  340. specularEnabled: false
  341. };
  342. if (scene.lightsEnabled && !disableLighting) {
  343. for (var light of mesh.lightSources) {
  344. this.PrepareDefinesForLight(scene, mesh, light, lightIndex, defines, specularSupported, state);
  345. lightIndex++;
  346. if (lightIndex === maxSimultaneousLights) {
  347. break;
  348. }
  349. }
  350. }
  351. defines["SPECULARTERM"] = state.specularEnabled;
  352. defines["SHADOWS"] = state.shadowEnabled;
  353. // Resetting all other lights if any
  354. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  355. if (defines["LIGHT" + index] !== undefined) {
  356. defines["LIGHT" + index] = false;
  357. defines["HEMILIGHT" + index] = false;
  358. defines["POINTLIGHT" + index] = false;
  359. defines["DIRLIGHT" + index] = false;
  360. defines["SPOTLIGHT" + index] = false;
  361. defines["SHADOW" + index] = false;
  362. defines["SHADOWPCF" + index] = false;
  363. defines["SHADOWPCSS" + index] = false;
  364. defines["SHADOWPOISSON" + index] = false;
  365. defines["SHADOWESM" + index] = false;
  366. defines["SHADOWCUBE" + index] = false;
  367. defines["SHADOWLOWQUALITY" + index] = false;
  368. defines["SHADOWMEDIUMQUALITY" + index] = false;
  369. }
  370. }
  371. let caps = scene.getEngine().getCaps();
  372. if (defines["SHADOWFLOAT"] === undefined) {
  373. state.needRebuild = true;
  374. }
  375. defines["SHADOWFLOAT"] = state.shadowEnabled &&
  376. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  377. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  378. defines["LIGHTMAPEXCLUDED"] = state.lightmapMode;
  379. if (state.needRebuild) {
  380. defines.rebuild();
  381. }
  382. return state.needNormals;
  383. }
  384. /**
  385. * Prepares the uniforms and samplers list to be used in the effect (for a specific light)
  386. * @param lightIndex defines the light index
  387. * @param uniformsList The uniform list
  388. * @param samplersList The sampler list
  389. * @param projectedLightTexture defines if projected texture must be used
  390. * @param uniformBuffersList defines an optional list of uniform buffers
  391. */
  392. public static PrepareUniformsAndSamplersForLight(lightIndex: number, uniformsList: string[], samplersList: string[], projectedLightTexture?: any, uniformBuffersList: Nullable<string[]> = null) {
  393. uniformsList.push(
  394. "vLightData" + lightIndex,
  395. "vLightDiffuse" + lightIndex,
  396. "vLightSpecular" + lightIndex,
  397. "vLightDirection" + lightIndex,
  398. "vLightFalloff" + lightIndex,
  399. "vLightGround" + lightIndex,
  400. "lightMatrix" + lightIndex,
  401. "shadowsInfo" + lightIndex,
  402. "depthValues" + lightIndex,
  403. );
  404. if (uniformBuffersList) {
  405. uniformBuffersList.push("Light" + lightIndex);
  406. }
  407. samplersList.push("shadowSampler" + lightIndex);
  408. samplersList.push("depthSampler" + lightIndex);
  409. if (projectedLightTexture) {
  410. samplersList.push("projectionLightSampler" + lightIndex);
  411. uniformsList.push(
  412. "textureProjectionMatrix" + lightIndex,
  413. );
  414. }
  415. }
  416. /**
  417. * Prepares the uniforms and samplers list to be used in the effect
  418. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  419. * @param samplersList The sampler list
  420. * @param defines The defines helping in the list generation
  421. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  422. */
  423. public static PrepareUniformsAndSamplersList(uniformsListOrOptions: string[] | IEffectCreationOptions, samplersList?: string[], defines?: any, maxSimultaneousLights = 4): void {
  424. let uniformsList: string[];
  425. let uniformBuffersList: Nullable<string[]> = null;
  426. if ((<IEffectCreationOptions>uniformsListOrOptions).uniformsNames) {
  427. var options = <IEffectCreationOptions>uniformsListOrOptions;
  428. uniformsList = options.uniformsNames;
  429. uniformBuffersList = options.uniformBuffersNames;
  430. samplersList = options.samplers;
  431. defines = options.defines;
  432. maxSimultaneousLights = options.maxSimultaneousLights || 0;
  433. } else {
  434. uniformsList = <string[]>uniformsListOrOptions;
  435. if (!samplersList) {
  436. samplersList = [];
  437. }
  438. }
  439. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  440. if (!defines["LIGHT" + lightIndex]) {
  441. break;
  442. }
  443. this.PrepareUniformsAndSamplersForLight(lightIndex, uniformsList, samplersList, defines["PROJECTEDLIGHTTEXTURE" + lightIndex], uniformBuffersList);
  444. }
  445. if (defines["NUM_MORPH_INFLUENCERS"]) {
  446. uniformsList.push("morphTargetInfluences");
  447. }
  448. }
  449. /**
  450. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  451. * @param defines The defines to update while falling back
  452. * @param fallbacks The authorized effect fallbacks
  453. * @param maxSimultaneousLights The maximum number of lights allowed
  454. * @param rank the current rank of the Effect
  455. * @returns The newly affected rank
  456. */
  457. public static HandleFallbacksForShadows(defines: any, fallbacks: EffectFallbacks, maxSimultaneousLights = 4, rank = 0): number {
  458. let lightFallbackRank = 0;
  459. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  460. if (!defines["LIGHT" + lightIndex]) {
  461. break;
  462. }
  463. if (lightIndex > 0) {
  464. lightFallbackRank = rank + lightIndex;
  465. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  466. }
  467. if (!defines["SHADOWS"]) {
  468. if (defines["SHADOW" + lightIndex]) {
  469. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  470. }
  471. if (defines["SHADOWPCF" + lightIndex]) {
  472. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  473. }
  474. if (defines["SHADOWPCSS" + lightIndex]) {
  475. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  476. }
  477. if (defines["SHADOWPOISSON" + lightIndex]) {
  478. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  479. }
  480. if (defines["SHADOWESM" + lightIndex]) {
  481. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  482. }
  483. }
  484. }
  485. return lightFallbackRank++;
  486. }
  487. private static _TmpMorphInfluencers = { "NUM_MORPH_INFLUENCERS": 0 };
  488. /**
  489. * Prepares the list of attributes required for morph targets according to the effect defines.
  490. * @param attribs The current list of supported attribs
  491. * @param mesh The mesh to prepare the morph targets attributes for
  492. * @param influencers The number of influencers
  493. */
  494. public static PrepareAttributesForMorphTargetsInfluencers(attribs: string[], mesh: AbstractMesh, influencers: number): void {
  495. this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS = influencers;
  496. this.PrepareAttributesForMorphTargets(attribs, mesh, this._TmpMorphInfluencers);
  497. }
  498. /**
  499. * Prepares the list of attributes required for morph targets according to the effect defines.
  500. * @param attribs The current list of supported attribs
  501. * @param mesh The mesh to prepare the morph targets attributes for
  502. * @param defines The current Defines of the effect
  503. */
  504. public static PrepareAttributesForMorphTargets(attribs: string[], mesh: AbstractMesh, defines: any): void {
  505. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  506. if (influencers > 0 && EngineStore.LastCreatedEngine) {
  507. var maxAttributesCount = EngineStore.LastCreatedEngine.getCaps().maxVertexAttribs;
  508. var manager = (<Mesh>mesh).morphTargetManager;
  509. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  510. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  511. var uv = manager && manager.supportsUVs && defines["UV1"];
  512. for (var index = 0; index < influencers; index++) {
  513. attribs.push(VertexBuffer.PositionKind + index);
  514. if (normal) {
  515. attribs.push(VertexBuffer.NormalKind + index);
  516. }
  517. if (tangent) {
  518. attribs.push(VertexBuffer.TangentKind + index);
  519. }
  520. if (uv) {
  521. attribs.push(VertexBuffer.UVKind + "_" + index);
  522. }
  523. if (attribs.length > maxAttributesCount) {
  524. Logger.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  525. }
  526. }
  527. }
  528. }
  529. /**
  530. * Prepares the list of attributes required for bones according to the effect defines.
  531. * @param attribs The current list of supported attribs
  532. * @param mesh The mesh to prepare the bones attributes for
  533. * @param defines The current Defines of the effect
  534. * @param fallbacks The current efffect fallback strategy
  535. */
  536. public static PrepareAttributesForBones(attribs: string[], mesh: AbstractMesh, defines: any, fallbacks: EffectFallbacks): void {
  537. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  538. fallbacks.addCPUSkinningFallback(0, mesh);
  539. attribs.push(VertexBuffer.MatricesIndicesKind);
  540. attribs.push(VertexBuffer.MatricesWeightsKind);
  541. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  542. attribs.push(VertexBuffer.MatricesIndicesExtraKind);
  543. attribs.push(VertexBuffer.MatricesWeightsExtraKind);
  544. }
  545. }
  546. }
  547. /**
  548. * Check and prepare the list of attributes required for instances according to the effect defines.
  549. * @param attribs The current list of supported attribs
  550. * @param defines The current MaterialDefines of the effect
  551. */
  552. public static PrepareAttributesForInstances(attribs: string[], defines: MaterialDefines): void {
  553. if (defines["INSTANCES"]) {
  554. this.PushAttributesForInstances(attribs);
  555. }
  556. }
  557. /**
  558. * Add the list of attributes required for instances to the attribs array.
  559. * @param attribs The current list of supported attribs
  560. */
  561. public static PushAttributesForInstances(attribs: string[]): void {
  562. attribs.push("world0");
  563. attribs.push("world1");
  564. attribs.push("world2");
  565. attribs.push("world3");
  566. }
  567. /**
  568. * Binds the light information to the effect.
  569. * @param light The light containing the generator
  570. * @param effect The effect we are binding the data to
  571. * @param lightIndex The light index in the effect used to render
  572. */
  573. public static BindLightProperties(light: Light, effect: Effect, lightIndex: number): void {
  574. light.transferToEffect(effect, lightIndex + "");
  575. }
  576. /**
  577. * Binds the lights information from the scene to the effect for the given mesh.
  578. * @param light Light to bind
  579. * @param lightIndex Light index
  580. * @param scene The scene where the light belongs to
  581. * @param effect The effect we are binding the data to
  582. * @param useSpecular Defines if specular is supported
  583. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  584. * @param rebuildInParallel Specifies whether the shader is rebuilding in parallel
  585. */
  586. public static BindLight(light: Light, lightIndex: number, scene: Scene, effect: Effect, useSpecular: boolean, usePhysicalLightFalloff = false, rebuildInParallel = false): void {
  587. let iAsString = lightIndex.toString();
  588. let needUpdate = false;
  589. if (rebuildInParallel && light._uniformBuffer._alreadyBound) {
  590. return;
  591. }
  592. light._uniformBuffer.bindToEffect(effect, "Light" + iAsString);
  593. if (light._renderId !== scene.getRenderId() || !light._uniformBuffer.useUbo) {
  594. light._renderId = scene.getRenderId();
  595. let scaledIntensity = light.getScaledIntensity();
  596. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  597. light.diffuse.scaleToRef(scaledIntensity, TmpColors.Color3[0]);
  598. light._uniformBuffer.updateColor4("vLightDiffuse", TmpColors.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  599. if (useSpecular) {
  600. light.specular.scaleToRef(scaledIntensity, TmpColors.Color3[1]);
  601. light._uniformBuffer.updateColor3("vLightSpecular", TmpColors.Color3[1], iAsString);
  602. }
  603. needUpdate = true;
  604. }
  605. // Shadows
  606. if (scene.shadowsEnabled && light.shadowEnabled) {
  607. var shadowGenerator = light.getShadowGenerator();
  608. if (shadowGenerator) {
  609. shadowGenerator.bindShadowLight(iAsString, effect);
  610. needUpdate = true;
  611. }
  612. }
  613. if (needUpdate) {
  614. light._uniformBuffer.update();
  615. }
  616. }
  617. /**
  618. * Binds the lights information from the scene to the effect for the given mesh.
  619. * @param scene The scene the lights belongs to
  620. * @param mesh The mesh we are binding the information to render
  621. * @param effect The effect we are binding the data to
  622. * @param defines The generated defines for the effect
  623. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  624. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  625. * @param rebuildInParallel Specifies whether the shader is rebuilding in parallel
  626. */
  627. public static BindLights(scene: Scene, mesh: AbstractMesh, effect: Effect, defines: any, maxSimultaneousLights = 4, usePhysicalLightFalloff = false, rebuildInParallel = false): void {
  628. let len = Math.min(mesh.lightSources.length, maxSimultaneousLights);
  629. for (var i = 0; i < len; i++) {
  630. let light = mesh.lightSources[i];
  631. this.BindLight(light, i, scene, effect, typeof defines === "boolean" ? defines : defines["SPECULARTERM"], usePhysicalLightFalloff, rebuildInParallel);
  632. }
  633. }
  634. private static _tempFogColor = Color3.Black();
  635. /**
  636. * Binds the fog information from the scene to the effect for the given mesh.
  637. * @param scene The scene the lights belongs to
  638. * @param mesh The mesh we are binding the information to render
  639. * @param effect The effect we are binding the data to
  640. * @param linearSpace Defines if the fog effect is applied in linear space
  641. */
  642. public static BindFogParameters(scene: Scene, mesh: AbstractMesh, effect: Effect, linearSpace = false): void {
  643. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) {
  644. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  645. // Convert fog color to linear space if used in a linear space computed shader.
  646. if (linearSpace) {
  647. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  648. effect.setColor3("vFogColor", this._tempFogColor);
  649. }
  650. else {
  651. effect.setColor3("vFogColor", scene.fogColor);
  652. }
  653. }
  654. }
  655. /**
  656. * Binds the bones information from the mesh to the effect.
  657. * @param mesh The mesh we are binding the information to render
  658. * @param effect The effect we are binding the data to
  659. */
  660. public static BindBonesParameters(mesh?: AbstractMesh, effect?: Effect): void {
  661. if (!effect || !mesh) {
  662. return;
  663. }
  664. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  665. mesh.computeBonesUsingShaders = false;
  666. }
  667. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  668. const skeleton = mesh.skeleton;
  669. if (skeleton.isUsingTextureForMatrices && effect.getUniformIndex("boneTextureWidth") > -1) {
  670. const boneTexture = skeleton.getTransformMatrixTexture(mesh);
  671. effect.setTexture("boneSampler", boneTexture);
  672. effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
  673. } else {
  674. const matrices = skeleton.getTransformMatrices(mesh);
  675. if (matrices) {
  676. effect.setMatrices("mBones", matrices);
  677. }
  678. }
  679. }
  680. }
  681. /**
  682. * Binds the morph targets information from the mesh to the effect.
  683. * @param abstractMesh The mesh we are binding the information to render
  684. * @param effect The effect we are binding the data to
  685. */
  686. public static BindMorphTargetParameters(abstractMesh: AbstractMesh, effect: Effect): void {
  687. let manager = (<Mesh>abstractMesh).morphTargetManager;
  688. if (!abstractMesh || !manager) {
  689. return;
  690. }
  691. effect.setFloatArray("morphTargetInfluences", manager.influences);
  692. }
  693. /**
  694. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  695. * @param defines The generated defines used in the effect
  696. * @param effect The effect we are binding the data to
  697. * @param scene The scene we are willing to render with logarithmic scale for
  698. */
  699. public static BindLogDepth(defines: any, effect: Effect, scene: Scene): void {
  700. if (defines["LOGARITHMICDEPTH"]) {
  701. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log((<Camera>scene.activeCamera).maxZ + 1.0) / Math.LN2));
  702. }
  703. }
  704. /**
  705. * Binds the clip plane information from the scene to the effect.
  706. * @param scene The scene the clip plane information are extracted from
  707. * @param effect The effect we are binding the data to
  708. */
  709. public static BindClipPlane(effect: Effect, scene: Scene): void {
  710. if (scene.clipPlane) {
  711. let clipPlane = scene.clipPlane;
  712. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  713. }
  714. if (scene.clipPlane2) {
  715. let clipPlane = scene.clipPlane2;
  716. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  717. }
  718. if (scene.clipPlane3) {
  719. let clipPlane = scene.clipPlane3;
  720. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  721. }
  722. if (scene.clipPlane4) {
  723. let clipPlane = scene.clipPlane4;
  724. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  725. }
  726. }
  727. }