materialDefinition.cpp 32 KB

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