materialDefinition.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "materials/materialDefinition.h"
  24. #include "console/consoleTypes.h"
  25. #include "console/engineAPI.h"
  26. #include "math/mathTypes.h"
  27. #include "materials/materialManager.h"
  28. #include "sceneData.h"
  29. #include "gfx/sim/cubemapData.h"
  30. #include "gfx/gfxCubemap.h"
  31. #include "math/mathIO.h"
  32. #include "materials/matInstance.h"
  33. #include "sfx/sfxTrack.h"
  34. #include "sfx/sfxTypes.h"
  35. #include "core/util/safeDelete.h"
  36. #include "T3D/accumulationVolume.h"
  37. #include "gui/controls/guiTreeViewCtrl.h"
  38. #include <console/persistenceManager.h>
  39. IMPLEMENT_CONOBJECT(Material);
  40. ConsoleDocClass(Material,
  41. "@brief A material in Torque 3D is a data structure that describes a surface.\n\n"
  42. "It contains many different types of information for rendering properties. "
  43. "Torque 3D generates shaders from Material definitions. The shaders are compiled "
  44. "at runtime and output into the example/shaders directory. Any errors or warnings "
  45. "generated from compiling the procedurally generated shaders are output to the console "
  46. "as well as the output window in the Visual C IDE.\n\n"
  47. "@tsexample\n"
  48. "singleton Material(DECAL_scorch)\n"
  49. "{\n"
  50. " baseTex[0] = \"./scorch_decal.png\";\n"
  51. " vertColor[ 0 ] = true;\n\n"
  52. " translucent = true;\n"
  53. " translucentBlendOp = None;\n"
  54. " translucentZWrite = true;\n"
  55. " alphaTest = true;\n"
  56. " alphaRef = 84;\n"
  57. "};\n"
  58. "@endtsexample\n\n"
  59. "@see Rendering\n"
  60. "@see ShaderData\n"
  61. "@ingroup GFX\n");
  62. ImplementBitfieldType(MaterialAnimType,
  63. "The type of animation effect to apply to this material.\n"
  64. "@ingroup GFX\n\n")
  65. {
  66. Material::Scroll, "Scroll", "Scroll the material along the X/Y axis.\n"
  67. },
  68. { Material::Rotate, "Rotate" , "Rotate the material around a point.\n" },
  69. { Material::Wave, "Wave" , "Warps the material with an animation using Sin, Triangle or Square mathematics.\n" },
  70. { Material::Scale, "Scale", "Scales the material larger and smaller with a pulsing effect.\n" },
  71. { Material::Sequence, "Sequence", "Enables the material to have multiple frames of animation in its imagemap.\n" }
  72. EndImplementBitfieldType;
  73. ImplementEnumType(MaterialBlendOp,
  74. "The type of graphical blending operation to apply to this material\n"
  75. "@ingroup GFX\n\n")
  76. {
  77. Material::None, "None", "Disable blending for this material."
  78. },
  79. { Material::Mul, "Mul", "Multiplicative blending." },
  80. { Material::PreMul, "PreMul", "Premultiplied alpha." },
  81. { Material::Add, "Add", "Adds the color of the material to the frame buffer with full alpha for each pixel." },
  82. { Material::AddAlpha, "AddAlpha", "The color is modulated by the alpha channel before being added to the frame buffer." },
  83. { Material::Sub, "Sub", "Subtractive Blending. Reverses the color model, causing dark colors to have a stronger visual effect." },
  84. { Material::LerpAlpha, "LerpAlpha", "Linearly interpolates between Material color and frame buffer color based on alpha." }
  85. EndImplementEnumType;
  86. ImplementEnumType(MaterialWaveType,
  87. "When using the Wave material animation, one of these Wave Types will be used to determine the type of wave to display.\n"
  88. "@ingroup GFX\n")
  89. {
  90. Material::Sin, "Sin", "Warps the material along a curved Sin Wave."
  91. },
  92. { Material::Triangle, "Triangle", "Warps the material along a sharp Triangle Wave." },
  93. { Material::Square, "Square", "Warps the material along a wave which transitions between two oppposite states. As a Square Wave, the transition is quick and sudden." },
  94. EndImplementEnumType;
  95. bool Material::sAllowTextureTargetAssignment = false;
  96. GFXCubemap* Material::GetNormalizeCube()
  97. {
  98. if (smNormalizeCube)
  99. return smNormalizeCube;
  100. smNormalizeCube = GFX->createCubemap();
  101. smNormalizeCube->initNormalize(64);
  102. return smNormalizeCube;
  103. }
  104. GFXCubemapHandle Material::smNormalizeCube;
  105. Material::Material()
  106. {
  107. for (U32 i = 0; i < MAX_STAGES; i++)
  108. {
  109. mDiffuse[i].set(1.0f, 1.0f, 1.0f, 1.0f);
  110. mDiffuseMapSRGB[i] = true;
  111. mRoughness[i] = 1.0f;
  112. mMetalness[i] = 0.0f;
  113. mIsSRGb[i] = false;
  114. mAOChan[i] = 0;
  115. mInvertRoughness[i] = false;
  116. mRoughnessChan[i] = 1;
  117. mMetalChan[i] = 2;
  118. mAccuEnabled[i] = false;
  119. mAccuScale[i] = 1.0f;
  120. mAccuDirection[i] = 1.0f;
  121. mAccuStrength[i] = 0.6f;
  122. mAccuCoverage[i] = 0.9f;
  123. mAccuSpecular[i] = 16.0f;
  124. INIT_IMAGEASSET_ARRAY(DiffuseMap, GFXStaticTextureSRGBProfile, i);
  125. INIT_IMAGEASSET_ARRAY(OverlayMap, GFXStaticTextureProfile, i);
  126. INIT_IMAGEASSET_ARRAY(LightMap, GFXStaticTextureProfile, i);
  127. INIT_IMAGEASSET_ARRAY(ToneMap, GFXStaticTextureProfile, i);
  128. INIT_IMAGEASSET_ARRAY(DetailMap, GFXStaticTextureProfile, i);
  129. INIT_IMAGEASSET_ARRAY(NormalMap, GFXNormalMapProfile, i);
  130. INIT_IMAGEASSET_ARRAY(ORMConfigMap, GFXStaticTextureProfile, i);
  131. INIT_IMAGEASSET_ARRAY(RoughMap, GFXStaticTextureProfile, i);
  132. INIT_IMAGEASSET_ARRAY(AOMap, GFXStaticTextureProfile, i);
  133. INIT_IMAGEASSET_ARRAY(MetalMap, GFXStaticTextureProfile, i);
  134. INIT_IMAGEASSET_ARRAY(GlowMap, GFXStaticTextureProfile, i);
  135. INIT_IMAGEASSET_ARRAY(DetailNormalMap, GFXNormalMapProfile, i);
  136. mParallaxScale[i] = 0.0f;
  137. mVertLit[i] = false;
  138. mVertColor[i] = false;
  139. mGlow[i] = false;
  140. mEmissive[i] = false;
  141. mDetailScale[i].set(2.0f, 2.0f);
  142. mDetailNormalMapStrength[i] = 1.0f;
  143. mMinnaertConstant[i] = -1.0f;
  144. mSubSurface[i] = false;
  145. mSubSurfaceColor[i].set(1.0f, 0.2f, 0.2f, 1.0f);
  146. mSubSurfaceRolloff[i] = 0.2f;
  147. mAnimFlags[i] = 0;
  148. mScrollDir[i].set(0.0f, 0.0f);
  149. mScrollSpeed[i] = 0.0f;
  150. mScrollOffset[i].set(0.0f, 0.0f);
  151. mRotSpeed[i] = 0.0f;
  152. mRotPivotOffset[i].set(0.0f, 0.0f);
  153. mRotPos[i] = 0.0f;
  154. mWavePos[i] = 0.0f;
  155. mWaveFreq[i] = 0.0f;
  156. mWaveAmp[i] = 0.0f;
  157. mWaveType[i] = 0;
  158. mSeqFramePerSec[i] = 0.0f;
  159. mSeqSegSize[i] = 0.0f;
  160. // Deferred Shading
  161. mMatInfoFlags[i] = 0.0f;
  162. mGlowMul[i] = 0.0f;
  163. }
  164. dMemset(mCellIndex, 0, sizeof(mCellIndex));
  165. dMemset(mCellLayout, 0, sizeof(mCellLayout));
  166. dMemset(mCellSize, 0, sizeof(mCellSize));
  167. dMemset(mNormalMapAtlas, 0, sizeof(mNormalMapAtlas));
  168. dMemset(mUseAnisotropic, 1, sizeof(mUseAnisotropic));
  169. mImposterLimits = Point4F::Zero;
  170. mDoubleSided = false;
  171. mTranslucent = false;
  172. mTranslucentBlendOp = PreMul;
  173. mTranslucentZWrite = false;
  174. mAlphaTest = false;
  175. mAlphaRef = 1;
  176. mCastShadows = true;
  177. mPlanarReflection = false;
  178. mCubemapData = NULL;
  179. mDynamicCubemap = false;
  180. mLastUpdateTime = 0;
  181. mAutoGenerated = false;
  182. mShowDust = false;
  183. mShowFootprints = true;
  184. dMemset(mEffectColor, 0, sizeof(mEffectColor));
  185. mEffectColor[0] = LinearColorF::WHITE;
  186. mEffectColor[1] = LinearColorF::WHITE;
  187. mFootstepSoundId = -1; mImpactSoundId = -1;
  188. mImpactFXIndex = -1;
  189. INIT_ASSET(CustomFootstepSound);
  190. INIT_ASSET(CustomImpactSound);
  191. mFriction = 0.0;
  192. mDirectSoundOcclusion = 1.f;
  193. mReverbSoundOcclusion = 1.0;
  194. }
  195. void Material::initPersistFields()
  196. {
  197. addField("mapTo", TypeRealString, Offset(mMapTo, Material),
  198. "Used to map this material to the material name used by TSShape.");
  199. addArray("Stages", MAX_STAGES);
  200. addField("diffuseColor", TypeColorF, Offset(mDiffuse, Material), MAX_STAGES,
  201. "This color is multiplied against the diffuse texture color. If no diffuse texture "
  202. "is present this is the material color.");
  203. INITPERSISTFIELD_IMAGEASSET_ARRAY(DiffuseMap, MAX_STAGES, Material, "Albedo");
  204. INITPERSISTFIELD_IMAGEASSET_ARRAY(OverlayMap, MAX_STAGES, Material, "Overlay");
  205. INITPERSISTFIELD_IMAGEASSET_ARRAY(LightMap, MAX_STAGES, Material, "LightMap");
  206. INITPERSISTFIELD_IMAGEASSET_ARRAY(ToneMap, MAX_STAGES, Material, "ToneMap");
  207. INITPERSISTFIELD_IMAGEASSET_ARRAY(DetailMap, MAX_STAGES, Material, "DetailMap");
  208. INITPERSISTFIELD_IMAGEASSET_ARRAY(NormalMap, MAX_STAGES, Material, "NormalMap");
  209. INITPERSISTFIELD_IMAGEASSET_ARRAY(ORMConfigMap, MAX_STAGES, Material, "AO|Roughness|metalness map");
  210. INITPERSISTFIELD_IMAGEASSET_ARRAY(RoughMap, MAX_STAGES, Material, "RoughMap (also needs MetalMap)");
  211. INITPERSISTFIELD_IMAGEASSET_ARRAY(AOMap, MAX_STAGES, Material, "AOMap");
  212. INITPERSISTFIELD_IMAGEASSET_ARRAY(MetalMap, MAX_STAGES, Material, "MetalMap (also needs RoughMap)");
  213. INITPERSISTFIELD_IMAGEASSET_ARRAY(GlowMap, MAX_STAGES, Material, "GlowMap (needs Albedo)");
  214. INITPERSISTFIELD_IMAGEASSET_ARRAY(DetailNormalMap, MAX_STAGES, Material, "DetailNormalMap");
  215. addField("diffuseMapSRGB", TypeBool, Offset(mDiffuseMapSRGB, Material), MAX_STAGES,
  216. "Enable sRGB for the diffuse color texture map.");
  217. addField("detailScale", TypePoint2F, Offset(mDetailScale, Material), MAX_STAGES,
  218. "The scale factor for the detail map.");
  219. addField("detailNormalMapStrength", TypeF32, Offset(mDetailNormalMapStrength, Material), MAX_STAGES,
  220. "Used to scale the strength of the detail normal map when blended with the base normal map.");
  221. addField("roughness", TypeF32, Offset(mRoughness, Material), MAX_STAGES,
  222. "The degree of roughness when not using a ORMConfigMap.");
  223. addField("metalness", TypeF32, Offset(mMetalness, Material), MAX_STAGES,
  224. "The degree of Metalness when not using a ORMConfigMap.");
  225. addField("glowMul", TypeF32, Offset(mGlowMul, Material), MAX_STAGES,
  226. "glow mask multiplier");
  227. addProtectedField("accuEnabled", TYPEID< bool >(), Offset(mAccuEnabled, Material),
  228. &_setAccuEnabled, &defaultProtectedGetFn, MAX_STAGES, "Accumulation texture.");
  229. addField("accuScale", TypeF32, Offset(mAccuScale, Material), MAX_STAGES,
  230. "The scale that is applied to the accu map texture. You can use this to fit the texture to smaller or larger objects.");
  231. addField("accuDirection", TypeF32, Offset(mAccuDirection, Material), MAX_STAGES,
  232. "The direction of the accumulation. Chose whether you want the accu map to go from top to bottom (ie. snow) or upwards (ie. mold).");
  233. addField("accuStrength", TypeF32, Offset(mAccuStrength, Material), MAX_STAGES,
  234. "The strength of the accu map. This changes the transparency of the accu map texture. Make it subtle or add more contrast.");
  235. addField("accuCoverage", TypeF32, Offset(mAccuCoverage, Material), MAX_STAGES,
  236. "The coverage ratio of the accu map texture. Use this to make the entire shape pick up some of the accu map texture or none at all.");
  237. addField("accuSpecular", TypeF32, Offset(mAccuSpecular, Material), MAX_STAGES,
  238. "Changes specularity to this value where the accumulated material is present.");
  239. addField("isSRGb", TypeBool, Offset(mIsSRGb, Material), MAX_STAGES,
  240. "Substance Designer Workaround.");
  241. addField("invertRoughness", TypeBool, Offset(mInvertRoughness, Material), MAX_STAGES,
  242. "Treat Roughness as Roughness");
  243. addField("roughnessChan", TypeF32, Offset(mRoughnessChan, Material), MAX_STAGES,
  244. "The input channel roughness maps use.");
  245. addField("AOChan", TypeF32, Offset(mAOChan, Material), MAX_STAGES,
  246. "The input channel AO maps use.");
  247. addField("metalChan", TypeF32, Offset(mMetalChan, Material), MAX_STAGES,
  248. "The input channel metalness maps use.");
  249. addField("glow", TypeBool, Offset(mGlow, Material), MAX_STAGES,
  250. "Enables rendering as glowing.");
  251. addField("parallaxScale", TypeF32, Offset(mParallaxScale, Material), MAX_STAGES,
  252. "Enables parallax mapping and defines the scale factor for the parallax effect. Typically "
  253. "this value is less than 0.4 else the effect breaks down.");
  254. addField("useAnisotropic", TypeBool, Offset(mUseAnisotropic, Material), MAX_STAGES,
  255. "Use anisotropic filtering for the textures of this stage.");
  256. addField("vertLit", TypeBool, Offset(mVertLit, Material), MAX_STAGES,
  257. "If true the vertex color is used for lighting.");
  258. addField("vertColor", TypeBool, Offset(mVertColor, Material), MAX_STAGES,
  259. "If enabled, vertex colors are premultiplied with diffuse colors.");
  260. addField("minnaertConstant", TypeF32, Offset(mMinnaertConstant, Material), MAX_STAGES,
  261. "The Minnaert shading constant value. Must be greater than 0 to enable the effect.");
  262. addField("subSurface", TypeBool, Offset(mSubSurface, Material), MAX_STAGES,
  263. "Enables the subsurface scattering approximation.");
  264. addField("subSurfaceColor", TypeColorF, Offset(mSubSurfaceColor, Material), MAX_STAGES,
  265. "The color used for the subsurface scattering approximation.");
  266. addField("subSurfaceRolloff", TypeF32, Offset(mSubSurfaceRolloff, Material), MAX_STAGES,
  267. "The 0 to 1 rolloff factor used in the subsurface scattering approximation.");
  268. addField("emissive", TypeBool, Offset(mEmissive, Material), MAX_STAGES,
  269. "Enables emissive lighting for the material.");
  270. addField("doubleSided", TypeBool, Offset(mDoubleSided, Material),
  271. "Disables backface culling casing surfaces to be double sided. "
  272. "Note that the lighting on the backside will be a mirror of the front "
  273. "side of the surface.");
  274. addField("animFlags", TYPEID< AnimType >(), Offset(mAnimFlags, Material), MAX_STAGES,
  275. "The types of animation to play on this material.");
  276. addField("scrollDir", TypePoint2F, Offset(mScrollDir, Material), MAX_STAGES,
  277. "The scroll direction in UV space when scroll animation is enabled.");
  278. addField("scrollSpeed", TypeF32, Offset(mScrollSpeed, Material), MAX_STAGES,
  279. "The speed to scroll the texture in UVs per second when scroll animation is enabled.");
  280. addField("rotSpeed", TypeF32, Offset(mRotSpeed, Material), MAX_STAGES,
  281. "The speed to rotate the texture in degrees per second when rotation animation is enabled.");
  282. addField("rotPivotOffset", TypePoint2F, Offset(mRotPivotOffset, Material), MAX_STAGES,
  283. "The piviot position in UV coordinates to center the rotation animation.");
  284. addField("waveType", TYPEID< WaveType >(), Offset(mWaveType, Material), MAX_STAGES,
  285. "The type of wave animation to perform when wave animation is enabled.");
  286. addField("waveFreq", TypeF32, Offset(mWaveFreq, Material), MAX_STAGES,
  287. "The wave frequency when wave animation is enabled.");
  288. addField("waveAmp", TypeF32, Offset(mWaveAmp, Material), MAX_STAGES,
  289. "The wave amplitude when wave animation is enabled.");
  290. addField("sequenceFramePerSec", TypeF32, Offset(mSeqFramePerSec, Material), MAX_STAGES,
  291. "The number of frames per second for frame based sequence animations if greater than zero.");
  292. addField("sequenceSegmentSize", TypeF32, Offset(mSeqSegSize, Material), MAX_STAGES,
  293. "The size of each frame in UV units for sequence animations.");
  294. // Texture atlasing
  295. addField("cellIndex", TypePoint2I, Offset(mCellIndex, Material), MAX_STAGES,
  296. "@internal");
  297. addField("cellLayout", TypePoint2I, Offset(mCellLayout, Material), MAX_STAGES,
  298. "@internal");
  299. addField("cellSize", TypeS32, Offset(mCellSize, Material), MAX_STAGES,
  300. "@internal");
  301. addField("bumpAtlas", TypeBool, Offset(mNormalMapAtlas, Material), MAX_STAGES,
  302. "@internal");
  303. // For backwards compatibility.
  304. //
  305. // They point at the new 'map' fields, but reads always return
  306. // an empty string and writes only apply if the value is not empty.
  307. //
  308. addProtectedField("baseTex", TypeImageFilename, Offset(mDiffuseMapName, Material),
  309. defaultProtectedSetNotEmptyFn, emptyStringProtectedGetFn, MAX_STAGES,
  310. "For backwards compatibility.\n@see diffuseMap\n", AbstractClassRep::FIELD_HideInInspectors);
  311. addProtectedField("detailTex", TypeImageFilename, Offset(mDetailMapName, Material),
  312. defaultProtectedSetNotEmptyFn, emptyStringProtectedGetFn, MAX_STAGES,
  313. "For backwards compatibility.\n@see detailMap\n", AbstractClassRep::FIELD_HideInInspectors);
  314. addProtectedField("overlayTex", TypeImageFilename, Offset(mOverlayMapName, Material),
  315. defaultProtectedSetNotEmptyFn, emptyStringProtectedGetFn, MAX_STAGES,
  316. "For backwards compatibility.\n@see overlayMap\n", AbstractClassRep::FIELD_HideInInspectors);
  317. addProtectedField("bumpTex", TypeImageFilename, Offset(mNormalMapName, Material),
  318. defaultProtectedSetNotEmptyFn, emptyStringProtectedGetFn, MAX_STAGES,
  319. "For backwards compatibility.\n@see normalMap\n", AbstractClassRep::FIELD_HideInInspectors);
  320. addProtectedField("colorMultiply", TypeColorF, Offset(mDiffuse, Material),
  321. defaultProtectedSetNotEmptyFn, emptyStringProtectedGetFn, MAX_STAGES,
  322. "For backwards compatibility.\n@see diffuseColor\n", AbstractClassRep::FIELD_HideInInspectors);
  323. endArray("Stages");
  324. addField("castShadows", TypeBool, Offset(mCastShadows, Material),
  325. "If set to false the lighting system will not cast shadows from this material.");
  326. addField("planarReflection", TypeBool, Offset(mPlanarReflection, Material), "@internal");
  327. addField("translucent", TypeBool, Offset(mTranslucent, Material),
  328. "If true this material is translucent blended.");
  329. addField("translucentBlendOp", TYPEID< BlendOp >(), Offset(mTranslucentBlendOp, Material),
  330. "The type of blend operation to use when the material is translucent.");
  331. addField("translucentZWrite", TypeBool, Offset(mTranslucentZWrite, Material),
  332. "If enabled and the material is translucent it will write into the depth buffer.");
  333. addField("alphaTest", TypeBool, Offset(mAlphaTest, Material),
  334. "Enables alpha test when rendering the material.\n@see alphaRef\n");
  335. addField("alphaRef", TypeS32, Offset(mAlphaRef, Material),
  336. "The alpha reference value for alpha testing. Must be between 0 to 255.\n@see alphaTest\n");
  337. addField("cubemap", TypeRealString, Offset(mCubemapName, Material),
  338. "The name of a CubemapData for environment mapping.");
  339. addField("dynamicCubemap", TypeBool, Offset(mDynamicCubemap, Material),
  340. "Enables the material to use the dynamic cubemap from the ShapeBase object its applied to.");
  341. addGroup("Behavioral");
  342. addField("showFootprints", TypeBool, Offset(mShowFootprints, Material),
  343. "Whether to show player footprint decals on this material.\n\n"
  344. "@see PlayerData::decalData");
  345. addField("showDust", TypeBool, Offset(mShowDust, Material),
  346. "Whether to emit dust particles from a shape moving over the material. This is, for example, used by "
  347. "vehicles or players to decide whether to show dust trails.");
  348. addField("effectColor", TypeColorF, Offset(mEffectColor, Material), NUM_EFFECT_COLOR_STAGES,
  349. "If #showDust is true, this is the set of colors to use for the ParticleData of the dust "
  350. "emitter.\n\n"
  351. "@see ParticleData::colors");
  352. addField("footstepSoundId", TypeS32, Offset(mFootstepSoundId, Material),
  353. "What sound to play from the PlayerData sound list when the player walks over the material. -1 (default) to not play any sound.\n"
  354. "\n"
  355. "The IDs are:\n\n"
  356. "- 0: PlayerData::FootSoftSound\n"
  357. "- 1: PlayerData::FootHardSound\n"
  358. "- 2: PlayerData::FootMetalSound\n"
  359. "- 3: PlayerData::FootSnowSound\n"
  360. "- 4: PlayerData::FootShallowSound\n"
  361. "- 5: PlayerData::FootWadingSound\n"
  362. "- 6: PlayerData::FootUnderwaterSound\n"
  363. "- 7: PlayerData::FootBubblesSound\n"
  364. "- 8: PlayerData::movingBubblesSound\n"
  365. "- 9: PlayerData::waterBreathSound\n"
  366. "- 10: PlayerData::impactSoftSound\n"
  367. "- 11: PlayerData::impactHardSound\n"
  368. "- 12: PlayerData::impactMetalSound\n"
  369. "- 13: PlayerData::impactSnowSound\n"
  370. "- 14: PlayerData::impactWaterEasy\n"
  371. "- 15: PlayerData::impactWaterMedium\n"
  372. "- 16: PlayerData::impactWaterHard\n"
  373. "- 17: PlayerData::exitingWater\n");
  374. INITPERSISTFIELD_SOUNDASSET(CustomFootstepSound, Material,
  375. "The sound to play when the player walks over the material. If this is set, it overrides #footstepSoundId. This field is "
  376. "useful for directly assigning custom footstep sounds to materials without having to rely on the PlayerData sound assignment.\n\n"
  377. "@warn Be aware that materials are client-side objects. This means that the SFXTracks assigned to materials must be client-side, too.");
  378. addField("impactSoundId", TypeS32, Offset(mImpactSoundId, Material),
  379. "What sound to play from the PlayerData sound list when the player impacts on the surface with a velocity equal or greater "
  380. "than PlayerData::groundImpactMinSpeed.\n\n"
  381. "For a list of IDs, see #footstepSoundId");
  382. addField("ImpactFXIndex", TypeS32, Offset(mImpactFXIndex, Material),
  383. "What FX to play from the PlayerData sound list when the player impacts on the surface with a velocity equal or greater "
  384. "than PlayerData::groundImpactMinSpeed.\n\n"
  385. "For a list of IDs, see #impactFXId");
  386. INITPERSISTFIELD_SOUNDASSET(CustomImpactSound, Material,
  387. "The sound to play when the player impacts on the surface with a velocity equal or greater than PlayerData::groundImpactMinSpeed. "
  388. "If this is set, it overrides #impactSoundId. This field is useful for directly assigning custom impact sounds to materials "
  389. "without having to rely on the PlayerData sound assignment.\n\n"
  390. "@warn Be aware that materials are client-side objects. This means that the SFXTracks assigned to materials must be client-side, too.");
  391. //Deactivate these for the moment as they are not used.
  392. #if 0
  393. addField("friction", TypeF32, Offset(mFriction, Material));
  394. addField("directSoundOcclusion", TypeF32, Offset(mDirectSoundOcclusion, Material));
  395. addField("reverbSoundOcclusion", TypeF32, Offset(mReverbSoundOcclusion, Material));
  396. #endif
  397. endGroup("Behavioral");
  398. Parent::initPersistFields();
  399. }
  400. bool Material::writeField(StringTableEntry fieldname, const char* value)
  401. {
  402. // Never allow the old field names to be written.
  403. if (fieldname == StringTable->insert("baseTex") ||
  404. fieldname == StringTable->insert("detailTex") ||
  405. fieldname == StringTable->insert("overlayTex") ||
  406. fieldname == StringTable->insert("bumpTex") ||
  407. fieldname == StringTable->insert("envTex") ||
  408. fieldname == StringTable->insert("colorMultiply") ||
  409. fieldname == StringTable->insert("internalName"))
  410. return false;
  411. return Parent::writeField(fieldname, value);
  412. }
  413. bool Material::onAdd()
  414. {
  415. if (Parent::onAdd() == false)
  416. return false;
  417. mCubemapData = dynamic_cast<CubemapData*>(Sim::findObject(mCubemapName));
  418. if (mTranslucentBlendOp >= NumBlendTypes || mTranslucentBlendOp < 0)
  419. {
  420. Con::errorf("Invalid blend op in material: %s", getName());
  421. mTranslucentBlendOp = PreMul;
  422. }
  423. SimSet* matSet = MATMGR->getMaterialSet();
  424. if (matSet)
  425. matSet->addObject((SimObject*)this);
  426. // save the current script path for texture lookup later
  427. const String scriptFile = Con::getVariable("$Con::File"); // current script file - local materials.tscript
  428. String::SizeType slash = scriptFile.find('/', scriptFile.length(), String::Right);
  429. if (slash != String::NPos)
  430. mPath = scriptFile.substr(0, slash + 1);
  431. //convert any non-assets we have
  432. /*for (U32 i = 0; i < MAX_STAGES; i++)
  433. {
  434. AUTOCONVERT_IMAGEASSET_ARRAY(DiffuseMap, i);
  435. AUTOCONVERT_IMAGEASSET_ARRAY(OverlayMap, i);
  436. AUTOCONVERT_IMAGEASSET_ARRAY(LightMap, i);
  437. AUTOCONVERT_IMAGEASSET_ARRAY(ToneMap, i);
  438. AUTOCONVERT_IMAGEASSET_ARRAY(DetailMap, i);
  439. AUTOCONVERT_IMAGEASSET_ARRAY(ORMConfigMap, i);
  440. AUTOCONVERT_IMAGEASSET_ARRAY(AOMap, i);
  441. AUTOCONVERT_IMAGEASSET_ARRAY(RoughMap, i);
  442. AUTOCONVERT_IMAGEASSET_ARRAY(MetalMap, i);
  443. AUTOCONVERT_IMAGEASSET_ARRAY(GlowMap, i);
  444. AUTOCONVERT_IMAGEASSET_ARRAY(DetailNormalMap, i);
  445. }
  446. //bind any assets we have
  447. for (U32 i = 0; i < MAX_STAGES; i++)
  448. {
  449. LOAD_IMAGEASSET_ARRAY(DiffuseMap, i);
  450. LOAD_IMAGEASSET_ARRAY(OverlayMap, i);
  451. LOAD_IMAGEASSET_ARRAY(LightMap, i);
  452. LOAD_IMAGEASSET_ARRAY(ToneMap, i);
  453. LOAD_IMAGEASSET_ARRAY(DetailMap, i);
  454. LOAD_IMAGEASSET_ARRAY(ORMConfigMap, i);
  455. LOAD_IMAGEASSET_ARRAY(AOMap, i);
  456. LOAD_IMAGEASSET_ARRAY(RoughMap, i);
  457. LOAD_IMAGEASSET_ARRAY(MetalMap, i);
  458. LOAD_IMAGEASSET_ARRAY(GlowMap, i);
  459. LOAD_IMAGEASSET_ARRAY(DetailNormalMap, i);
  460. }*/
  461. inspectPostApply();
  462. _mapMaterial();
  463. return true;
  464. }
  465. void Material::onRemove()
  466. {
  467. smNormalizeCube = NULL;
  468. Parent::onRemove();
  469. }
  470. void Material::inspectPostApply()
  471. {
  472. Parent::inspectPostApply();
  473. // Reload the material instances which
  474. // use this material.
  475. if (isProperlyAdded())
  476. reload();
  477. }
  478. bool Material::isLightmapped() const
  479. {
  480. bool ret = false;
  481. for (U32 i = 0; i < MAX_STAGES; i++)
  482. ret |= mLightMapName[i] != StringTable->EmptyString() || mToneMapName[i] != StringTable->EmptyString() || mVertLit[i];
  483. return ret;
  484. }
  485. void Material::updateTimeBasedParams()
  486. {
  487. U32 lastTime = MATMGR->getLastUpdateTime();
  488. F32 dt = MATMGR->getDeltaTime();
  489. if (mLastUpdateTime != lastTime)
  490. {
  491. for (U32 i = 0; i < MAX_STAGES; i++)
  492. {
  493. mScrollOffset[i] += mScrollDir[i] * mScrollSpeed[i] * dt;
  494. mScrollOffset[i].x = mWrapF(mScrollOffset[i].x, 0.0, 1.0);
  495. mScrollOffset[i].y = mWrapF(mScrollOffset[i].y, 0.0, 1.0);
  496. mRotPos[i] = mWrapF((mRotPos[i] + (mRotSpeed[i] * dt)), 0.0, 360.0);
  497. mWavePos[i] = mWrapF((mWavePos[i] + (mWaveFreq[i] * dt)), 0.0, 1.0);
  498. }
  499. mLastUpdateTime = lastTime;
  500. }
  501. }
  502. void Material::_mapMaterial()
  503. {
  504. if (String(getName()).isEmpty())
  505. {
  506. Con::warnf("[Material::mapMaterial] - Cannot map unnamed Material");
  507. return;
  508. }
  509. // If mapTo not defined in script, try to use the base texture name instead
  510. if (mMapTo.isEmpty())
  511. {
  512. if (mDiffuseMapName[0] == StringTable->EmptyString() && mDiffuseMapAsset->isNull())
  513. return;
  514. else
  515. {
  516. // extract filename from base texture
  517. if (mDiffuseMapName[0] != StringTable->EmptyString())
  518. {
  519. U32 slashPos = String(mDiffuseMapName[0]).find('/', 0, String::Right);
  520. if (slashPos == String::NPos)
  521. // no '/' character, must be no path, just the filename
  522. mMapTo = mDiffuseMapName[0];
  523. else
  524. // use everything after the last slash
  525. mMapTo = String(mDiffuseMapName[0]).substr(slashPos + 1, strlen(mDiffuseMapName[0]) - slashPos - 1);
  526. }
  527. else if (!mDiffuseMapAsset->isNull())
  528. {
  529. mMapTo = mDiffuseMapAsset[0]->getImageFileName();
  530. }
  531. }
  532. }
  533. // add mapping
  534. MATMGR->mapMaterial(mMapTo, getName());
  535. }
  536. BaseMatInstance* Material::createMatInstance()
  537. {
  538. return new MatInstance(*this);
  539. }
  540. void Material::flush()
  541. {
  542. MATMGR->flushInstance(this);
  543. }
  544. void Material::reload()
  545. {
  546. MATMGR->reInitInstance(this);
  547. }
  548. void Material::StageData::getFeatureSet(FeatureSet* outFeatures) const
  549. {
  550. TextureTable::ConstIterator iter = mTextures.begin();
  551. for (; iter != mTextures.end(); iter++)
  552. {
  553. if (iter->value.isValid())
  554. outFeatures->addFeature(*iter->key);
  555. }
  556. }
  557. DefineEngineMethod(Material, flush, void, (), ,
  558. "Flushes all material instances that use this material.")
  559. {
  560. object->flush();
  561. }
  562. DefineEngineMethod(Material, reload, void, (), ,
  563. "Reloads all material instances that use this material.")
  564. {
  565. object->reload();
  566. }
  567. DefineEngineMethod(Material, dumpInstances, void, (), ,
  568. "Dumps a formatted list of the currently allocated material instances for this material to the console.")
  569. {
  570. MATMGR->dumpMaterialInstances(object);
  571. }
  572. DefineEngineMethod(Material, getMaterialInstances, void, (GuiTreeViewCtrl* matTree), (nullAsType< GuiTreeViewCtrl*>()),
  573. "Dumps a formatted list of the currently allocated material instances for this material to the console.")
  574. {
  575. MATMGR->getMaterialInstances(object, matTree);
  576. }
  577. DefineEngineMethod(Material, getAnimFlags, const char*, (U32 id), , "")
  578. {
  579. char* animFlags = Con::getReturnBuffer(512);
  580. if (object->mAnimFlags[id] & Material::Scroll)
  581. {
  582. if (String::compare(animFlags, "") == 0)
  583. dStrcpy(animFlags, "$Scroll", 512);
  584. }
  585. if (object->mAnimFlags[id] & Material::Rotate)
  586. {
  587. if (String::compare(animFlags, "") == 0)
  588. dStrcpy(animFlags, "$Rotate", 512);
  589. else
  590. dStrcat(animFlags, " | $Rotate", 512);
  591. }
  592. if (object->mAnimFlags[id] & Material::Wave)
  593. {
  594. if (String::compare(animFlags, "") == 0)
  595. dStrcpy(animFlags, "$Wave", 512);
  596. else
  597. dStrcat(animFlags, " | $Wave", 512);
  598. }
  599. if (object->mAnimFlags[id] & Material::Scale)
  600. {
  601. if (String::compare(animFlags, "") == 0)
  602. dStrcpy(animFlags, "$Scale", 512);
  603. else
  604. dStrcat(animFlags, " | $Scale", 512);
  605. }
  606. if (object->mAnimFlags[id] & Material::Sequence)
  607. {
  608. if (String::compare(animFlags, "") == 0)
  609. dStrcpy(animFlags, "$Sequence", 512);
  610. else
  611. dStrcat(animFlags, " | $Sequence", 512);
  612. }
  613. return animFlags;
  614. }
  615. DefineEngineMethod(Material, setAnimFlags, void, (S32 id, const char *flags), (0, ""), "setAnimFlags")
  616. {
  617. object->mAnimFlags[id] = 0;
  618. if (String(flags).find("$Scroll") != String::NPos)
  619. object->mAnimFlags[id] |= Material::Scroll;
  620. if (String(flags).find("$Rotate") != String::NPos)
  621. object->mAnimFlags[id] |= Material::Rotate;
  622. if (String(flags).find("$Wave") != String::NPos)
  623. object->mAnimFlags[id] |= Material::Wave;
  624. if (String(flags).find("$Scale") != String::NPos)
  625. object->mAnimFlags[id] |= Material::Scale;
  626. if (String(flags).find("$Sequence") != String::NPos)
  627. object->mAnimFlags[id] |= Material::Sequence;
  628. //if we're still unset, see if they tried assigning a number
  629. if (object->mAnimFlags[id] == 0)
  630. object->mAnimFlags[id] = dAtoi(flags);
  631. }
  632. DefineEngineMethod(Material, getFilename, const char*, (), , "Get filename of material")
  633. {
  634. SimObject* material = static_cast<SimObject*>(object);
  635. return material->getFilename();
  636. }
  637. DefineEngineMethod(Material, isAutoGenerated, bool, (), ,
  638. "Returns true if this Material was automatically generated by MaterialList::mapMaterials()")
  639. {
  640. return object->isAutoGenerated();
  641. }
  642. DefineEngineMethod(Material, setAutoGenerated, void, (bool isAutoGenerated), ,
  643. "setAutoGenerated(bool isAutoGenerated): Set whether or not the Material is autogenerated.")
  644. {
  645. object->setAutoGenerated(isAutoGenerated);
  646. }
  647. DefineEngineMethod(Material, getAutogeneratedFile, const char*, (), , "Get filename of autogenerated shader file")
  648. {
  649. SimObject* material = static_cast<SimObject*>(object);
  650. return material->getFilename();
  651. }
  652. // Accumulation
  653. bool Material::_setAccuEnabled(void* object, const char* index, const char* data)
  654. {
  655. Material* mat = reinterpret_cast<Material*>(object);
  656. if (index)
  657. {
  658. U32 i = dAtoui(index);
  659. mat->mAccuEnabled[i] = dAtob(data);
  660. AccumulationVolume::refreshVolumes();
  661. }
  662. return true;
  663. }
  664. //declare general get<entry>, get<entry>Asset and set<entry> methods
  665. //signatures are:
  666. //using DiffuseMap as an example
  667. //material.getDiffuseMap(%layer); //returns the raw file referenced
  668. //material.getDiffuseMapAsset(%layer); //returns the asset id
  669. //material.setDiffuseMap(%texture, %layer); //tries to set the asset and failing that attempts a flat file reference
  670. DEF_IMAGEASSET_ARRAY_BINDS(Material, DiffuseMap)
  671. DEF_IMAGEASSET_ARRAY_BINDS(Material, OverlayMap);
  672. DEF_IMAGEASSET_ARRAY_BINDS(Material, LightMap);
  673. DEF_IMAGEASSET_ARRAY_BINDS(Material, ToneMap);
  674. DEF_IMAGEASSET_ARRAY_BINDS(Material, DetailMap);
  675. DEF_IMAGEASSET_ARRAY_BINDS(Material, NormalMap);
  676. DEF_IMAGEASSET_ARRAY_BINDS(Material, ORMConfigMap);
  677. DEF_IMAGEASSET_ARRAY_BINDS(Material, RoughMap);
  678. DEF_IMAGEASSET_ARRAY_BINDS(Material, AOMap);
  679. DEF_IMAGEASSET_ARRAY_BINDS(Material, MetalMap);
  680. DEF_IMAGEASSET_ARRAY_BINDS(Material, GlowMap);
  681. DEF_IMAGEASSET_ARRAY_BINDS(Material, DetailNormalMap);