materialDefinition.cpp 35 KB

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