terrData.cpp 41 KB

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