babylon.simpleMaterial.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. module BABYLON {
  3. var maxSimultaneousLights = 4;
  4. class SimpleMaterialDefines extends MaterialDefines {
  5. public DIFFUSE = false;
  6. public CLIPPLANE = false;
  7. public ALPHATEST = false;
  8. public POINTSIZE = false;
  9. public FOG = false;
  10. public LIGHT0 = false;
  11. public LIGHT1 = false;
  12. public LIGHT2 = false;
  13. public LIGHT3 = false;
  14. public SPOTLIGHT0 = false;
  15. public SPOTLIGHT1 = false;
  16. public SPOTLIGHT2 = false;
  17. public SPOTLIGHT3 = false;
  18. public HEMILIGHT0 = false;
  19. public HEMILIGHT1 = false;
  20. public HEMILIGHT2 = false;
  21. public HEMILIGHT3 = false;
  22. public DIRLIGHT0 = false;
  23. public DIRLIGHT1 = false;
  24. public DIRLIGHT2 = false;
  25. public DIRLIGHT3 = false;
  26. public POINTLIGHT0 = false;
  27. public POINTLIGHT1 = false;
  28. public POINTLIGHT2 = false;
  29. public POINTLIGHT3 = false;
  30. public SHADOW0 = false;
  31. public SHADOW1 = false;
  32. public SHADOW2 = false;
  33. public SHADOW3 = false;
  34. public SHADOWS = false;
  35. public SHADOWVSM0 = false;
  36. public SHADOWVSM1 = false;
  37. public SHADOWVSM2 = false;
  38. public SHADOWVSM3 = false;
  39. public SHADOWPCF0 = false;
  40. public SHADOWPCF1 = false;
  41. public SHADOWPCF2 = false;
  42. public SHADOWPCF3 = false;
  43. public NORMAL = false;
  44. public UV1 = false;
  45. public UV2 = false;
  46. public VERTEXCOLOR = false;
  47. public VERTEXALPHA = false;
  48. public NUM_BONE_INFLUENCERS = 0;
  49. public BonesPerMesh = 0;
  50. public INSTANCES = false;
  51. constructor() {
  52. super();
  53. this._keys = Object.keys(this);
  54. }
  55. }
  56. export class SimpleMaterial extends Material {
  57. public diffuseTexture: BaseTexture;
  58. public diffuseColor = new Color3(1, 1, 1);
  59. public disableLighting = false;
  60. private _worldViewProjectionMatrix = Matrix.Zero();
  61. private _scaledDiffuse = new Color3();
  62. private _renderId: number;
  63. private _defines = new SimpleMaterialDefines();
  64. private _cachedDefines = new SimpleMaterialDefines();
  65. constructor(name: string, scene: Scene) {
  66. super(name, scene);
  67. this._cachedDefines.BonesPerMesh = -1;
  68. }
  69. public needAlphaBlending(): boolean {
  70. return (this.alpha < 1.0);
  71. }
  72. public needAlphaTesting(): boolean {
  73. return false;
  74. }
  75. public getAlphaTestTexture(): BaseTexture {
  76. return null;
  77. }
  78. // Methods
  79. private _checkCache(scene: Scene, mesh?: AbstractMesh, useInstances?: boolean): boolean {
  80. if (!mesh) {
  81. return true;
  82. }
  83. if (this._defines.INSTANCES !== useInstances) {
  84. return false;
  85. }
  86. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  87. return true;
  88. }
  89. return false;
  90. }
  91. public isReady(mesh?: AbstractMesh, useInstances?: boolean): boolean {
  92. if (this.checkReadyOnlyOnce) {
  93. if (this._wasPreviouslyReady) {
  94. return true;
  95. }
  96. }
  97. var scene = this.getScene();
  98. if (!this.checkReadyOnEveryCall) {
  99. if (this._renderId === scene.getRenderId()) {
  100. if (this._checkCache(scene, mesh, useInstances)) {
  101. return true;
  102. }
  103. }
  104. }
  105. var engine = scene.getEngine();
  106. var needNormals = false;
  107. var needUVs = false;
  108. this._defines.reset();
  109. // Textures
  110. if (scene.texturesEnabled) {
  111. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  112. if (!this.diffuseTexture.isReady()) {
  113. return false;
  114. } else {
  115. needUVs = true;
  116. this._defines.DIFFUSE = true;
  117. }
  118. }
  119. }
  120. // Effect
  121. if (scene.clipPlane) {
  122. this._defines.CLIPPLANE = true;
  123. }
  124. if (engine.getAlphaTesting()) {
  125. this._defines.ALPHATEST = true;
  126. }
  127. // Point size
  128. if (this.pointsCloud || scene.forcePointsCloud) {
  129. this._defines.POINTSIZE = true;
  130. }
  131. // Fog
  132. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE && this.fogEnabled) {
  133. this._defines.FOG = true;
  134. }
  135. var lightIndex = 0;
  136. if (scene.lightsEnabled && !this.disableLighting) {
  137. for (var index = 0; index < scene.lights.length; index++) {
  138. var light = scene.lights[index];
  139. if (!light.isEnabled()) {
  140. continue;
  141. }
  142. // Excluded check
  143. if (light._excludedMeshesIds.length > 0) {
  144. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  145. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  146. if (excludedMesh) {
  147. light.excludedMeshes.push(excludedMesh);
  148. }
  149. }
  150. light._excludedMeshesIds = [];
  151. }
  152. // Included check
  153. if (light._includedOnlyMeshesIds.length > 0) {
  154. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  155. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  156. if (includedOnlyMesh) {
  157. light.includedOnlyMeshes.push(includedOnlyMesh);
  158. }
  159. }
  160. light._includedOnlyMeshesIds = [];
  161. }
  162. if (!light.canAffectMesh(mesh)) {
  163. continue;
  164. }
  165. needNormals = true;
  166. this._defines["LIGHT" + lightIndex] = true;
  167. var type;
  168. if (light instanceof SpotLight) {
  169. type = "SPOTLIGHT" + lightIndex;
  170. } else if (light instanceof HemisphericLight) {
  171. type = "HEMILIGHT" + lightIndex;
  172. } else if (light instanceof PointLight) {
  173. type = "POINTLIGHT" + lightIndex;
  174. } else {
  175. type = "DIRLIGHT" + lightIndex;
  176. }
  177. this._defines[type] = true;
  178. // Shadows
  179. if (scene.shadowsEnabled) {
  180. var shadowGenerator = light.getShadowGenerator();
  181. if (mesh && mesh.receiveShadows && shadowGenerator) {
  182. this._defines["SHADOW" + lightIndex] = true;
  183. this._defines.SHADOWS = true;
  184. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  185. this._defines["SHADOWVSM" + lightIndex] = true;
  186. }
  187. if (shadowGenerator.usePoissonSampling) {
  188. this._defines["SHADOWPCF" + lightIndex] = true;
  189. }
  190. }
  191. }
  192. lightIndex++;
  193. if (lightIndex === maxSimultaneousLights)
  194. break;
  195. }
  196. }
  197. // Attribs
  198. if (mesh) {
  199. if (needNormals && mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  200. this._defines.NORMAL = true;
  201. }
  202. if (needUVs) {
  203. if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  204. this._defines.UV1 = true;
  205. }
  206. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
  207. this._defines.UV2 = true;
  208. }
  209. }
  210. if (mesh.useVertexColors && mesh.isVerticesDataPresent(VertexBuffer.ColorKind)) {
  211. this._defines.VERTEXCOLOR = true;
  212. if (mesh.hasVertexAlpha) {
  213. this._defines.VERTEXALPHA = true;
  214. }
  215. }
  216. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  217. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  218. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  219. }
  220. // Instances
  221. if (useInstances) {
  222. this._defines.INSTANCES = true;
  223. }
  224. }
  225. // Get correct effect
  226. if (!this._defines.isEqual(this._cachedDefines)) {
  227. this._defines.cloneTo(this._cachedDefines);
  228. scene.resetCachedMaterial();
  229. // Fallbacks
  230. var fallbacks = new EffectFallbacks();
  231. if (this._defines.FOG) {
  232. fallbacks.addFallback(1, "FOG");
  233. }
  234. for (lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  235. if (!this._defines["LIGHT" + lightIndex]) {
  236. continue;
  237. }
  238. if (lightIndex > 0) {
  239. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  240. }
  241. if (this._defines["SHADOW" + lightIndex]) {
  242. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  243. }
  244. if (this._defines["SHADOWPCF" + lightIndex]) {
  245. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  246. }
  247. if (this._defines["SHADOWVSM" + lightIndex]) {
  248. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  249. }
  250. }
  251. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  252. fallbacks.addCPUSkinningFallback(0, mesh);
  253. }
  254. //Attributes
  255. var attribs = [VertexBuffer.PositionKind];
  256. if (this._defines.NORMAL) {
  257. attribs.push(VertexBuffer.NormalKind);
  258. }
  259. if (this._defines.UV1) {
  260. attribs.push(VertexBuffer.UVKind);
  261. }
  262. if (this._defines.UV2) {
  263. attribs.push(VertexBuffer.UV2Kind);
  264. }
  265. if (this._defines.VERTEXCOLOR) {
  266. attribs.push(VertexBuffer.ColorKind);
  267. }
  268. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  269. attribs.push(VertexBuffer.MatricesIndicesKind);
  270. attribs.push(VertexBuffer.MatricesWeightsKind);
  271. if (this._defines.NUM_BONE_INFLUENCERS > 4) {
  272. attribs.push(VertexBuffer.MatricesIndicesExtraKind);
  273. attribs.push(VertexBuffer.MatricesWeightsExtraKind);
  274. }
  275. }
  276. if (this._defines.INSTANCES) {
  277. attribs.push("world0");
  278. attribs.push("world1");
  279. attribs.push("world2");
  280. attribs.push("world3");
  281. }
  282. // Legacy browser patch
  283. var shaderName = "simple";
  284. var join = this._defines.toString();
  285. this._effect = scene.getEngine().createEffect(shaderName,
  286. attribs,
  287. ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vDiffuseColor",
  288. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  289. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  290. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  291. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  292. "vFogInfos", "vFogColor", "pointSize",
  293. "vDiffuseInfos",
  294. "mBones",
  295. "vClipPlane", "diffuseMatrix",
  296. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues"
  297. ],
  298. ["diffuseSampler",
  299. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  300. ],
  301. join, fallbacks, this.onCompiled, this.onError);
  302. }
  303. if (!this._effect.isReady()) {
  304. return false;
  305. }
  306. this._renderId = scene.getRenderId();
  307. this._wasPreviouslyReady = true;
  308. if (mesh) {
  309. if (!mesh._materialDefines) {
  310. mesh._materialDefines = new SimpleMaterialDefines();
  311. }
  312. this._defines.cloneTo(mesh._materialDefines);
  313. }
  314. return true;
  315. }
  316. public bindOnlyWorldMatrix(world: Matrix): void {
  317. this._effect.setMatrix("world", world);
  318. }
  319. public bind(world: Matrix, mesh?: Mesh): void {
  320. var scene = this.getScene();
  321. // Matrices
  322. this.bindOnlyWorldMatrix(world);
  323. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  324. // Bones
  325. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  326. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  327. }
  328. if (scene.getCachedMaterial() !== this) {
  329. // Textures
  330. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  331. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  332. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  333. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  334. }
  335. // Clip plane
  336. if (scene.clipPlane) {
  337. var clipPlane = scene.clipPlane;
  338. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  339. }
  340. // Point size
  341. if (this.pointsCloud) {
  342. this._effect.setFloat("pointSize", this.pointSize);
  343. }
  344. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  345. }
  346. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  347. if (scene.lightsEnabled && !this.disableLighting) {
  348. var lightIndex = 0;
  349. var depthValuesAlreadySet = false;
  350. for (var index = 0; index < scene.lights.length; index++) {
  351. var light = scene.lights[index];
  352. if (!light.isEnabled()) {
  353. continue;
  354. }
  355. if (!light.canAffectMesh(mesh)) {
  356. continue;
  357. }
  358. if (light instanceof PointLight) {
  359. // Point Light
  360. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  361. } else if (light instanceof DirectionalLight) {
  362. // Directional Light
  363. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  364. } else if (light instanceof SpotLight) {
  365. // Spot Light
  366. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  367. } else if (light instanceof HemisphericLight) {
  368. // Hemispheric Light
  369. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  370. }
  371. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  372. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  373. // Shadows
  374. if (scene.shadowsEnabled) {
  375. var shadowGenerator = light.getShadowGenerator();
  376. if (mesh.receiveShadows && shadowGenerator) {
  377. if (!(<any>light).needCube()) {
  378. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  379. } else {
  380. if (!depthValuesAlreadySet) {
  381. depthValuesAlreadySet = true;
  382. this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  383. }
  384. }
  385. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  386. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  387. }
  388. }
  389. lightIndex++;
  390. if (lightIndex === maxSimultaneousLights)
  391. break;
  392. }
  393. }
  394. // View
  395. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) {
  396. this._effect.setMatrix("view", scene.getViewMatrix());
  397. }
  398. // Fog
  399. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) {
  400. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  401. this._effect.setColor3("vFogColor", scene.fogColor);
  402. }
  403. super.bind(world, mesh);
  404. }
  405. public getAnimatables(): IAnimatable[] {
  406. var results = [];
  407. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  408. results.push(this.diffuseTexture);
  409. }
  410. return results;
  411. }
  412. public dispose(forceDisposeEffect?: boolean): void {
  413. if (this.diffuseTexture) {
  414. this.diffuseTexture.dispose();
  415. }
  416. super.dispose(forceDisposeEffect);
  417. }
  418. public clone(name: string): SimpleMaterial {
  419. var newMaterial = new SimpleMaterial(name, this.getScene());
  420. // Base material
  421. this.copyTo(newMaterial);
  422. // Simple material
  423. if (this.diffuseTexture && this.diffuseTexture.clone) {
  424. newMaterial.diffuseTexture = this.diffuseTexture.clone();
  425. }
  426. newMaterial.diffuseColor = this.diffuseColor.clone();
  427. return newMaterial;
  428. }
  429. public serialize(): any {
  430. var serializationObject = super.serialize();
  431. serializationObject.customType = "BABYLON.SimpleMaterial";
  432. serializationObject.diffuseColor = this.diffuseColor.asArray();
  433. serializationObject.disableLighting = this.disableLighting;
  434. if (this.diffuseTexture) {
  435. serializationObject.diffuseTexture = this.diffuseTexture.serialize();
  436. }
  437. return serializationObject;
  438. }
  439. public static Parse(source: any, scene: Scene, rootUrl: string): SimpleMaterial {
  440. var material = new SimpleMaterial(source.name, scene);
  441. material.diffuseColor = Color3.FromArray(source.diffuseColor);
  442. material.disableLighting = source.disableLighting;
  443. material.alpha = source.alpha;
  444. material.id = source.id;
  445. Tags.AddTagsTo(material, source.tags);
  446. material.backFaceCulling = source.backFaceCulling;
  447. material.wireframe = source.wireframe;
  448. if (source.diffuseTexture) {
  449. material.diffuseTexture = Texture.Parse(source.diffuseTexture, scene, rootUrl);
  450. }
  451. if (source.checkReadyOnlyOnce) {
  452. material.checkReadyOnlyOnce = source.checkReadyOnlyOnce;
  453. }
  454. return material;
  455. }
  456. }
  457. }