materialHelper.ts 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  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 { PrePassRenderer } from "../Rendering/prePassRenderer";
  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 positionIndex = scene.prePassRenderer.getIndex(PrePassRenderer.POSITION_TEXTURE_TYPE);
  276. if (positionIndex !== -1) {
  277. defines.PREPASS_POSITION = true;
  278. defines.PREPASS_POSITION_INDEX = positionIndex;
  279. } else {
  280. defines.PREPASS_POSITION = false;
  281. }
  282. const velocityIndex = scene.prePassRenderer.getIndex(PrePassRenderer.VELOCITY_TEXTURE_TYPE);
  283. if (velocityIndex !== -1) {
  284. defines.PREPASS_VELOCITY = true;
  285. defines.PREPASS_VELOCITY_INDEX = velocityIndex;
  286. } else {
  287. defines.PREPASS_VELOCITY = false;
  288. }
  289. const irradianceIndex = scene.prePassRenderer.getIndex(PrePassRenderer.IRRADIANCE_TEXTURE_TYPE);
  290. if (irradianceIndex !== -1) {
  291. defines.PREPASS_IRRADIANCE = true;
  292. defines.PREPASS_IRRADIANCE_INDEX = irradianceIndex;
  293. } else {
  294. defines.PREPASS_IRRADIANCE = false;
  295. }
  296. const albedoIndex = scene.prePassRenderer.getIndex(PrePassRenderer.ALBEDO_TEXTURE_TYPE);
  297. if (albedoIndex !== -1) {
  298. defines.PREPASS_ALBEDO = true;
  299. defines.PREPASS_ALBEDO_INDEX = albedoIndex;
  300. } else {
  301. defines.PREPASS_ALBEDO = false;
  302. }
  303. const depthNormalIndex = scene.prePassRenderer.getIndex(PrePassRenderer.DEPTHNORMAL_TEXTURE_TYPE);
  304. if (depthNormalIndex !== -1) {
  305. defines.PREPASS_DEPTHNORMAL = true;
  306. defines.PREPASS_DEPTHNORMAL_INDEX = depthNormalIndex;
  307. } else {
  308. defines.PREPASS_DEPTHNORMAL = false;
  309. }
  310. } else {
  311. defines.PREPASS = false;
  312. }
  313. if (defines.PREPASS != previousPrePass) {
  314. defines.markAsUnprocessed();
  315. defines.markAsImageProcessingDirty();
  316. }
  317. }
  318. /**
  319. * Prepares the defines related to the light information passed in parameter
  320. * @param scene The scene we are intending to draw
  321. * @param mesh The mesh the effect is compiling for
  322. * @param light The light the effect is compiling for
  323. * @param lightIndex The index of the light
  324. * @param defines The defines to update
  325. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  326. * @param state Defines the current state regarding what is needed (normals, etc...)
  327. */
  328. public static PrepareDefinesForLight(scene: Scene, mesh: AbstractMesh, light: Light, lightIndex: number, defines: any, specularSupported: boolean, state: {
  329. needNormals: boolean,
  330. needRebuild: boolean,
  331. shadowEnabled: boolean,
  332. specularEnabled: boolean,
  333. lightmapMode: boolean
  334. }) {
  335. state.needNormals = true;
  336. if (defines["LIGHT" + lightIndex] === undefined) {
  337. state.needRebuild = true;
  338. }
  339. defines["LIGHT" + lightIndex] = true;
  340. defines["SPOTLIGHT" + lightIndex] = false;
  341. defines["HEMILIGHT" + lightIndex] = false;
  342. defines["POINTLIGHT" + lightIndex] = false;
  343. defines["DIRLIGHT" + lightIndex] = false;
  344. light.prepareLightSpecificDefines(defines, lightIndex);
  345. // FallOff.
  346. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  347. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  348. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  349. switch (light.falloffType) {
  350. case Light.FALLOFF_GLTF:
  351. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  352. break;
  353. case Light.FALLOFF_PHYSICAL:
  354. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  355. break;
  356. case Light.FALLOFF_STANDARD:
  357. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  358. break;
  359. }
  360. // Specular
  361. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  362. state.specularEnabled = true;
  363. }
  364. // Shadows
  365. defines["SHADOW" + lightIndex] = false;
  366. defines["SHADOWCSM" + lightIndex] = false;
  367. defines["SHADOWCSMDEBUG" + lightIndex] = false;
  368. defines["SHADOWCSMNUM_CASCADES" + lightIndex] = false;
  369. defines["SHADOWCSMUSESHADOWMAXZ" + lightIndex] = false;
  370. defines["SHADOWCSMNOBLEND" + lightIndex] = false;
  371. defines["SHADOWCSM_RIGHTHANDED" + lightIndex] = false;
  372. defines["SHADOWPCF" + lightIndex] = false;
  373. defines["SHADOWPCSS" + lightIndex] = false;
  374. defines["SHADOWPOISSON" + lightIndex] = false;
  375. defines["SHADOWESM" + lightIndex] = false;
  376. defines["SHADOWCUBE" + lightIndex] = false;
  377. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  378. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  379. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  380. var shadowGenerator = light.getShadowGenerator();
  381. if (shadowGenerator) {
  382. const shadowMap = shadowGenerator.getShadowMap();
  383. if (shadowMap) {
  384. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  385. state.shadowEnabled = true;
  386. shadowGenerator.prepareDefines(defines, lightIndex);
  387. }
  388. }
  389. }
  390. }
  391. if (light.lightmapMode != Light.LIGHTMAP_DEFAULT) {
  392. state.lightmapMode = true;
  393. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  394. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == Light.LIGHTMAP_SHADOWSONLY);
  395. } else {
  396. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  397. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  398. }
  399. }
  400. /**
  401. * Prepares the defines related to the light information passed in parameter
  402. * @param scene The scene we are intending to draw
  403. * @param mesh The mesh the effect is compiling for
  404. * @param defines The defines to update
  405. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  406. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  407. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  408. * @returns true if normals will be required for the rest of the effect
  409. */
  410. public static PrepareDefinesForLights(scene: Scene, mesh: AbstractMesh, defines: any, specularSupported: boolean, maxSimultaneousLights = 4, disableLighting = false): boolean {
  411. if (!defines._areLightsDirty) {
  412. return defines._needNormals;
  413. }
  414. var lightIndex = 0;
  415. let state = {
  416. needNormals: false,
  417. needRebuild: false,
  418. lightmapMode: false,
  419. shadowEnabled: false,
  420. specularEnabled: false
  421. };
  422. if (scene.lightsEnabled && !disableLighting) {
  423. for (var light of mesh.lightSources) {
  424. this.PrepareDefinesForLight(scene, mesh, light, lightIndex, defines, specularSupported, state);
  425. lightIndex++;
  426. if (lightIndex === maxSimultaneousLights) {
  427. break;
  428. }
  429. }
  430. }
  431. defines["SPECULARTERM"] = state.specularEnabled;
  432. defines["SHADOWS"] = state.shadowEnabled;
  433. // Resetting all other lights if any
  434. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  435. if (defines["LIGHT" + index] !== undefined) {
  436. defines["LIGHT" + index] = false;
  437. defines["HEMILIGHT" + index] = false;
  438. defines["POINTLIGHT" + index] = false;
  439. defines["DIRLIGHT" + index] = false;
  440. defines["SPOTLIGHT" + index] = false;
  441. defines["SHADOW" + index] = false;
  442. defines["SHADOWCSM" + index] = false;
  443. defines["SHADOWCSMDEBUG" + index] = false;
  444. defines["SHADOWCSMNUM_CASCADES" + index] = false;
  445. defines["SHADOWCSMUSESHADOWMAXZ" + index] = false;
  446. defines["SHADOWCSMNOBLEND" + index] = false;
  447. defines["SHADOWCSM_RIGHTHANDED" + index] = false;
  448. defines["SHADOWPCF" + index] = false;
  449. defines["SHADOWPCSS" + index] = false;
  450. defines["SHADOWPOISSON" + index] = false;
  451. defines["SHADOWESM" + index] = false;
  452. defines["SHADOWCUBE" + index] = false;
  453. defines["SHADOWLOWQUALITY" + index] = false;
  454. defines["SHADOWMEDIUMQUALITY" + index] = false;
  455. }
  456. }
  457. let caps = scene.getEngine().getCaps();
  458. if (defines["SHADOWFLOAT"] === undefined) {
  459. state.needRebuild = true;
  460. }
  461. defines["SHADOWFLOAT"] = state.shadowEnabled &&
  462. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  463. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  464. defines["LIGHTMAPEXCLUDED"] = state.lightmapMode;
  465. if (state.needRebuild) {
  466. defines.rebuild();
  467. }
  468. return state.needNormals;
  469. }
  470. /**
  471. * Prepares the uniforms and samplers list to be used in the effect (for a specific light)
  472. * @param lightIndex defines the light index
  473. * @param uniformsList The uniform list
  474. * @param samplersList The sampler list
  475. * @param projectedLightTexture defines if projected texture must be used
  476. * @param uniformBuffersList defines an optional list of uniform buffers
  477. */
  478. public static PrepareUniformsAndSamplersForLight(lightIndex: number, uniformsList: string[], samplersList: string[], projectedLightTexture?: any, uniformBuffersList: Nullable<string[]> = null) {
  479. uniformsList.push(
  480. "vLightData" + lightIndex,
  481. "vLightDiffuse" + lightIndex,
  482. "vLightSpecular" + lightIndex,
  483. "vLightDirection" + lightIndex,
  484. "vLightFalloff" + lightIndex,
  485. "vLightGround" + lightIndex,
  486. "lightMatrix" + lightIndex,
  487. "shadowsInfo" + lightIndex,
  488. "depthValues" + lightIndex,
  489. );
  490. if (uniformBuffersList) {
  491. uniformBuffersList.push("Light" + lightIndex);
  492. }
  493. samplersList.push("shadowSampler" + lightIndex);
  494. samplersList.push("depthSampler" + lightIndex);
  495. uniformsList.push(
  496. "viewFrustumZ" + lightIndex,
  497. "cascadeBlendFactor" + lightIndex,
  498. "lightSizeUVCorrection" + lightIndex,
  499. "depthCorrection" + lightIndex,
  500. "penumbraDarkness" + lightIndex,
  501. "frustumLengths" + lightIndex,
  502. );
  503. if (projectedLightTexture) {
  504. samplersList.push("projectionLightSampler" + lightIndex);
  505. uniformsList.push(
  506. "textureProjectionMatrix" + lightIndex,
  507. );
  508. }
  509. }
  510. /**
  511. * Prepares the uniforms and samplers list to be used in the effect
  512. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  513. * @param samplersList The sampler list
  514. * @param defines The defines helping in the list generation
  515. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  516. */
  517. public static PrepareUniformsAndSamplersList(uniformsListOrOptions: string[] | IEffectCreationOptions, samplersList?: string[], defines?: any, maxSimultaneousLights = 4): void {
  518. let uniformsList: string[];
  519. let uniformBuffersList: Nullable<string[]> = null;
  520. if ((<IEffectCreationOptions>uniformsListOrOptions).uniformsNames) {
  521. var options = <IEffectCreationOptions>uniformsListOrOptions;
  522. uniformsList = options.uniformsNames;
  523. uniformBuffersList = options.uniformBuffersNames;
  524. samplersList = options.samplers;
  525. defines = options.defines;
  526. maxSimultaneousLights = options.maxSimultaneousLights || 0;
  527. } else {
  528. uniformsList = <string[]>uniformsListOrOptions;
  529. if (!samplersList) {
  530. samplersList = [];
  531. }
  532. }
  533. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  534. if (!defines["LIGHT" + lightIndex]) {
  535. break;
  536. }
  537. this.PrepareUniformsAndSamplersForLight(lightIndex, uniformsList, samplersList, defines["PROJECTEDLIGHTTEXTURE" + lightIndex], uniformBuffersList);
  538. }
  539. if (defines["NUM_MORPH_INFLUENCERS"]) {
  540. uniformsList.push("morphTargetInfluences");
  541. }
  542. }
  543. /**
  544. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  545. * @param defines The defines to update while falling back
  546. * @param fallbacks The authorized effect fallbacks
  547. * @param maxSimultaneousLights The maximum number of lights allowed
  548. * @param rank the current rank of the Effect
  549. * @returns The newly affected rank
  550. */
  551. public static HandleFallbacksForShadows(defines: any, fallbacks: EffectFallbacks, maxSimultaneousLights = 4, rank = 0): number {
  552. let lightFallbackRank = 0;
  553. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  554. if (!defines["LIGHT" + lightIndex]) {
  555. break;
  556. }
  557. if (lightIndex > 0) {
  558. lightFallbackRank = rank + lightIndex;
  559. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  560. }
  561. if (!defines["SHADOWS"]) {
  562. if (defines["SHADOW" + lightIndex]) {
  563. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  564. }
  565. if (defines["SHADOWPCF" + lightIndex]) {
  566. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  567. }
  568. if (defines["SHADOWPCSS" + lightIndex]) {
  569. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  570. }
  571. if (defines["SHADOWPOISSON" + lightIndex]) {
  572. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  573. }
  574. if (defines["SHADOWESM" + lightIndex]) {
  575. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  576. }
  577. }
  578. }
  579. return lightFallbackRank++;
  580. }
  581. private static _TmpMorphInfluencers = { "NUM_MORPH_INFLUENCERS": 0 };
  582. /**
  583. * Prepares the list of attributes required for morph targets according to the effect defines.
  584. * @param attribs The current list of supported attribs
  585. * @param mesh The mesh to prepare the morph targets attributes for
  586. * @param influencers The number of influencers
  587. */
  588. public static PrepareAttributesForMorphTargetsInfluencers(attribs: string[], mesh: AbstractMesh, influencers: number): void {
  589. this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS = influencers;
  590. this.PrepareAttributesForMorphTargets(attribs, mesh, this._TmpMorphInfluencers);
  591. }
  592. /**
  593. * Prepares the list of attributes required for morph targets according to the effect defines.
  594. * @param attribs The current list of supported attribs
  595. * @param mesh The mesh to prepare the morph targets attributes for
  596. * @param defines The current Defines of the effect
  597. */
  598. public static PrepareAttributesForMorphTargets(attribs: string[], mesh: AbstractMesh, defines: any): void {
  599. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  600. if (influencers > 0 && EngineStore.LastCreatedEngine) {
  601. var maxAttributesCount = EngineStore.LastCreatedEngine.getCaps().maxVertexAttribs;
  602. var manager = (<Mesh>mesh).morphTargetManager;
  603. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  604. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  605. var uv = manager && manager.supportsUVs && defines["UV1"];
  606. for (var index = 0; index < influencers; index++) {
  607. attribs.push(VertexBuffer.PositionKind + index);
  608. if (normal) {
  609. attribs.push(VertexBuffer.NormalKind + index);
  610. }
  611. if (tangent) {
  612. attribs.push(VertexBuffer.TangentKind + index);
  613. }
  614. if (uv) {
  615. attribs.push(VertexBuffer.UVKind + "_" + index);
  616. }
  617. if (attribs.length > maxAttributesCount) {
  618. Logger.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  619. }
  620. }
  621. }
  622. }
  623. /**
  624. * Prepares the list of attributes required for bones according to the effect defines.
  625. * @param attribs The current list of supported attribs
  626. * @param mesh The mesh to prepare the bones attributes for
  627. * @param defines The current Defines of the effect
  628. * @param fallbacks The current efffect fallback strategy
  629. */
  630. public static PrepareAttributesForBones(attribs: string[], mesh: AbstractMesh, defines: any, fallbacks: EffectFallbacks): void {
  631. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  632. fallbacks.addCPUSkinningFallback(0, mesh);
  633. attribs.push(VertexBuffer.MatricesIndicesKind);
  634. attribs.push(VertexBuffer.MatricesWeightsKind);
  635. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  636. attribs.push(VertexBuffer.MatricesIndicesExtraKind);
  637. attribs.push(VertexBuffer.MatricesWeightsExtraKind);
  638. }
  639. }
  640. }
  641. /**
  642. * Check and prepare the list of attributes required for instances according to the effect defines.
  643. * @param attribs The current list of supported attribs
  644. * @param defines The current MaterialDefines of the effect
  645. */
  646. public static PrepareAttributesForInstances(attribs: string[], defines: MaterialDefines): void {
  647. if (defines["INSTANCES"] || defines["THIN_INSTANCES"]) {
  648. this.PushAttributesForInstances(attribs);
  649. }
  650. }
  651. /**
  652. * Add the list of attributes required for instances to the attribs array.
  653. * @param attribs The current list of supported attribs
  654. */
  655. public static PushAttributesForInstances(attribs: string[]): void {
  656. attribs.push("world0");
  657. attribs.push("world1");
  658. attribs.push("world2");
  659. attribs.push("world3");
  660. }
  661. /**
  662. * Binds the light information to the effect.
  663. * @param light The light containing the generator
  664. * @param effect The effect we are binding the data to
  665. * @param lightIndex The light index in the effect used to render
  666. */
  667. public static BindLightProperties(light: Light, effect: Effect, lightIndex: number): void {
  668. light.transferToEffect(effect, lightIndex + "");
  669. }
  670. /**
  671. * Binds the lights information from the scene to the effect for the given mesh.
  672. * @param light Light to bind
  673. * @param lightIndex Light index
  674. * @param scene The scene where the light belongs to
  675. * @param effect The effect we are binding the data to
  676. * @param useSpecular Defines if specular is supported
  677. * @param rebuildInParallel Specifies whether the shader is rebuilding in parallel
  678. */
  679. public static BindLight(light: Light, lightIndex: number, scene: Scene, effect: Effect, useSpecular: boolean, rebuildInParallel = false): void {
  680. light._bindLight(lightIndex, scene, effect, useSpecular, rebuildInParallel);
  681. }
  682. /**
  683. * Binds the lights information from the scene to the effect for the given mesh.
  684. * @param scene The scene the lights belongs to
  685. * @param mesh The mesh we are binding the information to render
  686. * @param effect The effect we are binding the data to
  687. * @param defines The generated defines for the effect
  688. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  689. * @param rebuildInParallel Specifies whether the shader is rebuilding in parallel
  690. */
  691. public static BindLights(scene: Scene, mesh: AbstractMesh, effect: Effect, defines: any, maxSimultaneousLights = 4, rebuildInParallel = false): void {
  692. let len = Math.min(mesh.lightSources.length, maxSimultaneousLights);
  693. for (var i = 0; i < len; i++) {
  694. let light = mesh.lightSources[i];
  695. this.BindLight(light, i, scene, effect, typeof defines === "boolean" ? defines : defines["SPECULARTERM"], rebuildInParallel);
  696. }
  697. }
  698. private static _tempFogColor = Color3.Black();
  699. /**
  700. * Binds the fog information from the scene to the effect for the given mesh.
  701. * @param scene The scene the lights belongs to
  702. * @param mesh The mesh we are binding the information to render
  703. * @param effect The effect we are binding the data to
  704. * @param linearSpace Defines if the fog effect is applied in linear space
  705. */
  706. public static BindFogParameters(scene: Scene, mesh: AbstractMesh, effect: Effect, linearSpace = false): void {
  707. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) {
  708. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  709. // Convert fog color to linear space if used in a linear space computed shader.
  710. if (linearSpace) {
  711. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  712. effect.setColor3("vFogColor", this._tempFogColor);
  713. }
  714. else {
  715. effect.setColor3("vFogColor", scene.fogColor);
  716. }
  717. }
  718. }
  719. /**
  720. * Binds the bones information from the mesh to the effect.
  721. * @param mesh The mesh we are binding the information to render
  722. * @param effect The effect we are binding the data to
  723. */
  724. public static BindBonesParameters(mesh?: AbstractMesh, effect?: Effect): void {
  725. if (!effect || !mesh) {
  726. return;
  727. }
  728. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  729. mesh.computeBonesUsingShaders = false;
  730. }
  731. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  732. const skeleton = mesh.skeleton;
  733. if (skeleton.isUsingTextureForMatrices && effect.getUniformIndex("boneTextureWidth") > -1) {
  734. const boneTexture = skeleton.getTransformMatrixTexture(mesh);
  735. effect.setTexture("boneSampler", boneTexture);
  736. effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
  737. } else {
  738. const matrices = skeleton.getTransformMatrices(mesh);
  739. if (matrices) {
  740. effect.setMatrices("mBones", matrices);
  741. }
  742. }
  743. }
  744. }
  745. /**
  746. * Binds the morph targets information from the mesh to the effect.
  747. * @param abstractMesh The mesh we are binding the information to render
  748. * @param effect The effect we are binding the data to
  749. */
  750. public static BindMorphTargetParameters(abstractMesh: AbstractMesh, effect: Effect): void {
  751. let manager = (<Mesh>abstractMesh).morphTargetManager;
  752. if (!abstractMesh || !manager) {
  753. return;
  754. }
  755. effect.setFloatArray("morphTargetInfluences", manager.influences);
  756. }
  757. /**
  758. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  759. * @param defines The generated defines used in the effect
  760. * @param effect The effect we are binding the data to
  761. * @param scene The scene we are willing to render with logarithmic scale for
  762. */
  763. public static BindLogDepth(defines: any, effect: Effect, scene: Scene): void {
  764. if (defines["LOGARITHMICDEPTH"]) {
  765. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log((<Camera>scene.activeCamera).maxZ + 1.0) / Math.LN2));
  766. }
  767. }
  768. /**
  769. * Binds the clip plane information from the scene to the effect.
  770. * @param scene The scene the clip plane information are extracted from
  771. * @param effect The effect we are binding the data to
  772. */
  773. public static BindClipPlane(effect: Effect, scene: Scene): void {
  774. ThinMaterialHelper.BindClipPlane(effect, scene);
  775. }
  776. }