materialHelper.ts 38 KB

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