materialHelper.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  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 multiview
  205. * @param scene The scene we are intending to draw
  206. * @param defines The defines to update
  207. */
  208. public static PrepareDefinesForMultiview(scene: Scene, defines: any) {
  209. if (scene.activeCamera) {
  210. var previousMultiview = defines.MULTIVIEW;
  211. defines.MULTIVIEW = (scene.activeCamera.outputRenderTarget !== null && scene.activeCamera.outputRenderTarget.getViewCount() > 1);
  212. if (defines.MULTIVIEW != previousMultiview) {
  213. defines.markAsUnprocessed();
  214. }
  215. }
  216. }
  217. /**
  218. * Prepares the defines related to the light information passed in parameter
  219. * @param scene The scene we are intending to draw
  220. * @param mesh The mesh the effect is compiling for
  221. * @param defines The defines to update
  222. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  223. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  224. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  225. * @returns true if normals will be required for the rest of the effect
  226. */
  227. public static PrepareDefinesForLights(scene: Scene, mesh: AbstractMesh, defines: any, specularSupported: boolean, maxSimultaneousLights = 4, disableLighting = false): boolean {
  228. if (!defines._areLightsDirty) {
  229. return defines._needNormals;
  230. }
  231. var lightIndex = 0;
  232. var needNormals = false;
  233. var needRebuild = false;
  234. var lightmapMode = false;
  235. var shadowEnabled = false;
  236. var specularEnabled = false;
  237. if (scene.lightsEnabled && !disableLighting) {
  238. for (var light of mesh._lightSources) {
  239. needNormals = true;
  240. if (defines["LIGHT" + lightIndex] === undefined) {
  241. needRebuild = true;
  242. }
  243. defines["LIGHT" + lightIndex] = true;
  244. defines["SPOTLIGHT" + lightIndex] = false;
  245. defines["HEMILIGHT" + lightIndex] = false;
  246. defines["POINTLIGHT" + lightIndex] = false;
  247. defines["DIRLIGHT" + lightIndex] = false;
  248. light.prepareLightSpecificDefines(defines, lightIndex);
  249. // FallOff.
  250. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  251. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  252. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  253. switch (light.falloffType) {
  254. case Light.FALLOFF_GLTF:
  255. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  256. break;
  257. case Light.FALLOFF_PHYSICAL:
  258. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  259. break;
  260. case Light.FALLOFF_STANDARD:
  261. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  262. break;
  263. }
  264. // Specular
  265. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  266. specularEnabled = true;
  267. }
  268. // Shadows
  269. defines["SHADOW" + lightIndex] = false;
  270. defines["SHADOWPCF" + lightIndex] = false;
  271. defines["SHADOWPCSS" + lightIndex] = false;
  272. defines["SHADOWPOISSON" + lightIndex] = false;
  273. defines["SHADOWESM" + lightIndex] = false;
  274. defines["SHADOWCUBE" + lightIndex] = false;
  275. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  276. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  277. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  278. var shadowGenerator = light.getShadowGenerator();
  279. if (shadowGenerator) {
  280. const shadowMap = shadowGenerator.getShadowMap();
  281. if (shadowMap) {
  282. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  283. shadowEnabled = true;
  284. shadowGenerator.prepareDefines(defines, lightIndex);
  285. }
  286. }
  287. }
  288. }
  289. if (light.lightmapMode != Light.LIGHTMAP_DEFAULT) {
  290. lightmapMode = true;
  291. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  292. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == Light.LIGHTMAP_SHADOWSONLY);
  293. } else {
  294. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  295. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  296. }
  297. lightIndex++;
  298. if (lightIndex === maxSimultaneousLights) {
  299. break;
  300. }
  301. }
  302. }
  303. defines["SPECULARTERM"] = specularEnabled;
  304. defines["SHADOWS"] = shadowEnabled;
  305. // Resetting all other lights if any
  306. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  307. if (defines["LIGHT" + index] !== undefined) {
  308. defines["LIGHT" + index] = false;
  309. defines["HEMILIGHT" + index] = false;
  310. defines["POINTLIGHT" + index] = false;
  311. defines["DIRLIGHT" + index] = false;
  312. defines["SPOTLIGHT" + index] = false;
  313. defines["SHADOW" + index] = false;
  314. defines["SHADOWPCF" + index] = false;
  315. defines["SHADOWPCSS" + index] = false;
  316. defines["SHADOWPOISSON" + index] = false;
  317. defines["SHADOWESM" + index] = false;
  318. defines["SHADOWCUBE" + index] = false;
  319. defines["SHADOWLOWQUALITY" + index] = false;
  320. defines["SHADOWMEDIUMQUALITY" + index] = false;
  321. }
  322. }
  323. let caps = scene.getEngine().getCaps();
  324. if (defines["SHADOWFLOAT"] === undefined) {
  325. needRebuild = true;
  326. }
  327. defines["SHADOWFLOAT"] = shadowEnabled &&
  328. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  329. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  330. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  331. if (needRebuild) {
  332. defines.rebuild();
  333. }
  334. return needNormals;
  335. }
  336. /**
  337. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  338. * that won t be acctive due to defines being turned off.
  339. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  340. * @param samplersList The samplers list
  341. * @param defines The defines helping in the list generation
  342. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  343. */
  344. public static PrepareUniformsAndSamplersList(uniformsListOrOptions: string[] | EffectCreationOptions, samplersList?: string[], defines?: any, maxSimultaneousLights = 4): void {
  345. let uniformsList: string[];
  346. let uniformBuffersList: Nullable<string[]> = null;
  347. if ((<EffectCreationOptions>uniformsListOrOptions).uniformsNames) {
  348. var options = <EffectCreationOptions>uniformsListOrOptions;
  349. uniformsList = options.uniformsNames;
  350. uniformBuffersList = options.uniformBuffersNames;
  351. samplersList = options.samplers;
  352. defines = options.defines;
  353. maxSimultaneousLights = options.maxSimultaneousLights;
  354. } else {
  355. uniformsList = <string[]>uniformsListOrOptions;
  356. if (!samplersList) {
  357. samplersList = [];
  358. }
  359. }
  360. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  361. if (!defines["LIGHT" + lightIndex]) {
  362. break;
  363. }
  364. uniformsList.push(
  365. "vLightData" + lightIndex,
  366. "vLightDiffuse" + lightIndex,
  367. "vLightSpecular" + lightIndex,
  368. "vLightDirection" + lightIndex,
  369. "vLightFalloff" + lightIndex,
  370. "vLightGround" + lightIndex,
  371. "lightMatrix" + lightIndex,
  372. "shadowsInfo" + lightIndex,
  373. "depthValues" + lightIndex,
  374. );
  375. if (uniformBuffersList) {
  376. uniformBuffersList.push("Light" + lightIndex);
  377. }
  378. samplersList.push("shadowSampler" + lightIndex);
  379. samplersList.push("depthSampler" + lightIndex);
  380. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  381. samplersList.push("projectionLightSampler" + lightIndex);
  382. uniformsList.push(
  383. "textureProjectionMatrix" + lightIndex,
  384. );
  385. }
  386. }
  387. if (defines["NUM_MORPH_INFLUENCERS"]) {
  388. uniformsList.push("morphTargetInfluences");
  389. }
  390. }
  391. /**
  392. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  393. * @param defines The defines to update while falling back
  394. * @param fallbacks The authorized effect fallbacks
  395. * @param maxSimultaneousLights The maximum number of lights allowed
  396. * @param rank the current rank of the Effect
  397. * @returns The newly affected rank
  398. */
  399. public static HandleFallbacksForShadows(defines: any, fallbacks: EffectFallbacks, maxSimultaneousLights = 4, rank = 0): number {
  400. let lightFallbackRank = 0;
  401. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  402. if (!defines["LIGHT" + lightIndex]) {
  403. break;
  404. }
  405. if (lightIndex > 0) {
  406. lightFallbackRank = rank + lightIndex;
  407. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  408. }
  409. if (!defines["SHADOWS"]) {
  410. if (defines["SHADOW" + lightIndex]) {
  411. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  412. }
  413. if (defines["SHADOWPCF" + lightIndex]) {
  414. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  415. }
  416. if (defines["SHADOWPCSS" + lightIndex]) {
  417. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  418. }
  419. if (defines["SHADOWPOISSON" + lightIndex]) {
  420. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  421. }
  422. if (defines["SHADOWESM" + lightIndex]) {
  423. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  424. }
  425. }
  426. }
  427. return lightFallbackRank++;
  428. }
  429. /**
  430. * Prepares the list of attributes required for morph targets according to the effect defines.
  431. * @param attribs The current list of supported attribs
  432. * @param mesh The mesh to prepare the morph targets attributes for
  433. * @param defines The current Defines of the effect
  434. */
  435. public static PrepareAttributesForMorphTargets(attribs: string[], mesh: AbstractMesh, defines: any): void {
  436. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  437. if (influencers > 0 && EngineStore.LastCreatedEngine) {
  438. var maxAttributesCount = EngineStore.LastCreatedEngine.getCaps().maxVertexAttribs;
  439. var manager = (<Mesh>mesh).morphTargetManager;
  440. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  441. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  442. for (var index = 0; index < influencers; index++) {
  443. attribs.push(VertexBuffer.PositionKind + index);
  444. if (normal) {
  445. attribs.push(VertexBuffer.NormalKind + index);
  446. }
  447. if (tangent) {
  448. attribs.push(VertexBuffer.TangentKind + index);
  449. }
  450. if (attribs.length > maxAttributesCount) {
  451. Logger.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  452. }
  453. }
  454. }
  455. }
  456. /**
  457. * Prepares the list of attributes required for bones according to the effect defines.
  458. * @param attribs The current list of supported attribs
  459. * @param mesh The mesh to prepare the bones attributes for
  460. * @param defines The current Defines of the effect
  461. * @param fallbacks The current efffect fallback strategy
  462. */
  463. public static PrepareAttributesForBones(attribs: string[], mesh: AbstractMesh, defines: any, fallbacks: EffectFallbacks): void {
  464. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  465. fallbacks.addCPUSkinningFallback(0, mesh);
  466. attribs.push(VertexBuffer.MatricesIndicesKind);
  467. attribs.push(VertexBuffer.MatricesWeightsKind);
  468. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  469. attribs.push(VertexBuffer.MatricesIndicesExtraKind);
  470. attribs.push(VertexBuffer.MatricesWeightsExtraKind);
  471. }
  472. }
  473. }
  474. /**
  475. * Prepares the list of attributes required for instances according to the effect defines.
  476. * @param attribs The current list of supported attribs
  477. * @param defines The current Defines of the effect
  478. */
  479. public static PrepareAttributesForInstances(attribs: string[], defines: any): void {
  480. if (defines["INSTANCES"]) {
  481. attribs.push("world0");
  482. attribs.push("world1");
  483. attribs.push("world2");
  484. attribs.push("world3");
  485. }
  486. }
  487. /**
  488. * Binds the light shadow information to the effect for the given mesh.
  489. * @param light The light containing the generator
  490. * @param scene The scene the lights belongs to
  491. * @param mesh The mesh we are binding the information to render
  492. * @param lightIndex The light index in the effect used to render the mesh
  493. * @param effect The effect we are binding the data to
  494. */
  495. public static BindLightShadow(light: Light, mesh: AbstractMesh, lightIndex: string, effect: Effect): void {
  496. if (light.shadowEnabled && mesh.receiveShadows) {
  497. var shadowGenerator = light.getShadowGenerator();
  498. if (shadowGenerator) {
  499. shadowGenerator.bindShadowLight(lightIndex, effect);
  500. }
  501. }
  502. }
  503. /**
  504. * Binds the light information to the effect.
  505. * @param light The light containing the generator
  506. * @param effect The effect we are binding the data to
  507. * @param lightIndex The light index in the effect used to render
  508. */
  509. public static BindLightProperties(light: Light, effect: Effect, lightIndex: number): void {
  510. light.transferToEffect(effect, lightIndex + "");
  511. }
  512. /**
  513. * Binds the lights information from the scene to the effect for the given mesh.
  514. * @param scene The scene the lights belongs to
  515. * @param mesh The mesh we are binding the information to render
  516. * @param effect The effect we are binding the data to
  517. * @param defines The generated defines for the effect
  518. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  519. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  520. */
  521. public static BindLights(scene: Scene, mesh: AbstractMesh, effect: Effect, defines: any, maxSimultaneousLights = 4, usePhysicalLightFalloff = false): void {
  522. let len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  523. for (var i = 0; i < len; i++) {
  524. let light = mesh._lightSources[i];
  525. let iAsString = i.toString();
  526. let scaledIntensity = light.getScaledIntensity();
  527. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  528. MaterialHelper.BindLightProperties(light, effect, i);
  529. light.diffuse.scaleToRef(scaledIntensity, Tmp.Color3[0]);
  530. light._uniformBuffer.updateColor4("vLightDiffuse", Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  531. if (defines["SPECULARTERM"]) {
  532. light.specular.scaleToRef(scaledIntensity, Tmp.Color3[1]);
  533. light._uniformBuffer.updateColor3("vLightSpecular", Tmp.Color3[1], iAsString);
  534. }
  535. // Shadows
  536. if (scene.shadowsEnabled) {
  537. this.BindLightShadow(light, mesh, iAsString, effect);
  538. }
  539. light._uniformBuffer.update();
  540. }
  541. }
  542. private static _tempFogColor = Color3.Black();
  543. /**
  544. * Binds the fog information from the scene to the effect for the given mesh.
  545. * @param scene The scene the lights belongs to
  546. * @param mesh The mesh we are binding the information to render
  547. * @param effect The effect we are binding the data to
  548. * @param linearSpace Defines if the fog effect is applied in linear space
  549. */
  550. public static BindFogParameters(scene: Scene, mesh: AbstractMesh, effect: Effect, linearSpace = false): void {
  551. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) {
  552. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  553. // Convert fog color to linear space if used in a linear space computed shader.
  554. if (linearSpace) {
  555. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  556. effect.setColor3("vFogColor", this._tempFogColor);
  557. }
  558. else {
  559. effect.setColor3("vFogColor", scene.fogColor);
  560. }
  561. }
  562. }
  563. /**
  564. * Binds the bones information from the mesh to the effect.
  565. * @param mesh The mesh we are binding the information to render
  566. * @param effect The effect we are binding the data to
  567. */
  568. public static BindBonesParameters(mesh?: AbstractMesh, effect?: Effect): void {
  569. if (!effect || !mesh) {
  570. return;
  571. }
  572. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  573. mesh.computeBonesUsingShaders = false;
  574. }
  575. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  576. const skeleton = mesh.skeleton;
  577. if (skeleton.isUsingTextureForMatrices && effect.getUniformIndex("boneTextureWidth") > -1) {
  578. const boneTexture = skeleton.getTransformMatrixTexture();
  579. effect.setTexture("boneSampler", boneTexture);
  580. effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
  581. } else {
  582. const matrices = skeleton.getTransformMatrices(mesh);
  583. if (matrices) {
  584. effect.setMatrices("mBones", matrices);
  585. }
  586. }
  587. }
  588. }
  589. /**
  590. * Binds the morph targets information from the mesh to the effect.
  591. * @param abstractMesh The mesh we are binding the information to render
  592. * @param effect The effect we are binding the data to
  593. */
  594. public static BindMorphTargetParameters(abstractMesh: AbstractMesh, effect: Effect): void {
  595. let manager = (<Mesh>abstractMesh).morphTargetManager;
  596. if (!abstractMesh || !manager) {
  597. return;
  598. }
  599. effect.setFloatArray("morphTargetInfluences", manager.influences);
  600. }
  601. /**
  602. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  603. * @param defines The generated defines used in the effect
  604. * @param effect The effect we are binding the data to
  605. * @param scene The scene we are willing to render with logarithmic scale for
  606. */
  607. public static BindLogDepth(defines: any, effect: Effect, scene: Scene): void {
  608. if (defines["LOGARITHMICDEPTH"]) {
  609. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log((<Camera>scene.activeCamera).maxZ + 1.0) / Math.LN2));
  610. }
  611. }
  612. /**
  613. * Binds the clip plane information from the scene to the effect.
  614. * @param scene The scene the clip plane information are extracted from
  615. * @param effect The effect we are binding the data to
  616. */
  617. public static BindClipPlane(effect: Effect, scene: Scene): void {
  618. if (scene.clipPlane) {
  619. let clipPlane = scene.clipPlane;
  620. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  621. }
  622. if (scene.clipPlane2) {
  623. let clipPlane = scene.clipPlane2;
  624. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  625. }
  626. if (scene.clipPlane3) {
  627. let clipPlane = scene.clipPlane3;
  628. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  629. }
  630. if (scene.clipPlane4) {
  631. let clipPlane = scene.clipPlane4;
  632. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  633. }
  634. }
  635. }