materialHelper.ts 40 KB

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