terrData.cpp 50 KB

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