terrData.cpp 45 KB

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