terrData.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437
  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. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  23. // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
  24. // Copyright (C) 2015 Faust Logic, Inc.
  25. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  26. #include "platform/platform.h"
  27. #include "terrain/terrData.h"
  28. #include "terrain/terrCollision.h"
  29. #include "terrain/terrCell.h"
  30. #include "terrain/terrRender.h"
  31. #include "terrain/terrMaterial.h"
  32. #include "terrain/terrCellMaterial.h"
  33. #include "gui/worldEditor/terrainEditor.h"
  34. #include "math/mathIO.h"
  35. #include "core/stream/fileStream.h"
  36. #include "core/stream/bitStream.h"
  37. #include "console/consoleTypes.h"
  38. #include "sim/netConnection.h"
  39. #include "core/util/safeDelete.h"
  40. #include "T3D/objectTypes.h"
  41. #include "renderInstance/renderPassManager.h"
  42. #include "scene/sceneRenderState.h"
  43. #include "materials/materialManager.h"
  44. #include "materials/baseMatInstance.h"
  45. #include "gfx/gfxTextureManager.h"
  46. #include "gfx/gfxCardProfile.h"
  47. #include "core/resourceManager.h"
  48. #include "T3D/physics/physicsPlugin.h"
  49. #include "T3D/physics/physicsBody.h"
  50. #include "T3D/physics/physicsCollision.h"
  51. #include "console/engineAPI.h"
  52. #include "console/engineAPI.h"
  53. using namespace Torque;
  54. IMPLEMENT_CO_NETOBJECT_V1(TerrainBlock);
  55. ConsoleDocClass( TerrainBlock,
  56. "@brief Represent a terrain object in a Torque 3D level\n\n"
  57. "@tsexample\n"
  58. "new TerrainBlock(theTerrain)\n"
  59. "{\n"
  60. " terrainFile = \"art/terrains/Deathball Desert_0.ter\";\n"
  61. " squareSize = \"2\";\n"
  62. " tile = \"0\";\n"
  63. " baseTexSize = \"1024\";\n"
  64. " screenError = \"16\";\n"
  65. " position = \"-1024 -1024 179.978\";\n"
  66. " rotation = \"1 0 0 0\";\n"
  67. " scale = \"1 1 1\";\n"
  68. " isRenderEnabled = \"true\";\n"
  69. " canSaveDynamicFields = \"1\";\n"
  70. "};\n"
  71. "@endtsexample\n\n"
  72. "@see TerrainMaterial\n\n"
  73. "@ingroup Terrain\n"
  74. );
  75. Signal<void(U32,TerrainBlock*,const Point2I& ,const Point2I&)> TerrainBlock::smUpdateSignal;
  76. F32 TerrainBlock::smLODScale = 1.0f;
  77. F32 TerrainBlock::smDetailScale = 1.0f;
  78. //RBP - Global function declared in Terrdata.h
  79. TerrainBlock* getTerrainUnderWorldPoint(const Point3F & wPos)
  80. {
  81. // Cast a ray straight down from the world position and see which
  82. // Terrain is the closest to our starting point
  83. Point3F startPnt = wPos;
  84. Point3F endPnt = wPos + Point3F(0.0f, 0.0f, -10000.0f);
  85. S32 blockIndex = -1;
  86. F32 nearT = 1.0f;
  87. SimpleQueryList queryList;
  88. gServerContainer.findObjects( TerrainObjectType, SimpleQueryList::insertionCallback, &queryList);
  89. for (U32 i = 0; i < queryList.mList.size(); i++)
  90. {
  91. Point3F tStartPnt, tEndPnt;
  92. TerrainBlock* terrBlock = dynamic_cast<TerrainBlock*>(queryList.mList[i]);
  93. terrBlock->getWorldTransform().mulP(startPnt, &tStartPnt);
  94. terrBlock->getWorldTransform().mulP(endPnt, &tEndPnt);
  95. RayInfo ri;
  96. if (terrBlock->castRayI(tStartPnt, tEndPnt, &ri, true))
  97. {
  98. if (ri.t < nearT)
  99. {
  100. blockIndex = i;
  101. nearT = ri.t;
  102. }
  103. }
  104. }
  105. if (blockIndex > -1)
  106. return (TerrainBlock*)(queryList.mList[blockIndex]);
  107. return NULL;
  108. }
  109. ConsoleDocFragment _getTerrainUnderWorldPoint1(
  110. "@brief Gets the terrain block that is located under the given world point\n\n"
  111. "@param position The world space coordinate you wish to query at. Formatted as (\"x y z\")\n\n"
  112. "@return Returns the ID of the requested terrain block (0 if not found).\n\n"
  113. "@ingroup Terrain",
  114. NULL,
  115. "bool getTerrainUnderWorldPoint( Point3F position );"
  116. );
  117. ConsoleDocFragment _getTerrainUnderWorldPoint2(
  118. "@brief Takes a world point and find the \"highest\" terrain underneath it\n\n"
  119. "@param x The X coordinate in world space\n"
  120. "@param y The Y coordinate in world space\n\n"
  121. "@param z The Z coordinate in world space\n\n"
  122. "@return Returns the ID of the requested terrain block (0 if not found).\n\n"
  123. "@ingroup Terrain",
  124. NULL,
  125. "bool getTerrainUnderWorldPoint( F32 x, F32 y, F32 z);"
  126. );
  127. DefineEngineFunction( getTerrainUnderWorldPoint, S32, (const char* ptOrX, const char* y, const char* z), ("", ""),
  128. "(Point3F x/y/z) Gets the terrain block that is located under the given world point.\n"
  129. "@param x/y/z The world coordinates (floating point values) you wish to query at. "
  130. "These can be formatted as either a string (\"x y z\") or separately as (x, y, z)\n"
  131. "@return Returns the ID of the requested terrain block (0 if not found).\n\n"
  132. "@hide")
  133. {
  134. Point3F pos;
  135. if(!String::isEmpty(ptOrX) && String::isEmpty(y) && String::isEmpty(z))
  136. dSscanf(ptOrX, "%f %f %f", &pos.x, &pos.y, &pos.z);
  137. else if(!String::isEmpty(ptOrX) && !String::isEmpty(y) && !String::isEmpty(z))
  138. {
  139. pos.x = dAtof(ptOrX);
  140. pos.y = dAtof(y);
  141. pos.z = dAtof(z);
  142. }
  143. TerrainBlock* terrain = getTerrainUnderWorldPoint(pos);
  144. if(terrain != NULL)
  145. {
  146. return terrain->getId();
  147. }
  148. return 0;
  149. }
  150. typedef TerrainBlock::BaseTexFormat baseTexFormat;
  151. DefineEnumType(baseTexFormat);
  152. ImplementEnumType(baseTexFormat,
  153. "Description\n"
  154. "@ingroup ?\n\n")
  155. { TerrainBlock::NONE, "NONE", "No cached terrain.\n" },
  156. { TerrainBlock::DDS, "DDS", "Cache the terrain in a DDS format.\n" },
  157. { TerrainBlock::PNG, "PNG", "Cache the terrain in a PNG format.\n" },
  158. EndImplementEnumType;
  159. TerrainBlock::TerrainBlock()
  160. : mLightMap( NULL ),
  161. mLightMapSize( 256 ),
  162. mCRC( 0 ),
  163. mMaxDetailDistance( 0.0f ),
  164. mBaseTexScaleConst( NULL ),
  165. mBaseTexIdConst( NULL ),
  166. mDetailsDirty( false ),
  167. mLayerTexDirty( false ),
  168. mBaseTexSize( 1024 ),
  169. mBaseTexFormat( TerrainBlock::DDS ),
  170. mCell( NULL ),
  171. mBaseMaterial( NULL ),
  172. mDefaultMatInst( NULL ),
  173. mSquareSize( 1.0f ),
  174. mPhysicsRep( NULL ),
  175. mScreenError( 16 ),
  176. mCastShadows( true ),
  177. mZoningDirty( false )
  178. {
  179. mTypeMask = TerrainObjectType | StaticObjectType | StaticShapeObjectType;
  180. mNetFlags.set(Ghostable | ScopeAlways);
  181. mIgnoreZodiacs = false;
  182. zode_primBuffer = 0;
  183. }
  184. extern Convex sTerrainConvexList;
  185. TerrainBlock::~TerrainBlock()
  186. {
  187. // Kill collision
  188. sTerrainConvexList.nukeList();
  189. SAFE_DELETE(mLightMap);
  190. mLightMapTex = NULL;
  191. #ifdef TORQUE_TOOLS
  192. TerrainEditor* editor = dynamic_cast<TerrainEditor*>(Sim::findObject("ETerrainEditor"));
  193. if (editor)
  194. editor->detachTerrain(this);
  195. #endif
  196. deleteZodiacPrimitiveBuffer();
  197. }
  198. void TerrainBlock::_onTextureEvent( GFXTexCallbackCode code )
  199. {
  200. if ( code == GFXZombify )
  201. {
  202. if ( mBaseTex.isValid() &&
  203. mBaseTex->isRenderTarget() )
  204. mBaseTex = NULL;
  205. mLayerTex = NULL;
  206. mLightMapTex = NULL;
  207. }
  208. }
  209. bool TerrainBlock::_setSquareSize( void *obj, const char *index, const char *data )
  210. {
  211. TerrainBlock *terrain = static_cast<TerrainBlock*>( obj );
  212. F32 newSqaureSize = dAtof( data );
  213. if ( !mIsEqual( terrain->mSquareSize, newSqaureSize ) )
  214. {
  215. terrain->mSquareSize = newSqaureSize;
  216. if ( terrain->isServerObject() && terrain->isProperlyAdded() )
  217. terrain->_updateBounds();
  218. terrain->setMaskBits( HeightMapChangeMask | SizeMask );
  219. }
  220. return false;
  221. }
  222. bool TerrainBlock::_setBaseTexSize( void *obj, const char *index, const char *data )
  223. {
  224. TerrainBlock *terrain = static_cast<TerrainBlock*>( obj );
  225. // NOTE: We're limiting the base texture size to
  226. // 2048 as anything greater in size becomes too
  227. // large to generate for many cards.
  228. //
  229. // If you want to remove this limit feel free, but
  230. // prepare for problems if you don't ship the baked
  231. // base texture with your installer.
  232. //
  233. S32 texSize = mClamp( dAtoi( data ), 0, 2048 );
  234. if ( terrain->mBaseTexSize != texSize )
  235. {
  236. terrain->mBaseTexSize = texSize;
  237. terrain->setMaskBits( MaterialMask );
  238. }
  239. return false;
  240. }
  241. bool TerrainBlock::_setBaseTexFormat(void *obj, const char *index, const char *data)
  242. {
  243. TerrainBlock *terrain = static_cast<TerrainBlock*>(obj);
  244. EngineEnumTable eTable = _baseTexFormat::_sEnumTable;
  245. for (U8 i = 0; i < eTable.getNumValues(); i++)
  246. {
  247. if (strcasecmp(eTable[i].mName, data) == 0)
  248. {
  249. terrain->mBaseTexFormat = (BaseTexFormat)eTable[i].mInt;
  250. terrain->_updateMaterials();
  251. if (terrain->isServerObject()) return false;
  252. terrain->_updateLayerTexture();
  253. // If the cached base texture is older that the terrain file or
  254. // it doesn't exist then generate and cache it.
  255. String baseCachePath = terrain->_getBaseTexCacheFileName();
  256. if (Platform::compareModifiedTimes(baseCachePath, terrain->mTerrFileName) < 0)
  257. terrain->_updateBaseTexture(true);
  258. break;
  259. }
  260. }
  261. return false;
  262. }
  263. bool TerrainBlock::_setLightMapSize( void *obj, const char *index, const char *data )
  264. {
  265. TerrainBlock *terrain = static_cast<TerrainBlock*>(obj);
  266. // Handle inspector value decrements correctly
  267. U32 mapSize = dAtoi( data );
  268. if ( mapSize == terrain->mLightMapSize-1 )
  269. mapSize = terrain->mLightMapSize/2;
  270. // Limit the lightmap size, and ensure it is a power of 2
  271. const U32 maxTextureSize = GFX->getCardProfiler()->queryProfile( "maxTextureSize", 1024 );
  272. mapSize = mClamp( getNextPow2( mapSize ), 0, maxTextureSize );
  273. if ( terrain->mLightMapSize != mapSize )
  274. {
  275. terrain->mLightMapSize = mapSize;
  276. terrain->setMaskBits( MaterialMask );
  277. }
  278. return false;
  279. }
  280. bool TerrainBlock::setFile( const FileName &terrFileName )
  281. {
  282. if ( terrFileName == mTerrFileName )
  283. return mFile != NULL;
  284. Resource<TerrainFile> file = ResourceManager::get().load( terrFileName );
  285. if( !file )
  286. return false;
  287. setFile( file );
  288. setMaskBits( FileMask | HeightMapChangeMask );
  289. return true;
  290. }
  291. void TerrainBlock::setFile(const Resource<TerrainFile>& terr)
  292. {
  293. mFile = terr;
  294. mTerrFileName = terr.getPath();
  295. }
  296. bool TerrainBlock::save(const char *filename)
  297. {
  298. return mFile->save(filename);
  299. }
  300. bool TerrainBlock::_setTerrainFile( void *obj, const char *index, const char *data )
  301. {
  302. static_cast<TerrainBlock*>( obj )->setFile( FileName( data ) );
  303. return false;
  304. }
  305. void TerrainBlock::_updateBounds()
  306. {
  307. if ( !mFile )
  308. return; // quick fix to stop crashing when deleting terrainblocks
  309. // Setup our object space bounds.
  310. mBounds.minExtents.set( 0.0f, 0.0f, 0.0f );
  311. mBounds.maxExtents.set( getWorldBlockSize(), getWorldBlockSize(), 0.0f );
  312. getMinMaxHeight( &mBounds.minExtents.z, &mBounds.maxExtents.z );
  313. // Set our mObjBox to be equal to mBounds
  314. if ( mObjBox.maxExtents != mBounds.maxExtents ||
  315. mObjBox.minExtents != mBounds.minExtents )
  316. {
  317. mObjBox = mBounds;
  318. resetWorldBox();
  319. }
  320. }
  321. void TerrainBlock::_onZoningChanged( SceneZoneSpaceManager *zoneManager )
  322. {
  323. if ( mCell == NULL || zoneManager != getSceneManager()->getZoneManager() )
  324. return;
  325. mZoningDirty = true;
  326. }
  327. void TerrainBlock::setHeight( const Point2I &pos, F32 height )
  328. {
  329. U16 ht = floatToFixed( height );
  330. mFile->setHeight( pos.x, pos.y, ht );
  331. // Note: We do not update the grid here as this could
  332. // be called several times in a loop. We depend on the
  333. // caller doing a grid update when he is done.
  334. }
  335. F32 TerrainBlock::getHeight( const Point2I &pos )
  336. {
  337. U16 ht = mFile->getHeight( pos.x, pos.y );
  338. return fixedToFloat( ht );
  339. }
  340. void TerrainBlock::updateGridMaterials( const Point2I &minPt, const Point2I &maxPt )
  341. {
  342. if ( mCell )
  343. {
  344. // Tell the terrain cell that something changed.
  345. const RectI gridRect( minPt, maxPt - minPt );
  346. mCell->updateGrid( gridRect, true );
  347. }
  348. // We mark us as dirty... it will be updated
  349. // before the next time we render the terrain.
  350. mLayerTexDirty = true;
  351. // Signal anyone that cares that the opacity was changed.
  352. smUpdateSignal.trigger( LayersUpdate, this, minPt, maxPt );
  353. }
  354. Point2I TerrainBlock::getGridPos( const Point3F &worldPos ) const
  355. {
  356. Point3F terrainPos = worldPos;
  357. getWorldTransform().mulP( terrainPos );
  358. F32 squareSize = ( F32 ) getSquareSize();
  359. F32 halfSquareSize = squareSize / 2.0;
  360. F32 x = ( terrainPos.x + halfSquareSize ) / squareSize;
  361. F32 y = ( terrainPos.y + halfSquareSize ) / squareSize;
  362. Point2I gridPos( ( S32 ) mFloor( x ), ( S32 ) mFloor( y ) );
  363. return gridPos;
  364. }
  365. void TerrainBlock::updateGrid( const Point2I &minPt, const Point2I &maxPt, bool updateClient )
  366. {
  367. // On the client we just signal everyone that the height
  368. // map has changed... the server does the actual changes.
  369. if ( isClientObject() )
  370. {
  371. PROFILE_SCOPE( TerrainBlock_updateGrid_Client );
  372. // This depends on the client getting this call 'after' the server.
  373. // Which is currently the case.
  374. _updateBounds();
  375. mZoningDirty = true;
  376. smUpdateSignal.trigger( HeightmapUpdate, this, minPt, maxPt );
  377. // Tell the terrain cell that the height changed.
  378. const RectI gridRect( minPt, maxPt - minPt );
  379. mCell->updateGrid( gridRect );
  380. // Rebuild the physics representation.
  381. if ( mPhysicsRep )
  382. {
  383. // Delay the update by a few milliseconds so
  384. // that we're not rebuilding during an active
  385. // editing operation.
  386. mPhysicsRep->queueCallback( 500, Delegate<void()>( this, &TerrainBlock::_updatePhysics ) );
  387. }
  388. return;
  389. }
  390. // Now on the server we rebuild the
  391. // affected area of the grid map.
  392. mFile->updateGrid( minPt, maxPt );
  393. // Fix up the bounds.
  394. _updateBounds();
  395. // Rebuild the physics representation.
  396. if ( mPhysicsRep )
  397. {
  398. // Delay the update by a few milliseconds so
  399. // that we're not rebuilding during an active
  400. // editing operation.
  401. mPhysicsRep->queueCallback( 500, Delegate<void()>( this, &TerrainBlock::_updatePhysics ) );
  402. }
  403. // Signal again here for any server side observers.
  404. smUpdateSignal.trigger( HeightmapUpdate, this, minPt, maxPt );
  405. // If this is a server object and the client update
  406. // was requested then try to use the local connection
  407. // pointer to do it.
  408. if ( updateClient && getClientObject() )
  409. ((TerrainBlock*)getClientObject())->updateGrid( minPt, maxPt, false );
  410. }
  411. bool TerrainBlock::getHeight( const Point2F &pos, F32 *height ) const
  412. {
  413. PROFILE_SCOPE( TerrainBlock_getHeight );
  414. F32 invSquareSize = 1.0f / mSquareSize;
  415. F32 xp = pos.x * invSquareSize;
  416. F32 yp = pos.y * invSquareSize;
  417. S32 x = S32(xp);
  418. S32 y = S32(yp);
  419. xp -= (F32)x;
  420. yp -= (F32)y;
  421. const U32 blockMask = mFile->mSize - 1;
  422. if ( x & ~blockMask || y & ~blockMask )
  423. return false;
  424. x &= blockMask;
  425. y &= blockMask;
  426. const TerrainSquare *sq = mFile->findSquare( 0, x, y );
  427. if ( sq->flags & TerrainSquare::Empty )
  428. return false;
  429. F32 zBottomLeft = fixedToFloat( mFile->getHeight( x, y ) );
  430. F32 zBottomRight = fixedToFloat( mFile->getHeight( x + 1, y ) );
  431. F32 zTopLeft = fixedToFloat( mFile->getHeight( x, y + 1 ) );
  432. F32 zTopRight = fixedToFloat( mFile->getHeight( x + 1, y + 1 ) );
  433. if ( sq->flags & TerrainSquare::Split45 )
  434. {
  435. if (xp>yp)
  436. // bottom half
  437. *height = zBottomLeft + xp * (zBottomRight-zBottomLeft) + yp * (zTopRight-zBottomRight);
  438. else
  439. // top half
  440. *height = zBottomLeft + xp * (zTopRight-zTopLeft) + yp * (zTopLeft-zBottomLeft);
  441. }
  442. else
  443. {
  444. if (1.0f-xp>yp)
  445. // bottom half
  446. *height = zBottomRight + (1.0f-xp) * (zBottomLeft-zBottomRight) + yp * (zTopLeft-zBottomLeft);
  447. else
  448. // top half
  449. *height = zBottomRight + (1.0f-xp) * (zTopLeft-zTopRight) + yp * (zTopRight-zBottomRight);
  450. }
  451. return true;
  452. }
  453. bool TerrainBlock::getNormal( const Point2F &pos, Point3F *normal, bool normalize, bool skipEmpty ) const
  454. {
  455. PROFILE_SCOPE( TerrainBlock_getNormal );
  456. F32 invSquareSize = 1.0f / mSquareSize;
  457. F32 xp = pos.x * invSquareSize;
  458. F32 yp = pos.y * invSquareSize;
  459. S32 x = S32(xp);
  460. S32 y = S32(yp);
  461. xp -= (F32)x;
  462. yp -= (F32)y;
  463. const U32 blockMask = mFile->mSize - 1;
  464. if ( x & ~blockMask || y & ~blockMask )
  465. return false;
  466. x &= blockMask;
  467. y &= blockMask;
  468. const TerrainSquare *sq = mFile->findSquare( 0, x, y );
  469. if ( skipEmpty && sq->flags & TerrainSquare::Empty )
  470. return false;
  471. F32 zBottomLeft = fixedToFloat( mFile->getHeight( x, y ) );
  472. F32 zBottomRight = fixedToFloat( mFile->getHeight( x + 1, y ) );
  473. F32 zTopLeft = fixedToFloat( mFile->getHeight( x, y + 1 ) );
  474. F32 zTopRight = fixedToFloat( mFile->getHeight( x + 1, y + 1 ) );
  475. if ( sq->flags & TerrainSquare::Split45 )
  476. {
  477. if (xp>yp)
  478. // bottom half
  479. normal->set(zBottomLeft-zBottomRight, zBottomRight-zTopRight, mSquareSize);
  480. else
  481. // top half
  482. normal->set(zTopLeft-zTopRight, zBottomLeft-zTopLeft, mSquareSize);
  483. }
  484. else
  485. {
  486. if (1.0f-xp>yp)
  487. // bottom half
  488. normal->set(zBottomLeft-zBottomRight, zBottomLeft-zTopLeft, mSquareSize);
  489. else
  490. // top half
  491. normal->set(zTopLeft-zTopRight, zBottomRight-zTopRight, mSquareSize);
  492. }
  493. if (normalize)
  494. normal->normalize();
  495. return true;
  496. }
  497. bool TerrainBlock::getSmoothNormal( const Point2F &pos,
  498. Point3F *normal,
  499. bool normalize,
  500. bool skipEmpty ) const
  501. {
  502. PROFILE_SCOPE( TerrainBlock_getSmoothNormal );
  503. F32 invSquareSize = 1.0f / mSquareSize;
  504. F32 xp = pos.x * invSquareSize;
  505. F32 yp = pos.y * invSquareSize;
  506. S32 x = S32(xp);
  507. S32 y = S32(yp);
  508. const U32 blockMask = mFile->mSize - 1;
  509. if ( x & ~blockMask || y & ~blockMask )
  510. return false;
  511. x &= blockMask;
  512. y &= blockMask;
  513. const TerrainSquare *sq = mFile->findSquare( 0, x, y );
  514. if ( skipEmpty && sq->flags & TerrainSquare::Empty )
  515. return false;
  516. F32 h1 = fixedToFloat( mFile->getHeight( x + 1, y ) );
  517. F32 h2 = fixedToFloat( mFile->getHeight( x, y + 1 ) );
  518. F32 h3 = fixedToFloat( mFile->getHeight( x - 1, y ) );
  519. F32 h4 = fixedToFloat( mFile->getHeight( x, y - 1 ) );
  520. normal->set( h3 - h1, h4 - h2, mSquareSize * 2.0f );
  521. if ( normalize )
  522. normal->normalize();
  523. return true;
  524. }
  525. bool TerrainBlock::getNormalAndHeight( const Point2F &pos, Point3F *normal, F32 *height, bool normalize ) const
  526. {
  527. PROFILE_SCOPE( TerrainBlock_getNormalAndHeight );
  528. F32 invSquareSize = 1.0f / mSquareSize;
  529. F32 xp = pos.x * invSquareSize;
  530. F32 yp = pos.y * invSquareSize;
  531. S32 x = S32(xp);
  532. S32 y = S32(yp);
  533. xp -= (F32)x;
  534. yp -= (F32)y;
  535. const U32 blockMask = mFile->mSize - 1;
  536. if ( x & ~blockMask || y & ~blockMask )
  537. return false;
  538. x &= blockMask;
  539. y &= blockMask;
  540. const TerrainSquare *sq = mFile->findSquare( 0, x, y );
  541. if ( sq->flags & TerrainSquare::Empty )
  542. return false;
  543. F32 zBottomLeft = fixedToFloat( mFile->getHeight(x, y) );
  544. F32 zBottomRight = fixedToFloat( mFile->getHeight(x + 1, y) );
  545. F32 zTopLeft = fixedToFloat( mFile->getHeight(x, y + 1) );
  546. F32 zTopRight = fixedToFloat( mFile->getHeight(x + 1, y + 1) );
  547. if ( sq->flags & TerrainSquare::Split45 )
  548. {
  549. if (xp>yp)
  550. {
  551. // bottom half
  552. normal->set(zBottomLeft-zBottomRight, zBottomRight-zTopRight, mSquareSize);
  553. *height = zBottomLeft + xp * (zBottomRight-zBottomLeft) + yp * (zTopRight-zBottomRight);
  554. }
  555. else
  556. {
  557. // top half
  558. normal->set(zTopLeft-zTopRight, zBottomLeft-zTopLeft, mSquareSize);
  559. *height = zBottomLeft + xp * (zTopRight-zTopLeft) + yp * (zTopLeft-zBottomLeft);
  560. }
  561. }
  562. else
  563. {
  564. if (1.0f-xp>yp)
  565. {
  566. // bottom half
  567. normal->set(zBottomLeft-zBottomRight, zBottomLeft-zTopLeft, mSquareSize);
  568. *height = zBottomRight + (1.0f-xp) * (zBottomLeft-zBottomRight) + yp * (zTopLeft-zBottomLeft);
  569. }
  570. else
  571. {
  572. // top half
  573. normal->set(zTopLeft-zTopRight, zBottomRight-zTopRight, mSquareSize);
  574. *height = zBottomRight + (1.0f-xp) * (zTopLeft-zTopRight) + yp * (zTopRight-zBottomRight);
  575. }
  576. }
  577. if (normalize)
  578. normal->normalize();
  579. return true;
  580. }
  581. bool TerrainBlock::getNormalHeightMaterial( const Point2F &pos,
  582. Point3F *normal,
  583. F32 *height,
  584. StringTableEntry &matName ) const
  585. {
  586. PROFILE_SCOPE( TerrainBlock_getNormalHeightMaterial );
  587. F32 invSquareSize = 1.0f / mSquareSize;
  588. F32 xp = pos.x * invSquareSize;
  589. F32 yp = pos.y * invSquareSize;
  590. S32 x = S32(xp);
  591. S32 y = S32(yp);
  592. S32 xm = S32(mFloor( xp + 0.5f ));
  593. S32 ym = S32(mFloor( yp + 0.5f ));
  594. xp -= (F32)x;
  595. yp -= (F32)y;
  596. const U32 blockMask = mFile->mSize - 1;
  597. if ( x & ~blockMask || y & ~blockMask )
  598. return false;
  599. x &= blockMask;
  600. y &= blockMask;
  601. const TerrainSquare *sq = mFile->findSquare( 0, x, y );
  602. if ( sq->flags & TerrainSquare::Empty )
  603. return false;
  604. F32 zBottomLeft = fixedToFloat( mFile->getHeight(x, y) );
  605. F32 zBottomRight = fixedToFloat( mFile->getHeight(x + 1, y) );
  606. F32 zTopLeft = fixedToFloat( mFile->getHeight(x, y + 1) );
  607. F32 zTopRight = fixedToFloat( mFile->getHeight(x + 1, y + 1) );
  608. matName = mFile->getMaterialName( xm, ym );
  609. if ( sq->flags & TerrainSquare::Split45 )
  610. {
  611. if (xp>yp)
  612. {
  613. // bottom half
  614. normal->set(zBottomLeft-zBottomRight, zBottomRight-zTopRight, mSquareSize);
  615. *height = zBottomLeft + xp * (zBottomRight-zBottomLeft) + yp * (zTopRight-zBottomRight);
  616. }
  617. else
  618. {
  619. // top half
  620. normal->set(zTopLeft-zTopRight, zBottomLeft-zTopLeft, mSquareSize);
  621. *height = zBottomLeft + xp * (zTopRight-zTopLeft) + yp * (zTopLeft-zBottomLeft);
  622. }
  623. }
  624. else
  625. {
  626. if (1.0f-xp>yp)
  627. {
  628. // bottom half
  629. normal->set(zBottomLeft-zBottomRight, zBottomLeft-zTopLeft, mSquareSize);
  630. *height = zBottomRight + (1.0f-xp) * (zBottomLeft-zBottomRight) + yp * (zTopLeft-zBottomLeft);
  631. }
  632. else
  633. {
  634. // top half
  635. normal->set(zTopLeft-zTopRight, zBottomRight-zTopRight, mSquareSize);
  636. *height = zBottomRight + (1.0f-xp) * (zTopLeft-zTopRight) + yp * (zTopRight-zBottomRight);
  637. }
  638. }
  639. normal->normalize();
  640. return true;
  641. }
  642. U32 TerrainBlock::getMaterialCount() const
  643. {
  644. return mFile->mMaterials.size();
  645. }
  646. void TerrainBlock::addMaterial( const String &name, U32 insertAt )
  647. {
  648. TerrainMaterial *mat = TerrainMaterial::findOrCreate( name );
  649. if ( insertAt == -1 )
  650. {
  651. mFile->mMaterials.push_back( mat );
  652. mFile->_initMaterialInstMapping();
  653. }
  654. else
  655. {
  656. // TODO: Insert and reindex!
  657. }
  658. mDetailsDirty = true;
  659. mLayerTexDirty = true;
  660. }
  661. void TerrainBlock::removeMaterial( U32 index )
  662. {
  663. // Cannot delete if only one layer.
  664. if ( mFile->mMaterials.size() == 1 )
  665. return;
  666. mFile->mMaterials.erase( index );
  667. mFile->_initMaterialInstMapping();
  668. for ( S32 i = 0; i < mFile->mLayerMap.size(); i++ )
  669. {
  670. if ( mFile->mLayerMap[i] >= index &&
  671. mFile->mLayerMap[i] != 0 )
  672. {
  673. mFile->mLayerMap[i]--;
  674. }
  675. }
  676. mDetailsDirty = true;
  677. mLayerTexDirty = true;
  678. }
  679. void TerrainBlock::updateMaterial( U32 index, const String &name )
  680. {
  681. if ( index >= mFile->mMaterials.size() )
  682. return;
  683. mFile->mMaterials[ index ] = TerrainMaterial::findOrCreate( name );
  684. mFile->_initMaterialInstMapping();
  685. mDetailsDirty = true;
  686. mLayerTexDirty = true;
  687. }
  688. TerrainMaterial* TerrainBlock::getMaterial( U32 index ) const
  689. {
  690. if ( index >= mFile->mMaterials.size() )
  691. return NULL;
  692. return mFile->mMaterials[ index ];
  693. }
  694. void TerrainBlock::deleteAllMaterials()
  695. {
  696. mFile->mMaterials.clear();
  697. mFile->mMaterialInstMapping.clearMatInstList();
  698. }
  699. const char* TerrainBlock::getMaterialName( U32 index ) const
  700. {
  701. if ( index < mFile->mMaterials.size() )
  702. return mFile->mMaterials[ index ]->getInternalName();
  703. return NULL;
  704. }
  705. void TerrainBlock::setLightMap( GBitmap *newLightMap )
  706. {
  707. SAFE_DELETE( mLightMap );
  708. mLightMap = newLightMap;
  709. mLightMapTex = NULL;
  710. }
  711. void TerrainBlock::clearLightMap()
  712. {
  713. if ( !mLightMap )
  714. mLightMap = new GBitmap( mLightMapSize, mLightMapSize, 0, GFXFormatR8G8B8 );
  715. mLightMap->fillWhite();
  716. mLightMapTex = NULL;
  717. }
  718. GFXTextureObject* TerrainBlock::getLightMapTex()
  719. {
  720. if ( mLightMapTex.isNull() && mLightMap )
  721. {
  722. mLightMapTex.set( mLightMap,
  723. &GFXStaticTextureProfile,
  724. false,
  725. "TerrainBlock::getLightMapTex()" );
  726. }
  727. return mLightMapTex;
  728. }
  729. void TerrainBlock::onEditorEnable()
  730. {
  731. }
  732. void TerrainBlock::onEditorDisable()
  733. {
  734. }
  735. bool TerrainBlock::onAdd()
  736. {
  737. if(!Parent::onAdd())
  738. return false;
  739. if ( mTerrFileName.isEmpty() )
  740. {
  741. mTerrFileName = Con::getVariable( "$Client::MissionFile" );
  742. String terrainDirectory( Con::getVariable( "$pref::Directories::Terrain" ) );
  743. if ( terrainDirectory.isEmpty() )
  744. {
  745. terrainDirectory = "art/terrains/";
  746. }
  747. mTerrFileName.replace("tools/levels/", terrainDirectory);
  748. mTerrFileName.replace("levels/", terrainDirectory);
  749. Vector<String> materials;
  750. materials.push_back( "warning_material" );
  751. TerrainFile::create( &mTerrFileName, 256, materials );
  752. }
  753. Resource<TerrainFile> terr = ResourceManager::get().load( mTerrFileName );
  754. if(terr == NULL)
  755. {
  756. if(isClientObject())
  757. NetConnection::setLastError("You are missing a file needed to play this mission: %s", mTerrFileName.c_str());
  758. return false;
  759. }
  760. setFile( terr );
  761. if ( terr->mNeedsResaving )
  762. {
  763. if (Platform::messageBox("Update Terrain File", "You appear to have a Terrain file in an older format. Do you want Torque to update it?", MBOkCancel, MIQuestion) == MROk)
  764. {
  765. terr->save(terr->mFilePath.getFullPath());
  766. terr->mNeedsResaving = false;
  767. }
  768. }
  769. if (terr->mFileVersion != TerrainFile::FILE_VERSION || terr->mNeedsResaving)
  770. {
  771. Con::errorf(" *********************************************************");
  772. Con::errorf(" *********************************************************");
  773. Con::errorf(" *********************************************************");
  774. Con::errorf(" PLEASE RESAVE THE TERRAIN FILE FOR THIS MISSION! THANKS!");
  775. Con::errorf(" *********************************************************");
  776. Con::errorf(" *********************************************************");
  777. Con::errorf(" *********************************************************");
  778. }
  779. _updateBounds();
  780. resetWorldBox();
  781. setRenderTransform(mObjToWorld);
  782. if (isClientObject())
  783. {
  784. if ( mCRC != terr.getChecksum() )
  785. {
  786. NetConnection::setLastError("Your terrain file doesn't match the version that is running on the server.");
  787. return false;
  788. }
  789. clearLightMap();
  790. // Init the detail layer rendering helper.
  791. _updateMaterials();
  792. _updateLayerTexture();
  793. // If the cached base texture is older that the terrain file or
  794. // it doesn't exist then generate and cache it.
  795. String baseCachePath = _getBaseTexCacheFileName();
  796. if ( Platform::compareModifiedTimes( baseCachePath, mTerrFileName ) < 0 )
  797. _updateBaseTexture( true );
  798. // The base texture should have been cached by now... so load it.
  799. mBaseTex.set( baseCachePath, &GFXStaticTextureSRGBProfile, "TerrainBlock::mBaseTex" );
  800. GFXTextureManager::addEventDelegate( this, &TerrainBlock::_onTextureEvent );
  801. MATMGR->getFlushSignal().notify( this, &TerrainBlock::_onFlushMaterials );
  802. // Build the terrain quadtree.
  803. _rebuildQuadtree();
  804. // Preload all the materials.
  805. mCell->preloadMaterials();
  806. mZoningDirty = true;
  807. SceneZoneSpaceManager::getZoningChangedSignal().notify( this, &TerrainBlock::_onZoningChanged );
  808. }
  809. else
  810. mCRC = terr.getChecksum();
  811. addToScene();
  812. _updatePhysics();
  813. return true;
  814. }
  815. String TerrainBlock::_getBaseTexCacheFileName() const
  816. {
  817. Torque::Path basePath( mTerrFileName );
  818. basePath.setFileName( basePath.getFileName() + "_basetex" );
  819. basePath.setExtension( formatToExtension(mBaseTexFormat) );
  820. return basePath.getFullPath();
  821. }
  822. void TerrainBlock::_rebuildQuadtree()
  823. {
  824. SAFE_DELETE( mCell );
  825. // Recursively build the cells.
  826. mCell = TerrCell::init( this );
  827. // Build the shared PrimitiveBuffer.
  828. mCell->createPrimBuffer( &mPrimBuffer );
  829. deleteZodiacPrimitiveBuffer();
  830. }
  831. void TerrainBlock::_updatePhysics()
  832. {
  833. if ( !PHYSICSMGR )
  834. return;
  835. SAFE_DELETE( mPhysicsRep );
  836. PhysicsCollision *colShape;
  837. // If we can steal the collision shape from the local server
  838. // object then do so as it saves us alot of cpu time and memory.
  839. //
  840. // TODO: We should move this sharing down into TerrFile where
  841. // it probably belongs.
  842. //
  843. if ( getServerObject() )
  844. {
  845. TerrainBlock *serverTerrain = (TerrainBlock*)getServerObject();
  846. colShape = serverTerrain->mPhysicsRep->getColShape();
  847. }
  848. else
  849. {
  850. // Get empty state of each vert
  851. bool *holes = new bool[ getBlockSize() * getBlockSize() ];
  852. for ( U32 row = 0; row < getBlockSize(); row++ )
  853. for ( U32 column = 0; column < getBlockSize(); column++ )
  854. holes[ row + (column * getBlockSize()) ] = mFile->isEmptyAt( row, column );
  855. colShape = PHYSICSMGR->createCollision();
  856. colShape->addHeightfield( mFile->getHeightMap().address(), holes, getBlockSize(), mSquareSize, MatrixF::Identity );
  857. delete [] holes;
  858. }
  859. PhysicsWorld *world = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" );
  860. mPhysicsRep = PHYSICSMGR->createBody();
  861. mPhysicsRep->init( colShape, 0, 0, this, world );
  862. mPhysicsRep->setTransform( getTransform() );
  863. }
  864. void TerrainBlock::onRemove()
  865. {
  866. removeFromScene();
  867. SceneZoneSpaceManager::getZoningChangedSignal().remove( this, &TerrainBlock::_onZoningChanged );
  868. SAFE_DELETE( mPhysicsRep );
  869. if ( isClientObject() )
  870. {
  871. mBaseTex = NULL;
  872. mLayerTex = NULL;
  873. SAFE_DELETE( mBaseMaterial );
  874. SAFE_DELETE( mDefaultMatInst );
  875. SAFE_DELETE( mCell );
  876. mPrimBuffer = NULL;
  877. mBaseShader = NULL;
  878. GFXTextureManager::removeEventDelegate( this, &TerrainBlock::_onTextureEvent );
  879. MATMGR->getFlushSignal().remove( this, &TerrainBlock::_onFlushMaterials );
  880. }
  881. Parent::onRemove();
  882. }
  883. void TerrainBlock::prepRenderImage( SceneRenderState* state )
  884. {
  885. PROFILE_SCOPE(TerrainBlock_prepRenderImage);
  886. // If we need to update our cached
  887. // zone state then do it now.
  888. if ( mZoningDirty )
  889. {
  890. mZoningDirty = false;
  891. mCell->updateZoning( getSceneManager()->getZoneManager() );
  892. }
  893. _renderBlock( state );
  894. }
  895. void TerrainBlock::setTransform(const MatrixF & mat)
  896. {
  897. Parent::setTransform( mat );
  898. // Update world-space OBBs.
  899. if( mCell )
  900. {
  901. mCell->updateOBBs();
  902. mZoningDirty = true;
  903. }
  904. if ( mPhysicsRep )
  905. mPhysicsRep->setTransform( mat );
  906. setRenderTransform( mat );
  907. setMaskBits( TransformMask );
  908. if(isClientObject())
  909. smUpdateSignal.trigger( HeightmapUpdate, this, Point2I::Zero, Point2I::Max );
  910. }
  911. void TerrainBlock::setScale( const VectorF &scale )
  912. {
  913. // We disable scaling... we never scale!
  914. Parent::setScale( VectorF::One );
  915. }
  916. void TerrainBlock::initPersistFields()
  917. {
  918. addGroup( "Media" );
  919. addProtectedField( "terrainFile", TypeStringFilename, Offset( mTerrFileName, TerrainBlock ),
  920. &TerrainBlock::_setTerrainFile, &defaultProtectedGetFn,
  921. "The source terrain data file." );
  922. endGroup( "Media" );
  923. addGroup( "Misc" );
  924. addField( "castShadows", TypeBool, Offset( mCastShadows, TerrainBlock ),
  925. "Allows the terrain to cast shadows onto itself and other objects.");
  926. addProtectedField( "squareSize", TypeF32, Offset( mSquareSize, TerrainBlock ),
  927. &TerrainBlock::_setSquareSize, &defaultProtectedGetFn,
  928. "Indicates the spacing between points on the XY plane on the terrain." );
  929. addProtectedField( "baseTexSize", TypeS32, Offset( mBaseTexSize, TerrainBlock ),
  930. &TerrainBlock::_setBaseTexSize, &defaultProtectedGetFn,
  931. "Size of base texture size per meter." );
  932. addProtectedField("baseTexFormat", TYPEID<baseTexFormat>(), Offset(mBaseTexFormat, TerrainBlock),
  933. &TerrainBlock::_setBaseTexFormat, &defaultProtectedGetFn,
  934. "");
  935. addProtectedField( "lightMapSize", TypeS32, Offset( mLightMapSize, TerrainBlock ),
  936. &TerrainBlock::_setLightMapSize, &defaultProtectedGetFn,
  937. "Light map dimensions in pixels." );
  938. addField( "screenError", TypeS32, Offset( mScreenError, TerrainBlock ), "Not yet implemented." );
  939. endGroup( "Misc" );
  940. addGroup("AFX");
  941. addField("ignoreZodiacs", TypeBool, Offset(mIgnoreZodiacs, TerrainBlock));
  942. endGroup("AFX");
  943. Parent::initPersistFields();
  944. removeField( "scale" );
  945. Con::addVariable( "$TerrainBlock::debugRender", TypeBool, &smDebugRender, "Triggers debug rendering of terrain cells\n\n"
  946. "@ingroup Terrain");
  947. Con::addVariable( "$pref::Terrain::lodScale", TypeF32, &smLODScale, "A global LOD scale used to tweak the default terrain screen error value.\n\n"
  948. "@ingroup Terrain");
  949. Con::addVariable( "$pref::Terrain::detailScale", TypeF32, &smDetailScale, "A global detail scale used to tweak the material detail distances.\n\n"
  950. "@ingroup Terrain");
  951. }
  952. void TerrainBlock::inspectPostApply()
  953. {
  954. Parent::inspectPostApply();
  955. setMaskBits( MiscMask );
  956. }
  957. U32 TerrainBlock::packUpdate(NetConnection* con, U32 mask, BitStream *stream)
  958. {
  959. U32 retMask = Parent::packUpdate( con, mask, stream );
  960. if ( stream->writeFlag( mask & TransformMask ) )
  961. mathWrite( *stream, getTransform() );
  962. if ( stream->writeFlag( mask & FileMask ) )
  963. {
  964. stream->write( mTerrFileName );
  965. stream->write( mCRC );
  966. }
  967. if ( stream->writeFlag( mask & SizeMask ) )
  968. stream->write( mSquareSize );
  969. stream->writeFlag( mCastShadows );
  970. if ( stream->writeFlag( mask & MaterialMask ) )
  971. {
  972. stream->write( mBaseTexSize );
  973. stream->write( mLightMapSize );
  974. }
  975. stream->writeFlag( mask & HeightMapChangeMask );
  976. if ( stream->writeFlag( mask & MiscMask ) )
  977. stream->write( mScreenError );
  978. stream->writeInt(mBaseTexFormat, 32);
  979. stream->writeFlag(mIgnoreZodiacs);
  980. return retMask;
  981. }
  982. void TerrainBlock::unpackUpdate(NetConnection* con, BitStream *stream)
  983. {
  984. Parent::unpackUpdate( con, stream );
  985. if ( stream->readFlag() ) // TransformMask
  986. {
  987. MatrixF mat;
  988. mathRead( *stream, &mat );
  989. setTransform( mat );
  990. }
  991. if ( stream->readFlag() ) // FileMask
  992. {
  993. FileName terrFile;
  994. stream->read( &terrFile );
  995. stream->read( &mCRC );
  996. if ( isProperlyAdded() )
  997. setFile( terrFile );
  998. else
  999. mTerrFileName = terrFile;
  1000. }
  1001. if ( stream->readFlag() ) // SizeMask
  1002. stream->read( &mSquareSize );
  1003. mCastShadows = stream->readFlag();
  1004. if ( stream->readFlag() ) // MaterialMask
  1005. {
  1006. U32 baseTexSize;
  1007. stream->read( &baseTexSize );
  1008. if ( mBaseTexSize != baseTexSize )
  1009. {
  1010. mBaseTexSize = baseTexSize;
  1011. if ( isProperlyAdded() )
  1012. _updateBaseTexture( NONE );
  1013. }
  1014. U32 lightMapSize;
  1015. stream->read( &lightMapSize );
  1016. if ( mLightMapSize != lightMapSize )
  1017. {
  1018. mLightMapSize = lightMapSize;
  1019. if ( isProperlyAdded() )
  1020. {
  1021. SAFE_DELETE( mLightMap );
  1022. clearLightMap();
  1023. }
  1024. }
  1025. }
  1026. if ( stream->readFlag() && isProperlyAdded() ) // HeightMapChangeMask
  1027. {
  1028. _updateBounds();
  1029. _rebuildQuadtree();
  1030. _updatePhysics();
  1031. mDetailsDirty = true;
  1032. mLayerTexDirty = true;
  1033. }
  1034. if ( stream->readFlag() ) // MiscMask
  1035. stream->read( &mScreenError );
  1036. mBaseTexFormat = (BaseTexFormat)stream->readInt(32);
  1037. mIgnoreZodiacs = stream->readFlag();
  1038. }
  1039. void TerrainBlock::getMinMaxHeight( F32 *minHeight, F32 *maxHeight ) const
  1040. {
  1041. // We can get the bound height from the last grid level.
  1042. const TerrainSquare *sq = mFile->findSquare( mFile->mGridLevels, 0, 0 );
  1043. *minHeight = fixedToFloat( sq->minHeight );
  1044. *maxHeight = fixedToFloat( sq->maxHeight );
  1045. }
  1046. //-----------------------------------------------------------------------------
  1047. // Console Methods
  1048. //-----------------------------------------------------------------------------
  1049. DefineEngineMethod( TerrainBlock, save, bool, ( const char* fileName),,
  1050. "@brief Saves the terrain block's terrain file to the specified file name.\n\n"
  1051. "@param fileName Name and path of file to save terrain data to.\n\n"
  1052. "@return True if file save was successful, false otherwise")
  1053. {
  1054. char filename[256];
  1055. dStrcpy(filename,fileName,256);
  1056. char *ext = dStrrchr(filename, '.');
  1057. if (!ext || dStricmp(ext, ".ter") != 0)
  1058. dStrcat(filename, ".ter", 256);
  1059. return static_cast<TerrainBlock*>(object)->save(filename);
  1060. }
  1061. //ConsoleMethod(TerrainBlock, save, bool, 3, 3, "(string fileName) - saves the terrain block's terrain file to the specified file name.")
  1062. //{
  1063. // char filename[256];
  1064. // dStrcpy(filename,argv[2],256);
  1065. // char *ext = dStrrchr(filename, '.');
  1066. // if (!ext || dStricmp(ext, ".ter") != 0)
  1067. // dStrcat(filename, ".ter", 256);
  1068. // return static_cast<TerrainBlock*>(object)->save(filename);
  1069. //}
  1070. ConsoleDocFragment _getTerrainHeight1(
  1071. "@brief Gets the terrain height at the specified position\n\n"
  1072. "@param position The world space point, minus the z (height) value. Formatted as (\"x y\")\n\n"
  1073. "@return Returns the terrain height at the given point as an F32 value.\n\n"
  1074. "@ingroup Terrain",
  1075. NULL,
  1076. "bool getTerrainHeight( Point2I position );"
  1077. );
  1078. ConsoleDocFragment _getTerrainHeight2(
  1079. "@brief Gets the terrain height at the specified position\n\n"
  1080. "@param x The X coordinate in world space\n"
  1081. "@param y The Y coordinate in world space\n\n"
  1082. "@return Returns the terrain height at the given point as an F32 value.\n\n"
  1083. "@ingroup Terrain",
  1084. NULL,
  1085. "bool getTerrainHeight( F32 x, F32 y);"
  1086. );
  1087. DefineEngineFunction( getTerrainHeight, F32, (const char* ptOrX, const char* y), (""), "(Point2 pos) - gets the terrain height at the specified position."
  1088. "@param pos The world space point, minus the z (height) value\n Can be formatted as either (\"x y\") or (x,y)\n"
  1089. "@return Returns the terrain height at the given point as an F32 value.\n"
  1090. "@hide")
  1091. {
  1092. F32 height = 0.0f;
  1093. Point2F pos;
  1094. if(!String::isEmpty(ptOrX) && String::isEmpty(y))
  1095. dSscanf(ptOrX, "%f %f", &pos.x, &pos.y);
  1096. else if(!String::isEmpty(ptOrX) && !String::isEmpty(y))
  1097. {
  1098. pos.x = dAtof(ptOrX);
  1099. pos.y = dAtof(y);
  1100. }
  1101. TerrainBlock * terrain = getTerrainUnderWorldPoint(Point3F(pos.x, pos.y, 5000.0f));
  1102. if(terrain && terrain->isServerObject())
  1103. {
  1104. Point3F offset;
  1105. terrain->getTransform().getColumn(3, &offset);
  1106. pos -= Point2F(offset.x, offset.y);
  1107. terrain->getHeight(pos, &height);
  1108. }
  1109. return height;
  1110. }
  1111. ConsoleDocFragment _getTerrainHeightBelowPosition1(
  1112. "@brief Takes a world point and find the \"highest\" terrain underneath it\n\n"
  1113. "@param position The world space point, minus the z (height) value. Formatted as (\"x y\")\n\n"
  1114. "@return Returns the closest terrain height below the given point as an F32 value.\n\n"
  1115. "@ingroup Terrain",
  1116. NULL,
  1117. "bool getTerrainHeightBelowPosition( Point2I position );"
  1118. );
  1119. ConsoleDocFragment _getTerrainHeightBelowPosition2(
  1120. "@brief Takes a world point and find the \"highest\" terrain underneath it\n\n"
  1121. "@param x The X coordinate in world space\n"
  1122. "@param y The Y coordinate in world space\n\n"
  1123. "@return Returns the closest terrain height below the given point as an F32 value.\n\n"
  1124. "@ingroup Terrain",
  1125. NULL,
  1126. "bool getTerrainHeightBelowPosition( F32 x, F32 y);"
  1127. );
  1128. DefineEngineFunction( getTerrainHeightBelowPosition, F32, (const char* ptOrX, const char* y, const char* z), ("", ""),
  1129. "(Point3F pos) - gets the terrain height at the specified position."
  1130. "@param pos The world space point. Can be formatted as either (\"x y z\") or (x,y,z)\n"
  1131. "@note This function is useful if you simply want to grab the terrain height underneath an object.\n"
  1132. "@return Returns the terrain height at the given point as an F32 value.\n"
  1133. "@hide")
  1134. {
  1135. F32 height = 0.0f;
  1136. Point3F pos;
  1137. if(!String::isEmpty(ptOrX) && String::isEmpty(y) && String::isEmpty(z))
  1138. dSscanf(ptOrX, "%f %f %f", &pos.x, &pos.y, &pos.z);
  1139. else if(!String::isEmpty(ptOrX) && !String::isEmpty(y) && !String::isEmpty(z))
  1140. {
  1141. pos.x = dAtof(ptOrX);
  1142. pos.y = dAtof(y);
  1143. pos.z = dAtof(z);
  1144. }
  1145. TerrainBlock * terrain = getTerrainUnderWorldPoint(pos);
  1146. Point2F nohghtPos(pos.x, pos.y);
  1147. if(terrain)
  1148. {
  1149. if(terrain->isServerObject())
  1150. {
  1151. Point3F offset;
  1152. terrain->getTransform().getColumn(3, &offset);
  1153. nohghtPos -= Point2F(offset.x, offset.y);
  1154. terrain->getHeight(nohghtPos, &height);
  1155. }
  1156. }
  1157. return height;
  1158. }
  1159. const U16* TerrainBlock::getZodiacPrimitiveBuffer()
  1160. {
  1161. if (!zode_primBuffer && !mIgnoreZodiacs)
  1162. TerrCell::createZodiacPrimBuffer(&zode_primBuffer);
  1163. return zode_primBuffer;
  1164. }
  1165. void TerrainBlock::deleteZodiacPrimitiveBuffer()
  1166. {
  1167. if (zode_primBuffer != 0)
  1168. {
  1169. delete [] zode_primBuffer;
  1170. zode_primBuffer = 0;
  1171. }
  1172. }