forest.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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 "forest/forest.h"
  24. #include "forest/forestCell.h"
  25. #include "forest/forestCollision.h"
  26. #include "forest/forestDataFile.h"
  27. #include "forest/forestWindMgr.h"
  28. #include "forest/forestWindAccumulator.h"
  29. #include "core/resourceManager.h"
  30. #include "core/volume.h"
  31. #include "T3D/gameBase/gameConnection.h"
  32. #include "console/consoleInternal.h"
  33. #include "core/stream/bitStream.h"
  34. #include "math/mathIO.h"
  35. #include "environment/sun.h"
  36. #include "scene/sceneManager.h"
  37. #include "math/mathUtils.h"
  38. #include "math/mTransform.h"
  39. #include "T3D/physics/physicsBody.h"
  40. #include "forest/editor/forestBrushElement.h"
  41. #include "console/engineAPI.h"
  42. /// For frame signal
  43. #include "gui/core/guiCanvas.h"
  44. extern bool gEditingMission;
  45. ForestCreatedSignal Forest::smCreatedSignal;
  46. ForestCreatedSignal Forest::smDestroyedSignal;
  47. bool Forest::smForceImposters = false;
  48. bool Forest::smDisableImposters = false;
  49. bool Forest::smDrawCells = false;
  50. bool Forest::smDrawBounds = false;
  51. IMPLEMENT_CO_NETOBJECT_V1(Forest);
  52. ConsoleDocClass( Forest,
  53. "@brief %Forest is a global-bounds scene object provides collision and rendering for a "
  54. "(.forest) data file.\n\n"
  55. "%Forest is designed to efficiently render a large number of static meshes: trees, rocks "
  56. "plants, etc. These cannot be moved at game-time or play animations but do support wind "
  57. "effects using vertex shader transformations guided by vertex color in the asset and "
  58. "user placed wind emitters ( or weapon explosions ).\n\n"
  59. "Script level manipulation of forest data is not possible through %Forest, it is only "
  60. "the rendering/collision. All editing is done through the world editor.\n\n"
  61. "@see TSForestItemData Defines a tree type.\n"
  62. "@see GuiForestEditorCtrl Used by the world editor to provide manipulation of forest data.\n"
  63. "@ingroup Forest"
  64. );
  65. Forest::Forest()
  66. : mDataFileName( NULL ),
  67. mReflectionLodScalar( 2.0f ),
  68. mConvexList( new Convex() ),
  69. mZoningDirty( false )
  70. {
  71. mTypeMask |= EnvironmentObjectType | StaticShapeObjectType | StaticObjectType;
  72. mNetFlags.set(Ghostable | ScopeAlways);
  73. }
  74. Forest::~Forest()
  75. {
  76. delete mConvexList;
  77. mConvexList = NULL;
  78. }
  79. void Forest::initPersistFields()
  80. {
  81. Parent::initPersistFields();
  82. addField( "dataFile", TypeFilename, Offset( mDataFileName, Forest ),
  83. "The source forest data file." );
  84. addGroup( "Lod" );
  85. addField( "lodReflectScalar", TypeF32, Offset( mReflectionLodScalar, Forest ),
  86. "Scalar applied to the farclip distance when Forest renders into a reflection." );
  87. endGroup( "Lod" );
  88. }
  89. void Forest::consoleInit()
  90. {
  91. // Some stats exposed to the console.
  92. Con::addVariable("$Forest::totalCells", TypeS32, &Forest::smTotalCells, "@internal" );
  93. Con::addVariable("$Forest::cellsRendered", TypeS32, &Forest::smCellsRendered, "@internal" );
  94. Con::addVariable("$Forest::cellItemsRendered", TypeS32, &Forest::smCellItemsRendered, "@internal" );
  95. Con::addVariable("$Forest::cellsBatched", TypeS32, &Forest::smCellsBatched, "@internal" );
  96. Con::addVariable("$Forest::cellItemsBatched", TypeS32, &Forest::smCellItemsBatched, "@internal" );
  97. Con::addVariable("$Forest::averageCellItems", TypeF32, &Forest::smAverageItemsPerCell, "@internal" );
  98. // Some debug flags.
  99. Con::addVariable("$Forest::forceImposters", TypeBool, &Forest::smForceImposters,
  100. "A debugging aid which will force all forest items to be rendered as imposters.\n"
  101. "@ingroup Forest\n" );
  102. Con::addVariable("$Forest::disableImposters", TypeBool, &Forest::smDisableImposters,
  103. "A debugging aid which will disable rendering of all imposters in the forest.\n"
  104. "@ingroup Forest\n" );
  105. Con::addVariable("$Forest::drawCells", TypeBool, &Forest::smDrawCells,
  106. "A debugging aid which renders the forest cell bounds.\n"
  107. "@ingroup Forest\n" );
  108. Con::addVariable("$Forest::drawBounds", TypeBool, &Forest::smDrawBounds,
  109. "A debugging aid which renders the forest bounds.\n"
  110. "@ingroup Forest\n" );
  111. // The canvas signal lets us know to clear the rendering stats.
  112. GuiCanvas::getGuiCanvasFrameSignal().notify( &Forest::_clearStats );
  113. }
  114. bool Forest::onAdd()
  115. {
  116. if (!Parent::onAdd())
  117. return false;
  118. const char *name = getName();
  119. if(name && name[0] && getClassRep())
  120. {
  121. Namespace *parent = getClassRep()->getNameSpace();
  122. Con::linkNamespaces(parent->mName, name);
  123. mNameSpace = Con::lookupNamespace(name);
  124. }
  125. setGlobalBounds();
  126. resetWorldBox();
  127. // TODO: Make sure this calls the script "onAdd" which will
  128. // populate the object with forest entries before creation.
  129. addToScene();
  130. // If we don't have a file name and the editor is
  131. // enabled then create an empty forest data file.
  132. if ( isServerObject() && ( !mDataFileName || !mDataFileName[0] ) )
  133. createNewFile();
  134. else
  135. {
  136. // Try to load the forest file.
  137. mData = ResourceManager::get().load( mDataFileName );
  138. if ( !mData )
  139. {
  140. if ( isClientObject() )
  141. NetConnection::setLastError( "You are missing a file needed to play this mission: %s", mDataFileName );
  142. return false;
  143. }
  144. }
  145. updateCollision();
  146. smCreatedSignal.trigger( this );
  147. if ( isClientObject() )
  148. {
  149. mZoningDirty = true;
  150. SceneZoneSpaceManager::getZoningChangedSignal().notify( this, &Forest::_onZoningChanged );
  151. ForestWindMgr::getAdvanceSignal().notify( this, &Forest::getLocalWindTrees );
  152. }
  153. return true;
  154. }
  155. void Forest::onRemove()
  156. {
  157. Parent::onRemove();
  158. smDestroyedSignal.trigger( this );
  159. if ( mData )
  160. mData->clearPhysicsRep( this );
  161. mData = NULL;
  162. if ( isClientObject() )
  163. {
  164. SceneZoneSpaceManager::getZoningChangedSignal().remove( this, &Forest::_onZoningChanged );
  165. ForestWindMgr::getAdvanceSignal().remove( this, &Forest::getLocalWindTrees );
  166. }
  167. mConvexList->nukeList();
  168. removeFromScene();
  169. }
  170. U32 Forest::packUpdate( NetConnection *connection, U32 mask, BitStream *stream )
  171. {
  172. U32 retMask = Parent::packUpdate( connection, mask, stream );
  173. if ( stream->writeFlag( mask & MediaMask ) )
  174. stream->writeString( mDataFileName );
  175. if ( stream->writeFlag( mask & LodMask ) )
  176. {
  177. stream->write( mReflectionLodScalar );
  178. }
  179. return retMask;
  180. }
  181. void Forest::unpackUpdate(NetConnection *connection, BitStream *stream)
  182. {
  183. Parent::unpackUpdate(connection,stream);
  184. if ( stream->readFlag() )
  185. {
  186. mDataFileName = stream->readSTString();
  187. }
  188. if ( stream->readFlag() ) // LodMask
  189. {
  190. stream->read( &mReflectionLodScalar );
  191. }
  192. }
  193. void Forest::inspectPostApply()
  194. {
  195. Parent::inspectPostApply();
  196. // Update the client... note that this
  197. // doesn't cause a regen of the forest.
  198. setMaskBits( LodMask );
  199. }
  200. void Forest::setTransform( const MatrixF &mat )
  201. {
  202. // Note: We do not use the position of the forest at all.
  203. Parent::setTransform( mat );
  204. }
  205. void Forest::_onZoningChanged( SceneZoneSpaceManager *zoneManager )
  206. {
  207. if ( mData == NULL || zoneManager != getSceneManager()->getZoneManager() )
  208. return;
  209. mZoningDirty = true;
  210. }
  211. void Forest::getLocalWindTrees( const Point3F &camPos, F32 radius, Vector<TreePlacementInfo> *placementInfo )
  212. {
  213. PROFILE_SCOPE( Forest_getLocalWindTrees );
  214. Vector<ForestItem> items;
  215. items.reserve( placementInfo->capacity() );
  216. mData->getItems( camPos, radius, &items );
  217. TreePlacementInfo treeInfo;
  218. dMemset( &treeInfo, 0, sizeof ( TreePlacementInfo ) );
  219. // Reserve some space in the output.
  220. placementInfo->reserve( items.size() );
  221. // Build an info struct for each returned item.
  222. Vector<ForestItem>::const_iterator iter = items.begin();
  223. for ( ; iter != items.end(); iter++ )
  224. {
  225. // Skip over any zero wind elements here and
  226. // just keep them out of the final list.
  227. treeInfo.dataBlock = iter->getData();
  228. if ( treeInfo.dataBlock->mWindScale < 0.001f )
  229. continue;
  230. treeInfo.pos = iter->getPosition();
  231. treeInfo.scale = iter->getScale();
  232. treeInfo.itemKey = iter->getKey();
  233. placementInfo->push_back( treeInfo );
  234. }
  235. }
  236. void Forest::applyRadialImpulse( const Point3F &origin, F32 radius, F32 magnitude )
  237. {
  238. if ( isServerObject() )
  239. return;
  240. // Find all the trees in the radius
  241. // then get their accumulators and
  242. // push our impulse into them.
  243. VectorF impulse( 0, 0, 0 );
  244. ForestWindAccumulator *accumulator = NULL;
  245. Vector<TreePlacementInfo> trees;
  246. getLocalWindTrees( origin, radius, &trees );
  247. for ( U32 i = 0; i < trees.size(); i++ )
  248. {
  249. const TreePlacementInfo &treeInfo = trees[i];
  250. accumulator = WINDMGR->getLocalWind( treeInfo.itemKey );
  251. if ( !accumulator )
  252. continue;
  253. impulse = treeInfo.pos - origin;
  254. impulse.normalize();
  255. impulse *= magnitude;
  256. accumulator->applyImpulse( impulse );
  257. }
  258. }
  259. void Forest::createNewFile()
  260. {
  261. // Release the current file if we have one.
  262. mData = NULL;
  263. // We need to construct a default file name
  264. String missionName( Con::getVariable( "$Client::MissionFile" ) );
  265. String levelDirectory( Con::getVariable( "$pref::Directories::Level" ) );
  266. if ( levelDirectory.isEmpty() )
  267. {
  268. levelDirectory = "levels";
  269. }
  270. missionName.replace( "tools/levels", levelDirectory );
  271. missionName = Platform::makeRelativePathName(missionName, Platform::getMainDotCsDir());
  272. Torque::Path basePath( missionName );
  273. String fileName = Torque::FS::MakeUniquePath( basePath.getPath(), basePath.getFileName(), "forest" );
  274. mDataFileName = StringTable->insert( fileName );
  275. ForestData *file = new ForestData;
  276. file->write( mDataFileName );
  277. delete file;
  278. mData = ResourceManager::get().load( mDataFileName );
  279. mZoningDirty = true;
  280. }
  281. void Forest::saveDataFile( const char *path )
  282. {
  283. if ( path && !String::isEmpty(path))
  284. mDataFileName = StringTable->insert( path );
  285. if ( mData )
  286. mData->write( mDataFileName );
  287. }
  288. DefineConsoleMethod( Forest, saveDataFile, void, (const char * path), (""), "saveDataFile( [path] )" )
  289. {
  290. object->saveDataFile( path );
  291. }
  292. DefineConsoleMethod(Forest, isDirty, bool, (), , "()")
  293. {
  294. return object->getData() && object->getData()->isDirty();
  295. }
  296. DefineConsoleMethod(Forest, regenCells, void, (), , "()")
  297. {
  298. object->getData()->regenCells();
  299. }
  300. DefineConsoleMethod(Forest, clear, void, (), , "()" )
  301. {
  302. object->clear();
  303. }