babylon.waterMaterial.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. /// <reference path="../simple/babylon.simpleMaterial.ts"/>
  3. module BABYLON {
  4. class WaterMaterialDefines extends MaterialDefines {
  5. public BUMP = false;
  6. public REFLECTION = false;
  7. public CLIPPLANE = false;
  8. public ALPHATEST = false;
  9. public POINTSIZE = false;
  10. public FOG = false;
  11. public NORMAL = false;
  12. public UV1 = false;
  13. public UV2 = false;
  14. public VERTEXCOLOR = false;
  15. public VERTEXALPHA = false;
  16. public NUM_BONE_INFLUENCERS = 0;
  17. public BonesPerMesh = 0;
  18. public INSTANCES = false;
  19. public SPECULARTERM = false;
  20. public LOGARITHMICDEPTH = false;
  21. public FRESNELSEPARATE = false;
  22. public BUMPSUPERIMPOSE = false;
  23. public BUMPAFFECTSREFLECTION = false;
  24. constructor() {
  25. super();
  26. this.rebuild();
  27. }
  28. }
  29. export class WaterMaterial extends Material {
  30. /*
  31. * Public members
  32. */
  33. @serializeAsTexture()
  34. public bumpTexture: BaseTexture;
  35. @serializeAsColor3()
  36. public diffuseColor = new Color3(1, 1, 1);
  37. @serializeAsColor3()
  38. public specularColor = new Color3(0, 0, 0);
  39. @serialize()
  40. public specularPower = 64;
  41. @serialize()
  42. public disableLighting = false;
  43. @serialize()
  44. public maxSimultaneousLights = 4;
  45. /**
  46. * @param {number}: Represents the wind force
  47. */
  48. @serialize()
  49. public windForce: number = 6;
  50. /**
  51. * @param {Vector2}: The direction of the wind in the plane (X, Z)
  52. */
  53. @serializeAsVector2()
  54. public windDirection: Vector2 = new Vector2(0, 1);
  55. /**
  56. * @param {number}: Wave height, represents the height of the waves
  57. */
  58. @serialize()
  59. public waveHeight: number = 0.4;
  60. /**
  61. * @param {number}: Bump height, represents the bump height related to the bump map
  62. */
  63. @serialize()
  64. public bumpHeight: number = 0.4;
  65. /**
  66. * @param {boolean}: Add a smaller moving bump to less steady waves.
  67. */
  68. @serialize()
  69. public bumpSuperimpose = false;
  70. /**
  71. * @param {boolean}: Color refraction and reflection differently with .waterColor2 and .colorBlendFactor2. Non-linear (physically correct) fresnel.
  72. */
  73. @serialize()
  74. public fresnelSeparate = false;
  75. /**
  76. * @param {boolean}: bump Waves modify the reflection.
  77. */
  78. @serialize()
  79. public bumpAffectsReflection = false;
  80. /**
  81. * @param {number}: The water color blended with the refraction (near)
  82. */
  83. @serializeAsColor3()
  84. public waterColor: Color3 = new Color3(0.1, 0.1, 0.6);
  85. /**
  86. * @param {number}: The blend factor related to the water color
  87. */
  88. @serialize()
  89. public colorBlendFactor: number = 0.2;
  90. /**
  91. * @param {number}: The water color blended with the reflection (far)
  92. */
  93. @serializeAsColor3()
  94. public waterColor2: Color3 = new Color3(0.1, 0.1, 0.6);
  95. /**
  96. * @param {number}: The blend factor related to the water color (reflection, far)
  97. */
  98. @serialize()
  99. public colorBlendFactor2: number = 0.2;
  100. /**
  101. * @param {number}: Represents the maximum length of a wave
  102. */
  103. @serialize()
  104. public waveLength: number = 0.1;
  105. /**
  106. * @param {number}: Defines the waves speed
  107. */
  108. @serialize()
  109. public waveSpeed: number = 1.0;
  110. /*
  111. * Private members
  112. */
  113. private _mesh: AbstractMesh = null;
  114. private _refractionRTT: RenderTargetTexture;
  115. private _reflectionRTT: RenderTargetTexture;
  116. private _material: ShaderMaterial;
  117. private _reflectionTransform: Matrix = Matrix.Zero();
  118. private _lastTime: number = 0;
  119. private _renderId: number;
  120. private _defines = new WaterMaterialDefines();
  121. private _cachedDefines = new WaterMaterialDefines();
  122. private _useLogarithmicDepth: boolean;
  123. /**
  124. * Constructor
  125. */
  126. constructor(name: string, scene: Scene, public renderTargetSize: Vector2 = new Vector2(512, 512)) {
  127. super(name, scene);
  128. // Create render targets
  129. this._createRenderTargets(scene, renderTargetSize);
  130. }
  131. @serialize()
  132. public get useLogarithmicDepth(): boolean {
  133. return this._useLogarithmicDepth;
  134. }
  135. public set useLogarithmicDepth(value: boolean) {
  136. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  137. }
  138. // Get / Set
  139. public get refractionTexture(): RenderTargetTexture {
  140. return this._refractionRTT;
  141. }
  142. public get reflectionTexture(): RenderTargetTexture {
  143. return this._reflectionRTT;
  144. }
  145. // Methods
  146. public addToRenderList(node: any): void {
  147. this._refractionRTT.renderList.push(node);
  148. this._reflectionRTT.renderList.push(node);
  149. }
  150. public enableRenderTargets(enable: boolean): void {
  151. var refreshRate = enable ? 1 : 0;
  152. this._refractionRTT.refreshRate = refreshRate;
  153. this._reflectionRTT.refreshRate = refreshRate;
  154. }
  155. public getRenderList(): AbstractMesh[] {
  156. return this._refractionRTT.renderList;
  157. }
  158. public get renderTargetsEnabled(): boolean {
  159. return !(this._refractionRTT.refreshRate === 0);
  160. }
  161. public needAlphaBlending(): boolean {
  162. return (this.alpha < 1.0);
  163. }
  164. public needAlphaTesting(): boolean {
  165. return false;
  166. }
  167. public getAlphaTestTexture(): BaseTexture {
  168. return null;
  169. }
  170. private _checkCache(scene: Scene, mesh?: AbstractMesh, useInstances?: boolean): boolean {
  171. if (!mesh) {
  172. return true;
  173. }
  174. if (this._defines.INSTANCES !== useInstances) {
  175. return false;
  176. }
  177. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  178. return true;
  179. }
  180. return false;
  181. }
  182. public isReady(mesh?: AbstractMesh, useInstances?: boolean): boolean {
  183. if (this.checkReadyOnlyOnce) {
  184. if (this._wasPreviouslyReady) {
  185. return true;
  186. }
  187. }
  188. var scene = this.getScene();
  189. if (!this.checkReadyOnEveryCall) {
  190. if (this._renderId === scene.getRenderId()) {
  191. if (this._checkCache(scene, mesh, useInstances)) {
  192. return true;
  193. }
  194. }
  195. }
  196. var engine = scene.getEngine();
  197. var needNormals = false;
  198. var needUVs = false;
  199. this._defines.reset();
  200. // Textures
  201. if (scene.texturesEnabled) {
  202. if (this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  203. if (!this.bumpTexture.isReady()) {
  204. return false;
  205. } else {
  206. needUVs = true;
  207. this._defines.BUMP = true;
  208. }
  209. }
  210. if (StandardMaterial.ReflectionTextureEnabled) {
  211. this._defines.REFLECTION = true;
  212. }
  213. }
  214. // Effect
  215. if (scene.clipPlane) {
  216. this._defines.CLIPPLANE = true;
  217. }
  218. if (engine.getAlphaTesting()) {
  219. this._defines.ALPHATEST = true;
  220. }
  221. // Point size
  222. if (this.pointsCloud || scene.forcePointsCloud) {
  223. this._defines.POINTSIZE = true;
  224. }
  225. if (this.useLogarithmicDepth) {
  226. this._defines.LOGARITHMICDEPTH = true;
  227. }
  228. if (this.fresnelSeparate) {
  229. this._defines.FRESNELSEPARATE = true;
  230. }
  231. if (this.bumpSuperimpose) {
  232. this._defines.BUMPSUPERIMPOSE = true;
  233. }
  234. if (this.bumpAffectsReflection) {
  235. this._defines.BUMPAFFECTSREFLECTION = true;
  236. }
  237. // Fog
  238. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE && this.fogEnabled) {
  239. this._defines.FOG = true;
  240. }
  241. // Lights
  242. if (scene.lightsEnabled && !this.disableLighting) {
  243. needNormals = MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  244. }
  245. // Attribs
  246. if (mesh) {
  247. if (needNormals && mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  248. this._defines.NORMAL = true;
  249. }
  250. if (needUVs) {
  251. if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  252. this._defines.UV1 = true;
  253. }
  254. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
  255. this._defines.UV2 = true;
  256. }
  257. }
  258. if (mesh.useVertexColors && mesh.isVerticesDataPresent(VertexBuffer.ColorKind)) {
  259. this._defines.VERTEXCOLOR = true;
  260. if (mesh.hasVertexAlpha) {
  261. this._defines.VERTEXALPHA = true;
  262. }
  263. }
  264. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  265. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  266. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  267. }
  268. // Instances
  269. if (useInstances) {
  270. this._defines.INSTANCES = true;
  271. }
  272. }
  273. this._mesh = mesh;
  274. // Get correct effect
  275. if (!this._defines.isEqual(this._cachedDefines)) {
  276. this._defines.cloneTo(this._cachedDefines);
  277. scene.resetCachedMaterial();
  278. // Fallbacks
  279. var fallbacks = new EffectFallbacks();
  280. if (this._defines.FOG) {
  281. fallbacks.addFallback(1, "FOG");
  282. }
  283. if (this._defines.LOGARITHMICDEPTH) {
  284. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  285. }
  286. MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  287. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  288. fallbacks.addCPUSkinningFallback(0, mesh);
  289. }
  290. //Attributes
  291. var attribs = [VertexBuffer.PositionKind];
  292. if (this._defines.NORMAL) {
  293. attribs.push(VertexBuffer.NormalKind);
  294. }
  295. if (this._defines.UV1) {
  296. attribs.push(VertexBuffer.UVKind);
  297. }
  298. if (this._defines.UV2) {
  299. attribs.push(VertexBuffer.UV2Kind);
  300. }
  301. if (this._defines.VERTEXCOLOR) {
  302. attribs.push(VertexBuffer.ColorKind);
  303. }
  304. MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  305. MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  306. // Legacy browser patch
  307. var shaderName = "water";
  308. var join = this._defines.toString();
  309. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vDiffuseColor", "vSpecularColor",
  310. "vFogInfos", "vFogColor", "pointSize",
  311. "vNormalInfos",
  312. "mBones",
  313. "vClipPlane", "normalMatrix",
  314. "logarithmicDepthConstant",
  315. // Water
  316. "worldReflectionViewProjection", "windDirection", "waveLength", "time", "windForce",
  317. "cameraPosition", "bumpHeight", "waveHeight", "waterColor", "waterColor2", "colorBlendFactor", "colorBlendFactor2", "waveSpeed"
  318. ]
  319. var samplers = ["normalSampler",
  320. // Water
  321. "refractionSampler", "reflectionSampler"
  322. ];
  323. MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  324. this._effect = scene.getEngine().createEffect(shaderName,
  325. attribs, uniforms, samplers,
  326. join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  327. }
  328. if (!this._effect.isReady()) {
  329. return false;
  330. }
  331. this._renderId = scene.getRenderId();
  332. this._wasPreviouslyReady = true;
  333. if (mesh) {
  334. if (!mesh._materialDefines) {
  335. mesh._materialDefines = new WaterMaterialDefines();
  336. }
  337. this._defines.cloneTo(mesh._materialDefines);
  338. }
  339. return true;
  340. }
  341. public bindOnlyWorldMatrix(world: Matrix): void {
  342. this._effect.setMatrix("world", world);
  343. }
  344. public bind(world: Matrix, mesh?: Mesh): void {
  345. var scene = this.getScene();
  346. // Matrices
  347. this.bindOnlyWorldMatrix(world);
  348. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  349. // Bones
  350. MaterialHelper.BindBonesParameters(mesh, this._effect);
  351. if (scene.getCachedMaterial() !== this) {
  352. // Textures
  353. if (this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  354. this._effect.setTexture("normalSampler", this.bumpTexture);
  355. this._effect.setFloat2("vNormalInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
  356. this._effect.setMatrix("normalMatrix", this.bumpTexture.getTextureMatrix());
  357. }
  358. // Clip plane
  359. MaterialHelper.BindClipPlane(this._effect, scene);
  360. // Point size
  361. if (this.pointsCloud) {
  362. this._effect.setFloat("pointSize", this.pointSize);
  363. }
  364. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  365. }
  366. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  367. if (this._defines.SPECULARTERM) {
  368. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  369. }
  370. if (scene.lightsEnabled && !this.disableLighting) {
  371. MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  372. }
  373. // View
  374. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) {
  375. this._effect.setMatrix("view", scene.getViewMatrix());
  376. }
  377. // Fog
  378. MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  379. // Log. depth
  380. MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  381. // Water
  382. if (StandardMaterial.ReflectionTextureEnabled) {
  383. this._effect.setTexture("refractionSampler", this._refractionRTT);
  384. this._effect.setTexture("reflectionSampler", this._reflectionRTT);
  385. }
  386. var wrvp = this._mesh.getWorldMatrix().multiply(this._reflectionTransform).multiply(scene.getProjectionMatrix());
  387. this._lastTime += scene.getEngine().getDeltaTime();
  388. this._effect.setMatrix("worldReflectionViewProjection", wrvp);
  389. this._effect.setVector2("windDirection", this.windDirection);
  390. this._effect.setFloat("waveLength", this.waveLength);
  391. this._effect.setFloat("time", this._lastTime / 100000);
  392. this._effect.setFloat("windForce", this.windForce);
  393. this._effect.setFloat("waveHeight", this.waveHeight);
  394. this._effect.setFloat("bumpHeight", this.bumpHeight);
  395. this._effect.setColor4("waterColor", this.waterColor, 1.0);
  396. this._effect.setFloat("colorBlendFactor", this.colorBlendFactor);
  397. this._effect.setColor4("waterColor2", this.waterColor2, 1.0);
  398. this._effect.setFloat("colorBlendFactor2", this.colorBlendFactor2);
  399. this._effect.setFloat("waveSpeed", this.waveSpeed);
  400. super.bind(world, mesh);
  401. }
  402. private _createRenderTargets(scene: Scene, renderTargetSize: Vector2): void {
  403. // Render targets
  404. this._refractionRTT = new RenderTargetTexture(name + "_refraction", {width: renderTargetSize.x, height: renderTargetSize.y}, scene, false, true);
  405. this._refractionRTT.wrapU = BABYLON.Texture.MIRROR_ADDRESSMODE;
  406. this._refractionRTT.wrapV = BABYLON.Texture.MIRROR_ADDRESSMODE;
  407. this._reflectionRTT = new RenderTargetTexture(name + "_reflection", {width: renderTargetSize.x, height: renderTargetSize.y}, scene, false, true);
  408. this._reflectionRTT.wrapU = BABYLON.Texture.MIRROR_ADDRESSMODE;
  409. this._reflectionRTT.wrapV = BABYLON.Texture.MIRROR_ADDRESSMODE;
  410. scene.customRenderTargets.push(this._refractionRTT);
  411. scene.customRenderTargets.push(this._reflectionRTT);
  412. var isVisible: boolean;
  413. var clipPlane = null;
  414. var savedViewMatrix;
  415. var mirrorMatrix = Matrix.Zero();
  416. this._refractionRTT.onBeforeRender = () => {
  417. if (this._mesh) {
  418. isVisible = this._mesh.isVisible;
  419. this._mesh.isVisible = false;
  420. }
  421. // Clip plane
  422. clipPlane = scene.clipPlane;
  423. var positiony = this._mesh ? this._mesh.position.y : 0.0;
  424. scene.clipPlane = Plane.FromPositionAndNormal(new Vector3(0, positiony + 0.05, 0), new Vector3(0, 1, 0));
  425. };
  426. this._refractionRTT.onAfterRender = () => {
  427. if (this._mesh) {
  428. this._mesh.isVisible = isVisible;
  429. }
  430. // Clip plane
  431. scene.clipPlane = clipPlane;
  432. };
  433. this._reflectionRTT.onBeforeRender = () => {
  434. if (this._mesh) {
  435. isVisible = this._mesh.isVisible;
  436. this._mesh.isVisible = false;
  437. }
  438. // Clip plane
  439. clipPlane = scene.clipPlane;
  440. var positiony = this._mesh ? this._mesh.position.y : 0.0;
  441. scene.clipPlane = Plane.FromPositionAndNormal(new Vector3(0, positiony - 0.05, 0), new Vector3(0, -1, 0));
  442. // Transform
  443. Matrix.ReflectionToRef(scene.clipPlane, mirrorMatrix);
  444. savedViewMatrix = scene.getViewMatrix();
  445. mirrorMatrix.multiplyToRef(savedViewMatrix, this._reflectionTransform);
  446. scene.setTransformMatrix(this._reflectionTransform, scene.getProjectionMatrix());
  447. scene.getEngine().cullBackFaces = false;
  448. scene._mirroredCameraPosition = Vector3.TransformCoordinates(scene.activeCamera.position, mirrorMatrix);
  449. };
  450. this._reflectionRTT.onAfterRender = () => {
  451. if (this._mesh) {
  452. this._mesh.isVisible = isVisible;
  453. }
  454. // Clip plane
  455. scene.clipPlane = clipPlane;
  456. // Transform
  457. scene.setTransformMatrix(savedViewMatrix, scene.getProjectionMatrix());
  458. scene.getEngine().cullBackFaces = true;
  459. scene._mirroredCameraPosition = null;
  460. };
  461. }
  462. public getAnimatables(): IAnimatable[] {
  463. var results = [];
  464. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  465. results.push(this.bumpTexture);
  466. }
  467. if (this._reflectionRTT && this._reflectionRTT.animations && this._reflectionRTT.animations.length > 0) {
  468. results.push(this._reflectionRTT);
  469. }
  470. if (this._refractionRTT && this._refractionRTT.animations && this._refractionRTT.animations.length > 0) {
  471. results.push(this._refractionRTT);
  472. }
  473. return results;
  474. }
  475. public dispose(forceDisposeEffect?: boolean): void {
  476. if (this.bumpTexture) {
  477. this.bumpTexture.dispose();
  478. }
  479. var index = this.getScene().customRenderTargets.indexOf(this._refractionRTT);
  480. if (index != -1){
  481. this.getScene().customRenderTargets.splice(index, 1);
  482. }
  483. index = -1;
  484. index = this.getScene().customRenderTargets.indexOf(this._reflectionRTT);
  485. if (index != -1){
  486. this.getScene().customRenderTargets.splice(index, 1);
  487. }
  488. if (this._reflectionRTT) {
  489. this._reflectionRTT.dispose();
  490. }
  491. if (this._refractionRTT) {
  492. this._refractionRTT.dispose();
  493. }
  494. super.dispose(forceDisposeEffect);
  495. }
  496. public clone(name: string): WaterMaterial {
  497. return SerializationHelper.Clone(() => new WaterMaterial(name, this.getScene()), this);
  498. }
  499. public serialize(): any {
  500. var serializationObject = SerializationHelper.Serialize(this);
  501. serializationObject.customType = "BABYLON.WaterMaterial";
  502. serializationObject.reflectionTexture.isRenderTarget = true;
  503. serializationObject.refractionTexture.isRenderTarget = true;
  504. return serializationObject;
  505. }
  506. // Statics
  507. public static Parse(source: any, scene: Scene, rootUrl: string): WaterMaterial {
  508. return SerializationHelper.Parse(() => new WaterMaterial(source.name, scene), source, scene, rootUrl);
  509. }
  510. public static CreateDefaultMesh(name: string, scene: Scene): Mesh {
  511. var mesh = Mesh.CreateGround(name, 512, 512, 32, scene, false);
  512. return mesh;
  513. }
  514. }
  515. }