furMaterial.ts 19 KB

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