materialHelper.ts 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  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["SHADOWCUBE" + lightIndex] = false;
  394. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  395. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  396. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  397. var shadowGenerator = light.getShadowGenerator();
  398. if (shadowGenerator) {
  399. const shadowMap = shadowGenerator.getShadowMap();
  400. if (shadowMap) {
  401. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  402. state.shadowEnabled = true;
  403. shadowGenerator.prepareDefines(defines, lightIndex);
  404. }
  405. }
  406. }
  407. }
  408. if (light.lightmapMode != Light.LIGHTMAP_DEFAULT) {
  409. state.lightmapMode = true;
  410. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  411. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == Light.LIGHTMAP_SHADOWSONLY);
  412. } else {
  413. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  414. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  415. }
  416. }
  417. /**
  418. * Prepares the defines related to the light information passed in parameter
  419. * @param scene The scene we are intending to draw
  420. * @param mesh The mesh the effect is compiling for
  421. * @param defines The defines to update
  422. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  423. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  424. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  425. * @returns true if normals will be required for the rest of the effect
  426. */
  427. public static PrepareDefinesForLights(scene: Scene, mesh: AbstractMesh, defines: any, specularSupported: boolean, maxSimultaneousLights = 4, disableLighting = false): boolean {
  428. if (!defines._areLightsDirty) {
  429. return defines._needNormals;
  430. }
  431. var lightIndex = 0;
  432. let state = {
  433. needNormals: false,
  434. needRebuild: false,
  435. lightmapMode: false,
  436. shadowEnabled: false,
  437. specularEnabled: false
  438. };
  439. if (scene.lightsEnabled && !disableLighting) {
  440. for (var light of mesh.lightSources) {
  441. this.PrepareDefinesForLight(scene, mesh, light, lightIndex, defines, specularSupported, state);
  442. lightIndex++;
  443. if (lightIndex === maxSimultaneousLights) {
  444. break;
  445. }
  446. }
  447. }
  448. defines["SPECULARTERM"] = state.specularEnabled;
  449. defines["SHADOWS"] = state.shadowEnabled;
  450. // Resetting all other lights if any
  451. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  452. if (defines["LIGHT" + index] !== undefined) {
  453. defines["LIGHT" + index] = false;
  454. defines["HEMILIGHT" + index] = false;
  455. defines["POINTLIGHT" + index] = false;
  456. defines["DIRLIGHT" + index] = false;
  457. defines["SPOTLIGHT" + index] = false;
  458. defines["SHADOW" + index] = false;
  459. defines["SHADOWCSM" + index] = false;
  460. defines["SHADOWCSMDEBUG" + index] = false;
  461. defines["SHADOWCSMNUM_CASCADES" + index] = false;
  462. defines["SHADOWCSMUSESHADOWMAXZ" + index] = false;
  463. defines["SHADOWCSMNOBLEND" + index] = false;
  464. defines["SHADOWCSM_RIGHTHANDED" + index] = false;
  465. defines["SHADOWPCF" + index] = false;
  466. defines["SHADOWPCSS" + index] = false;
  467. defines["SHADOWPOISSON" + index] = false;
  468. defines["SHADOWESM" + index] = false;
  469. defines["SHADOWCUBE" + index] = false;
  470. defines["SHADOWLOWQUALITY" + index] = false;
  471. defines["SHADOWMEDIUMQUALITY" + index] = false;
  472. }
  473. }
  474. let caps = scene.getEngine().getCaps();
  475. if (defines["SHADOWFLOAT"] === undefined) {
  476. state.needRebuild = true;
  477. }
  478. defines["SHADOWFLOAT"] = state.shadowEnabled &&
  479. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  480. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  481. defines["LIGHTMAPEXCLUDED"] = state.lightmapMode;
  482. if (state.needRebuild) {
  483. defines.rebuild();
  484. }
  485. return state.needNormals;
  486. }
  487. /**
  488. * Prepares the uniforms and samplers list to be used in the effect (for a specific light)
  489. * @param lightIndex defines the light index
  490. * @param uniformsList The uniform list
  491. * @param samplersList The sampler list
  492. * @param projectedLightTexture defines if projected texture must be used
  493. * @param uniformBuffersList defines an optional list of uniform buffers
  494. */
  495. public static PrepareUniformsAndSamplersForLight(lightIndex: number, uniformsList: string[], samplersList: string[], projectedLightTexture?: any, uniformBuffersList: Nullable<string[]> = null) {
  496. uniformsList.push(
  497. "vLightData" + lightIndex,
  498. "vLightDiffuse" + lightIndex,
  499. "vLightSpecular" + lightIndex,
  500. "vLightDirection" + lightIndex,
  501. "vLightFalloff" + lightIndex,
  502. "vLightGround" + lightIndex,
  503. "lightMatrix" + lightIndex,
  504. "shadowsInfo" + lightIndex,
  505. "depthValues" + lightIndex,
  506. );
  507. if (uniformBuffersList) {
  508. uniformBuffersList.push("Light" + lightIndex);
  509. }
  510. samplersList.push("shadowSampler" + lightIndex);
  511. samplersList.push("depthSampler" + lightIndex);
  512. uniformsList.push(
  513. "viewFrustumZ" + lightIndex,
  514. "cascadeBlendFactor" + lightIndex,
  515. "lightSizeUVCorrection" + lightIndex,
  516. "depthCorrection" + lightIndex,
  517. "penumbraDarkness" + lightIndex,
  518. "frustumLengths" + lightIndex,
  519. );
  520. if (projectedLightTexture) {
  521. samplersList.push("projectionLightSampler" + lightIndex);
  522. uniformsList.push(
  523. "textureProjectionMatrix" + lightIndex,
  524. );
  525. }
  526. }
  527. /**
  528. * Prepares the uniforms and samplers list to be used in the effect
  529. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  530. * @param samplersList The sampler list
  531. * @param defines The defines helping in the list generation
  532. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  533. */
  534. public static PrepareUniformsAndSamplersList(uniformsListOrOptions: string[] | IEffectCreationOptions, samplersList?: string[], defines?: any, maxSimultaneousLights = 4): void {
  535. let uniformsList: string[];
  536. let uniformBuffersList: Nullable<string[]> = null;
  537. if ((<IEffectCreationOptions>uniformsListOrOptions).uniformsNames) {
  538. var options = <IEffectCreationOptions>uniformsListOrOptions;
  539. uniformsList = options.uniformsNames;
  540. uniformBuffersList = options.uniformBuffersNames;
  541. samplersList = options.samplers;
  542. defines = options.defines;
  543. maxSimultaneousLights = options.maxSimultaneousLights || 0;
  544. } else {
  545. uniformsList = <string[]>uniformsListOrOptions;
  546. if (!samplersList) {
  547. samplersList = [];
  548. }
  549. }
  550. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  551. if (!defines["LIGHT" + lightIndex]) {
  552. break;
  553. }
  554. this.PrepareUniformsAndSamplersForLight(lightIndex, uniformsList, samplersList, defines["PROJECTEDLIGHTTEXTURE" + lightIndex], uniformBuffersList);
  555. }
  556. if (defines["NUM_MORPH_INFLUENCERS"]) {
  557. uniformsList.push("morphTargetInfluences");
  558. }
  559. }
  560. /**
  561. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  562. * @param defines The defines to update while falling back
  563. * @param fallbacks The authorized effect fallbacks
  564. * @param maxSimultaneousLights The maximum number of lights allowed
  565. * @param rank the current rank of the Effect
  566. * @returns The newly affected rank
  567. */
  568. public static HandleFallbacksForShadows(defines: any, fallbacks: EffectFallbacks, maxSimultaneousLights = 4, rank = 0): number {
  569. let lightFallbackRank = 0;
  570. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  571. if (!defines["LIGHT" + lightIndex]) {
  572. break;
  573. }
  574. if (lightIndex > 0) {
  575. lightFallbackRank = rank + lightIndex;
  576. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  577. }
  578. if (!defines["SHADOWS"]) {
  579. if (defines["SHADOW" + lightIndex]) {
  580. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  581. }
  582. if (defines["SHADOWPCF" + lightIndex]) {
  583. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  584. }
  585. if (defines["SHADOWPCSS" + lightIndex]) {
  586. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  587. }
  588. if (defines["SHADOWPOISSON" + lightIndex]) {
  589. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  590. }
  591. if (defines["SHADOWESM" + lightIndex]) {
  592. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  593. }
  594. }
  595. }
  596. return lightFallbackRank++;
  597. }
  598. private static _TmpMorphInfluencers = { "NUM_MORPH_INFLUENCERS": 0 };
  599. /**
  600. * Prepares the list of attributes required for morph targets according to the effect defines.
  601. * @param attribs The current list of supported attribs
  602. * @param mesh The mesh to prepare the morph targets attributes for
  603. * @param influencers The number of influencers
  604. */
  605. public static PrepareAttributesForMorphTargetsInfluencers(attribs: string[], mesh: AbstractMesh, influencers: number): void {
  606. this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS = influencers;
  607. this.PrepareAttributesForMorphTargets(attribs, mesh, this._TmpMorphInfluencers);
  608. }
  609. /**
  610. * Prepares the list of attributes required for morph targets according to the effect defines.
  611. * @param attribs The current list of supported attribs
  612. * @param mesh The mesh to prepare the morph targets attributes for
  613. * @param defines The current Defines of the effect
  614. */
  615. public static PrepareAttributesForMorphTargets(attribs: string[], mesh: AbstractMesh, defines: any): void {
  616. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  617. if (influencers > 0 && EngineStore.LastCreatedEngine) {
  618. var maxAttributesCount = EngineStore.LastCreatedEngine.getCaps().maxVertexAttribs;
  619. var manager = (<Mesh>mesh).morphTargetManager;
  620. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  621. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  622. var uv = manager && manager.supportsUVs && defines["UV1"];
  623. for (var index = 0; index < influencers; index++) {
  624. attribs.push(VertexBuffer.PositionKind + index);
  625. if (normal) {
  626. attribs.push(VertexBuffer.NormalKind + index);
  627. }
  628. if (tangent) {
  629. attribs.push(VertexBuffer.TangentKind + index);
  630. }
  631. if (uv) {
  632. attribs.push(VertexBuffer.UVKind + "_" + index);
  633. }
  634. if (attribs.length > maxAttributesCount) {
  635. Logger.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  636. }
  637. }
  638. }
  639. }
  640. /**
  641. * Prepares the list of attributes required for bones according to the effect defines.
  642. * @param attribs The current list of supported attribs
  643. * @param mesh The mesh to prepare the bones attributes for
  644. * @param defines The current Defines of the effect
  645. * @param fallbacks The current efffect fallback strategy
  646. */
  647. public static PrepareAttributesForBones(attribs: string[], mesh: AbstractMesh, defines: any, fallbacks: EffectFallbacks): void {
  648. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  649. fallbacks.addCPUSkinningFallback(0, mesh);
  650. attribs.push(VertexBuffer.MatricesIndicesKind);
  651. attribs.push(VertexBuffer.MatricesWeightsKind);
  652. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  653. attribs.push(VertexBuffer.MatricesIndicesExtraKind);
  654. attribs.push(VertexBuffer.MatricesWeightsExtraKind);
  655. }
  656. }
  657. }
  658. /**
  659. * Check and prepare the list of attributes required for instances according to the effect defines.
  660. * @param attribs The current list of supported attribs
  661. * @param defines The current MaterialDefines of the effect
  662. */
  663. public static PrepareAttributesForInstances(attribs: string[], defines: MaterialDefines): void {
  664. if (defines["INSTANCES"] || defines["THIN_INSTANCES"]) {
  665. this.PushAttributesForInstances(attribs);
  666. }
  667. }
  668. /**
  669. * Add the list of attributes required for instances to the attribs array.
  670. * @param attribs The current list of supported attribs
  671. */
  672. public static PushAttributesForInstances(attribs: string[]): void {
  673. attribs.push("world0");
  674. attribs.push("world1");
  675. attribs.push("world2");
  676. attribs.push("world3");
  677. }
  678. /**
  679. * Binds the light information to the effect.
  680. * @param light The light containing the generator
  681. * @param effect The effect we are binding the data to
  682. * @param lightIndex The light index in the effect used to render
  683. */
  684. public static BindLightProperties(light: Light, effect: Effect, lightIndex: number): void {
  685. light.transferToEffect(effect, lightIndex + "");
  686. }
  687. /**
  688. * Binds the lights information from the scene to the effect for the given mesh.
  689. * @param light Light to bind
  690. * @param lightIndex Light index
  691. * @param scene The scene where the light belongs to
  692. * @param effect The effect we are binding the data to
  693. * @param useSpecular Defines if specular is supported
  694. * @param rebuildInParallel Specifies whether the shader is rebuilding in parallel
  695. */
  696. public static BindLight(light: Light, lightIndex: number, scene: Scene, effect: Effect, useSpecular: boolean, rebuildInParallel = false): void {
  697. light._bindLight(lightIndex, scene, effect, useSpecular, rebuildInParallel);
  698. }
  699. /**
  700. * Binds the lights 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 defines The generated defines for the effect
  705. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  706. * @param rebuildInParallel Specifies whether the shader is rebuilding in parallel
  707. */
  708. public static BindLights(scene: Scene, mesh: AbstractMesh, effect: Effect, defines: any, maxSimultaneousLights = 4, rebuildInParallel = false): void {
  709. let len = Math.min(mesh.lightSources.length, maxSimultaneousLights);
  710. for (var i = 0; i < len; i++) {
  711. let light = mesh.lightSources[i];
  712. this.BindLight(light, i, scene, effect, typeof defines === "boolean" ? defines : defines["SPECULARTERM"], rebuildInParallel);
  713. }
  714. }
  715. private static _tempFogColor = Color3.Black();
  716. /**
  717. * Binds the fog information from the scene to the effect for the given mesh.
  718. * @param scene The scene the lights belongs to
  719. * @param mesh The mesh we are binding the information to render
  720. * @param effect The effect we are binding the data to
  721. * @param linearSpace Defines if the fog effect is applied in linear space
  722. */
  723. public static BindFogParameters(scene: Scene, mesh: AbstractMesh, effect: Effect, linearSpace = false): void {
  724. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) {
  725. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  726. // Convert fog color to linear space if used in a linear space computed shader.
  727. if (linearSpace) {
  728. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  729. effect.setColor3("vFogColor", this._tempFogColor);
  730. }
  731. else {
  732. effect.setColor3("vFogColor", scene.fogColor);
  733. }
  734. }
  735. }
  736. /**
  737. * Binds the bones information from the mesh to the effect.
  738. * @param mesh The mesh we are binding the information to render
  739. * @param effect The effect we are binding the data to
  740. * @param prePassConfiguration Configuration for the prepass, in case prepass is activated
  741. */
  742. public static BindBonesParameters(mesh?: AbstractMesh, effect?: Effect, prePassConfiguration?: PrePassConfiguration): void {
  743. if (!effect || !mesh) {
  744. return;
  745. }
  746. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  747. mesh.computeBonesUsingShaders = false;
  748. }
  749. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  750. const skeleton = mesh.skeleton;
  751. if (skeleton.isUsingTextureForMatrices && effect.getUniformIndex("boneTextureWidth") > -1) {
  752. const boneTexture = skeleton.getTransformMatrixTexture(mesh);
  753. effect.setTexture("boneSampler", boneTexture);
  754. effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
  755. } else {
  756. const matrices = skeleton.getTransformMatrices(mesh);
  757. if (matrices) {
  758. effect.setMatrices("mBones", matrices);
  759. if (prePassConfiguration && mesh.getScene().prePassRenderer && mesh.getScene().prePassRenderer!.getIndex(Constants.PREPASS_VELOCITY_TEXTURE_TYPE)) {
  760. if (prePassConfiguration.previousBones[mesh.uniqueId]) {
  761. effect.setMatrices("mPreviousBones", prePassConfiguration.previousBones[mesh.uniqueId]);
  762. }
  763. MaterialHelper._CopyBonesTransformationMatrices(matrices, prePassConfiguration.previousBones[mesh.uniqueId]);
  764. }
  765. }
  766. }
  767. }
  768. }
  769. // Copies the bones transformation matrices into the target array and returns the target's reference
  770. private static _CopyBonesTransformationMatrices(source: Float32Array, target: Float32Array): Float32Array {
  771. target.set(source)
  772. return target;
  773. }
  774. /**
  775. * Binds the morph targets information from the mesh to the effect.
  776. * @param abstractMesh The mesh we are binding the information to render
  777. * @param effect The effect we are binding the data to
  778. */
  779. public static BindMorphTargetParameters(abstractMesh: AbstractMesh, effect: Effect): void {
  780. let manager = (<Mesh>abstractMesh).morphTargetManager;
  781. if (!abstractMesh || !manager) {
  782. return;
  783. }
  784. effect.setFloatArray("morphTargetInfluences", manager.influences);
  785. }
  786. /**
  787. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  788. * @param defines The generated defines used in the effect
  789. * @param effect The effect we are binding the data to
  790. * @param scene The scene we are willing to render with logarithmic scale for
  791. */
  792. public static BindLogDepth(defines: any, effect: Effect, scene: Scene): void {
  793. if (defines["LOGARITHMICDEPTH"]) {
  794. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log((<Camera>scene.activeCamera).maxZ + 1.0) / Math.LN2));
  795. }
  796. }
  797. /**
  798. * Binds the clip plane information from the scene to the effect.
  799. * @param scene The scene the clip plane information are extracted from
  800. * @param effect The effect we are binding the data to
  801. */
  802. public static BindClipPlane(effect: Effect, scene: Scene): void {
  803. ThinMaterialHelper.BindClipPlane(effect, scene);
  804. }
  805. }