furMaterial.ts 19 KB

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