materialHelper.ts 31 KB

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