babylon.furMaterial.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. module BABYLON {
  3. class FurMaterialDefines extends MaterialDefines {
  4. public DIFFUSE = false;
  5. public HEIGHTMAP = false;
  6. public CLIPPLANE = false;
  7. public ALPHATEST = false;
  8. public DEPTHPREPASS = 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 HIGHLEVEL = false;
  20. constructor() {
  21. super();
  22. this.rebuild();
  23. }
  24. }
  25. export class FurMaterial extends PushMaterial {
  26. @serializeAsTexture("diffuseTexture")
  27. private _diffuseTexture: BaseTexture;
  28. @expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29. public diffuseTexture: BaseTexture;
  30. @serializeAsTexture("heightTexture")
  31. private _heightTexture: BaseTexture;
  32. @expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33. public heightTexture: BaseTexture;
  34. @serializeAsColor3()
  35. public diffuseColor = new Color3(1, 1, 1);
  36. @serialize()
  37. public furLength: number = 1;
  38. @serialize()
  39. public furAngle: number = 0;
  40. @serializeAsColor3()
  41. public furColor = new Color3(0.44,0.21,0.02);
  42. @serialize()
  43. public furOffset: number = 0.0;
  44. @serialize()
  45. public furSpacing: number = 12;
  46. @serializeAsVector3()
  47. public furGravity = new Vector3(0, 0, 0);
  48. @serialize()
  49. public furSpeed: number = 100;
  50. @serialize()
  51. public furDensity: number = 20;
  52. public furTexture: DynamicTexture;
  53. @serialize("disableLighting")
  54. private _disableLighting = false;
  55. @expandToProperty("_markAllSubMeshesAsLightsDirty")
  56. public disableLighting: boolean;
  57. @serialize("maxSimultaneousLights")
  58. private _maxSimultaneousLights = 4;
  59. @expandToProperty("_markAllSubMeshesAsLightsDirty")
  60. public maxSimultaneousLights: number;
  61. @serialize()
  62. public highLevelFur: boolean = true;
  63. public _meshes: AbstractMesh[];
  64. private _worldViewProjectionMatrix = Matrix.Zero();
  65. private _renderId: number;
  66. private _furTime: number = 0;
  67. constructor(name: string, scene: Scene) {
  68. super(name, scene);
  69. }
  70. @serialize()
  71. public get furTime() {
  72. return this._furTime;
  73. }
  74. public set furTime(furTime: number) {
  75. this._furTime = furTime;
  76. }
  77. public needAlphaBlending(): boolean {
  78. return (this.alpha < 1.0);
  79. }
  80. public needAlphaTesting(): boolean {
  81. return false;
  82. }
  83. public getAlphaTestTexture(): BaseTexture {
  84. return null;
  85. }
  86. public updateFur(): void {
  87. for (var i = 1; i < this._meshes.length; i++) {
  88. var offsetFur = <FurMaterial>this._meshes[i].material;
  89. offsetFur.furLength = this.furLength;
  90. offsetFur.furAngle = this.furAngle;
  91. offsetFur.furGravity = this.furGravity;
  92. offsetFur.furSpacing = this.furSpacing;
  93. offsetFur.furSpeed = this.furSpeed;
  94. offsetFur.furColor = this.furColor;
  95. offsetFur.diffuseTexture = this.diffuseTexture;
  96. offsetFur.furTexture = this.furTexture;
  97. offsetFur.highLevelFur = this.highLevelFur;
  98. offsetFur.furTime = this.furTime;
  99. offsetFur.furDensity = this.furDensity;
  100. }
  101. }
  102. // Methods
  103. public isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances?: boolean): boolean {
  104. if (this.isFrozen) {
  105. if (this._wasPreviouslyReady && subMesh.effect) {
  106. return true;
  107. }
  108. }
  109. if (!subMesh._materialDefines) {
  110. subMesh._materialDefines = new FurMaterialDefines();
  111. }
  112. var defines = <FurMaterialDefines>subMesh._materialDefines;
  113. var scene = this.getScene();
  114. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  115. if (this._renderId === scene.getRenderId()) {
  116. return true;
  117. }
  118. }
  119. var engine = scene.getEngine();
  120. // Textures
  121. if (defines._areTexturesDirty) {
  122. if (scene.texturesEnabled) {
  123. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  124. if (!this.diffuseTexture.isReady()) {
  125. return false;
  126. } else {
  127. defines._needUVs = true;
  128. defines.DIFFUSE = true;
  129. }
  130. }
  131. if (this.heightTexture && engine.getCaps().maxVertexTextureImageUnits) {
  132. if (!this.heightTexture.isReady()) {
  133. return false;
  134. } else {
  135. defines._needUVs = true;
  136. defines.HEIGHTMAP = true;
  137. }
  138. }
  139. }
  140. }
  141. // High level
  142. if (this.highLevelFur !== defines.HIGHLEVEL) {
  143. defines.HIGHLEVEL = true;
  144. defines.markAsUnprocessed();
  145. }
  146. // Misc.
  147. MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  148. // Lights
  149. defines._needNormals = MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights, this._disableLighting);
  150. // Values that need to be evaluated on every frame
  151. MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  152. // Attribs
  153. MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true);
  154. // Get correct effect
  155. if (defines.isDirty) {
  156. defines.markAsProcessed();
  157. scene.resetCachedMaterial();
  158. // Fallbacks
  159. var fallbacks = new EffectFallbacks();
  160. if (defines.FOG) {
  161. fallbacks.addFallback(1, "FOG");
  162. }
  163. MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this.maxSimultaneousLights);
  164. if (defines.NUM_BONE_INFLUENCERS > 0) {
  165. fallbacks.addCPUSkinningFallback(0, mesh);
  166. }
  167. //Attributes
  168. var attribs = [VertexBuffer.PositionKind];
  169. if (defines.NORMAL) {
  170. attribs.push(VertexBuffer.NormalKind);
  171. }
  172. if (defines.UV1) {
  173. attribs.push(VertexBuffer.UVKind);
  174. }
  175. if (defines.UV2) {
  176. attribs.push(VertexBuffer.UV2Kind);
  177. }
  178. if (defines.VERTEXCOLOR) {
  179. attribs.push(VertexBuffer.ColorKind);
  180. }
  181. MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  182. MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  183. // Legacy browser patch
  184. var shaderName = "fur";
  185. var join = defines.toString();
  186. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vDiffuseColor",
  187. "vFogInfos", "vFogColor", "pointSize",
  188. "vDiffuseInfos",
  189. "mBones",
  190. "vClipPlane", "diffuseMatrix",
  191. "furLength", "furAngle", "furColor", "furOffset", "furGravity", "furTime", "furSpacing", "furDensity"
  192. ];
  193. var samplers = ["diffuseSampler",
  194. "heightTexture", "furTexture"
  195. ];
  196. var uniformBuffers = [];
  197. MaterialHelper.PrepareUniformsAndSamplersList(<EffectCreationOptions>{
  198. uniformsNames: uniforms,
  199. uniformBuffersNames: uniformBuffers,
  200. samplers: samplers,
  201. defines: defines,
  202. maxSimultaneousLights: this.maxSimultaneousLights
  203. });
  204. subMesh.setEffect(scene.getEngine().createEffect(shaderName,
  205. <EffectCreationOptions>{
  206. attributes: attribs,
  207. uniformsNames: uniforms,
  208. uniformBuffersNames: uniformBuffers,
  209. samplers: samplers,
  210. defines: join,
  211. fallbacks: fallbacks,
  212. onCompiled: this.onCompiled,
  213. onError: this.onError,
  214. indexParameters: { maxSimultaneousLights: this.maxSimultaneousLights }
  215. }, engine), defines);
  216. }
  217. if (!subMesh.effect.isReady()) {
  218. return false;
  219. }
  220. this._renderId = scene.getRenderId();
  221. this._wasPreviouslyReady = true;
  222. return true;
  223. }
  224. public bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void {
  225. var scene = this.getScene();
  226. var defines = <FurMaterialDefines>subMesh._materialDefines;
  227. if (!defines) {
  228. return;
  229. }
  230. var effect = subMesh.effect;
  231. this._activeEffect = effect;
  232. // Matrices
  233. this.bindOnlyWorldMatrix(world);
  234. this._activeEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  235. // Bones
  236. MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  237. if (scene.getCachedMaterial() !== this) {
  238. // Textures
  239. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  240. this._activeEffect.setTexture("diffuseSampler", this._diffuseTexture);
  241. this._activeEffect.setFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  242. this._activeEffect.setMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  243. }
  244. if (this._heightTexture) {
  245. this._activeEffect.setTexture("heightTexture", this._heightTexture);
  246. }
  247. // Clip plane
  248. MaterialHelper.BindClipPlane(this._activeEffect, scene);
  249. // Point size
  250. if (this.pointsCloud) {
  251. this._activeEffect.setFloat("pointSize", this.pointSize);
  252. }
  253. this._activeEffect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  254. }
  255. this._activeEffect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  256. if (scene.lightsEnabled && !this.disableLighting) {
  257. MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this.maxSimultaneousLights);
  258. }
  259. // View
  260. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) {
  261. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  262. }
  263. // Fog
  264. MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  265. this._activeEffect.setFloat("furLength", this.furLength);
  266. this._activeEffect.setFloat("furAngle", this.furAngle);
  267. this._activeEffect.setColor4("furColor", this.furColor, 1.0);
  268. if (this.highLevelFur) {
  269. this._activeEffect.setVector3("furGravity", this.furGravity);
  270. this._activeEffect.setFloat("furOffset", this.furOffset);
  271. this._activeEffect.setFloat("furSpacing", this.furSpacing);
  272. this._activeEffect.setFloat("furDensity", this.furDensity);
  273. this._furTime += this.getScene().getEngine().getDeltaTime() / this.furSpeed;
  274. this._activeEffect.setFloat("furTime", this._furTime);
  275. this._activeEffect.setTexture("furTexture", this.furTexture);
  276. }
  277. this._afterBind(mesh, this._activeEffect);
  278. }
  279. public getAnimatables(): IAnimatable[] {
  280. var results = [];
  281. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  282. results.push(this.diffuseTexture);
  283. }
  284. if (this.heightTexture && this.heightTexture.animations && this.heightTexture.animations.length > 0) {
  285. results.push(this.heightTexture);
  286. }
  287. return results;
  288. }
  289. public getActiveTextures(): BaseTexture[] {
  290. var activeTextures = super.getActiveTextures();
  291. if (this._diffuseTexture) {
  292. activeTextures.push(this._diffuseTexture);
  293. }
  294. if (this._heightTexture) {
  295. activeTextures.push(this._heightTexture);
  296. }
  297. return activeTextures;
  298. }
  299. public hasTexture(texture: BaseTexture): boolean {
  300. if (super.hasTexture(texture)) {
  301. return true;
  302. }
  303. if (this.diffuseTexture === texture) {
  304. return true;
  305. }
  306. if (this._heightTexture === texture) {
  307. return true;
  308. }
  309. return false;
  310. }
  311. public dispose(forceDisposeEffect?: boolean): void {
  312. if (this.diffuseTexture) {
  313. this.diffuseTexture.dispose();
  314. }
  315. if (this._meshes) {
  316. for (var i = 1; i < this._meshes.length; i++) {
  317. this._meshes[i].material.dispose(forceDisposeEffect);
  318. this._meshes[i].dispose();
  319. }
  320. }
  321. super.dispose(forceDisposeEffect);
  322. }
  323. public clone(name: string): FurMaterial {
  324. return SerializationHelper.Clone(() => new FurMaterial(name, this.getScene()), this);
  325. }
  326. public serialize(): any {
  327. var serializationObject = SerializationHelper.Serialize(this);
  328. serializationObject.customType = "BABYLON.FurMaterial";
  329. if (this._meshes) {
  330. serializationObject.sourceMeshName = this._meshes[0].name;
  331. serializationObject.quality = this._meshes.length;
  332. }
  333. return serializationObject;
  334. }
  335. public getClassName(): string {
  336. return "FurMaterial";
  337. }
  338. // Statics
  339. public static Parse(source: any, scene: Scene, rootUrl: string): FurMaterial {
  340. var material = SerializationHelper.Parse(() => new FurMaterial(source.name, scene), source, scene, rootUrl);
  341. if (source.sourceMeshName && material.highLevelFur) {
  342. scene.executeWhenReady(() => {
  343. var sourceMesh = <Mesh>scene.getMeshByName(source.sourceMeshName);
  344. if (sourceMesh) {
  345. var furTexture = FurMaterial.GenerateTexture("Fur Texture", scene);
  346. material.furTexture = furTexture;
  347. FurMaterial.FurifyMesh(sourceMesh, source.quality);
  348. }
  349. });
  350. }
  351. return material;
  352. }
  353. public static GenerateTexture(name: string, scene: Scene): DynamicTexture {
  354. // Generate fur textures
  355. var texture = new DynamicTexture("FurTexture " + name, 256, scene, true);
  356. var context = texture.getContext();
  357. for ( var i = 0; i < 20000; ++i ) {
  358. context.fillStyle = "rgba(255, " + Math.floor(Math.random() * 255) + ", " + Math.floor(Math.random() * 255) + ", 1)";
  359. context.fillRect((Math.random() * texture.getSize().width), (Math.random() * texture.getSize().height), 2, 2);
  360. }
  361. texture.update(false);
  362. texture.wrapU = Texture.WRAP_ADDRESSMODE;
  363. texture.wrapV = Texture.WRAP_ADDRESSMODE;
  364. return texture;
  365. }
  366. // Creates and returns an array of meshes used as shells for the Fur Material
  367. // that can be disposed later in your code
  368. // The quality is in interval [0, 100]
  369. public static FurifyMesh(sourceMesh: Mesh, quality: number): Mesh[] {
  370. var meshes = [sourceMesh];
  371. var mat: FurMaterial = <FurMaterial>sourceMesh.material;
  372. var i;
  373. if (!(mat instanceof FurMaterial)) {
  374. throw "The material of the source mesh must be a Fur Material";
  375. }
  376. for (i = 1; i < quality; i++) {
  377. var offsetFur = new BABYLON.FurMaterial(mat.name + i, sourceMesh.getScene());
  378. sourceMesh.getScene().materials.pop();
  379. Tags.EnableFor(offsetFur);
  380. Tags.AddTagsTo(offsetFur, "furShellMaterial");
  381. offsetFur.furLength = mat.furLength;
  382. offsetFur.furAngle = mat.furAngle;
  383. offsetFur.furGravity = mat.furGravity;
  384. offsetFur.furSpacing = mat.furSpacing;
  385. offsetFur.furSpeed = mat.furSpeed;
  386. offsetFur.furColor = mat.furColor;
  387. offsetFur.diffuseTexture = mat.diffuseTexture;
  388. offsetFur.furOffset = i / quality;
  389. offsetFur.furTexture = mat.furTexture;
  390. offsetFur.highLevelFur = mat.highLevelFur;
  391. offsetFur.furTime = mat.furTime;
  392. offsetFur.furDensity = mat.furDensity;
  393. var offsetMesh = sourceMesh.clone(sourceMesh.name + i);
  394. offsetMesh.material = offsetFur;
  395. offsetMesh.skeleton = sourceMesh.skeleton;
  396. offsetMesh.position = Vector3.Zero();
  397. meshes.push(offsetMesh);
  398. }
  399. for (i = 1; i < meshes.length; i++) {
  400. meshes[i].parent = sourceMesh;
  401. }
  402. (<FurMaterial>sourceMesh.material)._meshes = meshes;
  403. return meshes;
  404. }
  405. }
  406. }