babylon.waterMaterial.ts 20 KB

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