materialDefinition.cpp 34 KB

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