materialDefinition.cpp 33 KB

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