Terrain.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469
  1. //
  2. // Copyright (c) 2008-2020 the Urho3D project.
  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 deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // 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 FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Graphics/DrawableEvents.h"
  26. #include "../Graphics/Geometry.h"
  27. #include "../Graphics/IndexBuffer.h"
  28. #include "../Graphics/Material.h"
  29. #include "../Graphics/Octree.h"
  30. #include "../Graphics/Terrain.h"
  31. #include "../Graphics/TerrainPatch.h"
  32. #include "../Graphics/VertexBuffer.h"
  33. #include "../IO/Log.h"
  34. #include "../Resource/Image.h"
  35. #include "../Resource/ResourceCache.h"
  36. #include "../Resource/ResourceEvents.h"
  37. #include "../Scene/Node.h"
  38. #include "../Scene/Scene.h"
  39. #include "../DebugNew.h"
  40. namespace Urho3D
  41. {
  42. extern const char* GEOMETRY_CATEGORY;
  43. static const Vector3 DEFAULT_SPACING(1.0f, 0.25f, 1.0f);
  44. static const unsigned MIN_LOD_LEVELS = 1;
  45. static const unsigned MAX_LOD_LEVELS = 4;
  46. static const int DEFAULT_PATCH_SIZE = 32;
  47. static const int MIN_PATCH_SIZE = 4;
  48. static const int MAX_PATCH_SIZE = 128;
  49. static const unsigned STITCH_NORTH = 1;
  50. static const unsigned STITCH_SOUTH = 2;
  51. static const unsigned STITCH_WEST = 4;
  52. static const unsigned STITCH_EAST = 8;
  53. inline void GrowUpdateRegion(IntRect& updateRegion, int x, int y)
  54. {
  55. if (updateRegion.left_ < 0)
  56. {
  57. updateRegion.left_ = updateRegion.right_ = x;
  58. updateRegion.top_ = updateRegion.bottom_ = y;
  59. }
  60. else
  61. {
  62. if (x < updateRegion.left_)
  63. updateRegion.left_ = x;
  64. if (x > updateRegion.right_)
  65. updateRegion.right_ = x;
  66. if (y < updateRegion.top_)
  67. updateRegion.top_ = y;
  68. if (y > updateRegion.bottom_)
  69. updateRegion.bottom_ = y;
  70. }
  71. }
  72. Terrain::Terrain(Context* context) :
  73. Component(context),
  74. indexBuffer_(new IndexBuffer(context)),
  75. spacing_(DEFAULT_SPACING),
  76. lastSpacing_(Vector3::ZERO),
  77. patchWorldOrigin_(Vector2::ZERO),
  78. patchWorldSize_(Vector2::ZERO),
  79. numVertices_(IntVector2::ZERO),
  80. lastNumVertices_(IntVector2::ZERO),
  81. numPatches_(IntVector2::ZERO),
  82. patchSize_(DEFAULT_PATCH_SIZE),
  83. lastPatchSize_(0),
  84. numLodLevels_(1),
  85. maxLodLevels_(MAX_LOD_LEVELS),
  86. occlusionLodLevel_(M_MAX_UNSIGNED),
  87. smoothing_(false),
  88. visible_(true),
  89. castShadows_(false),
  90. occluder_(false),
  91. occludee_(true),
  92. viewMask_(DEFAULT_VIEWMASK),
  93. lightMask_(DEFAULT_LIGHTMASK),
  94. shadowMask_(DEFAULT_SHADOWMASK),
  95. zoneMask_(DEFAULT_ZONEMASK),
  96. drawDistance_(0.0f),
  97. shadowDistance_(0.0f),
  98. lodBias_(1.0f),
  99. maxLights_(0),
  100. northID_(0),
  101. southID_(0),
  102. westID_(0),
  103. eastID_(0),
  104. recreateTerrain_(false),
  105. neighborsDirty_(false)
  106. {
  107. indexBuffer_->SetShadowed(true);
  108. }
  109. Terrain::~Terrain() = default;
  110. void Terrain::RegisterObject(Context* context)
  111. {
  112. context->RegisterFactory<Terrain>(GEOMETRY_CATEGORY);
  113. URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  114. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Height Map", GetHeightMapAttr, SetHeightMapAttr, ResourceRef, ResourceRef(Image::GetTypeStatic()),
  115. AM_DEFAULT);
  116. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()),
  117. AM_DEFAULT);
  118. URHO3D_ATTRIBUTE_EX("North Neighbor NodeID", unsigned, northID_, MarkNeighborsDirty, 0, AM_DEFAULT | AM_NODEID);
  119. URHO3D_ATTRIBUTE_EX("South Neighbor NodeID", unsigned, southID_, MarkNeighborsDirty, 0, AM_DEFAULT | AM_NODEID);
  120. URHO3D_ATTRIBUTE_EX("West Neighbor NodeID", unsigned, westID_, MarkNeighborsDirty, 0, AM_DEFAULT | AM_NODEID);
  121. URHO3D_ATTRIBUTE_EX("East Neighbor NodeID", unsigned, eastID_, MarkNeighborsDirty, 0, AM_DEFAULT | AM_NODEID);
  122. URHO3D_ATTRIBUTE_EX("Vertex Spacing", Vector3, spacing_, MarkTerrainDirty, DEFAULT_SPACING, AM_DEFAULT);
  123. URHO3D_ACCESSOR_ATTRIBUTE("Patch Size", GetPatchSize, SetPatchSizeAttr, int, DEFAULT_PATCH_SIZE, AM_DEFAULT);
  124. URHO3D_ACCESSOR_ATTRIBUTE("Max LOD Levels", GetMaxLodLevels, SetMaxLodLevelsAttr, unsigned, MAX_LOD_LEVELS, AM_DEFAULT);
  125. URHO3D_ATTRIBUTE_EX("Smooth Height Map", bool, smoothing_, MarkTerrainDirty, false, AM_DEFAULT);
  126. URHO3D_ACCESSOR_ATTRIBUTE("Is Occluder", IsOccluder, SetOccluder, bool, false, AM_DEFAULT);
  127. URHO3D_ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  128. URHO3D_ACCESSOR_ATTRIBUTE("Cast Shadows", GetCastShadows, SetCastShadows, bool, false, AM_DEFAULT);
  129. URHO3D_ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  130. URHO3D_ACCESSOR_ATTRIBUTE("Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  131. URHO3D_ACCESSOR_ATTRIBUTE("LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
  132. URHO3D_ACCESSOR_ATTRIBUTE("Max Lights", GetMaxLights, SetMaxLights, unsigned, 0, AM_DEFAULT);
  133. URHO3D_ACCESSOR_ATTRIBUTE("View Mask", GetViewMask, SetViewMask, unsigned, DEFAULT_VIEWMASK, AM_DEFAULT);
  134. URHO3D_ACCESSOR_ATTRIBUTE("Light Mask", GetLightMask, SetLightMask, unsigned, DEFAULT_LIGHTMASK, AM_DEFAULT);
  135. URHO3D_ACCESSOR_ATTRIBUTE("Shadow Mask", GetShadowMask, SetShadowMask, unsigned, DEFAULT_SHADOWMASK, AM_DEFAULT);
  136. URHO3D_ACCESSOR_ATTRIBUTE("Zone Mask", GetZoneMask, SetZoneMask, unsigned, DEFAULT_ZONEMASK, AM_DEFAULT);
  137. URHO3D_ACCESSOR_ATTRIBUTE("Occlusion LOD level", GetOcclusionLodLevel, SetOcclusionLodLevelAttr, unsigned, M_MAX_UNSIGNED, AM_DEFAULT);
  138. }
  139. void Terrain::ApplyAttributes()
  140. {
  141. if (recreateTerrain_)
  142. CreateGeometry();
  143. if (neighborsDirty_)
  144. {
  145. Scene* scene = GetScene();
  146. Node* north = scene ? scene->GetNode(northID_) : nullptr;
  147. Node* south = scene ? scene->GetNode(southID_) : nullptr;
  148. Node* west = scene ? scene->GetNode(westID_) : nullptr;
  149. Node* east = scene ? scene->GetNode(eastID_) : nullptr;
  150. Terrain* northTerrain = north ? north->GetComponent<Terrain>() : nullptr;
  151. Terrain* southTerrain = south ? south->GetComponent<Terrain>() : nullptr;
  152. Terrain* westTerrain = west ? west->GetComponent<Terrain>() : nullptr;
  153. Terrain* eastTerrain = east ? east->GetComponent<Terrain>() : nullptr;
  154. SetNeighbors(northTerrain, southTerrain, westTerrain, eastTerrain);
  155. neighborsDirty_ = false;
  156. }
  157. }
  158. void Terrain::OnSetEnabled()
  159. {
  160. bool enabled = IsEnabledEffective();
  161. for (unsigned i = 0; i < patches_.Size(); ++i)
  162. {
  163. if (patches_[i])
  164. patches_[i]->SetEnabled(enabled);
  165. }
  166. }
  167. void Terrain::SetPatchSize(int size)
  168. {
  169. if (size < MIN_PATCH_SIZE || size > MAX_PATCH_SIZE || !IsPowerOfTwo((unsigned)size))
  170. return;
  171. if (size != patchSize_)
  172. {
  173. patchSize_ = size;
  174. CreateGeometry();
  175. MarkNetworkUpdate();
  176. }
  177. }
  178. void Terrain::SetSpacing(const Vector3& spacing)
  179. {
  180. if (spacing != spacing_)
  181. {
  182. spacing_ = spacing;
  183. CreateGeometry();
  184. MarkNetworkUpdate();
  185. }
  186. }
  187. void Terrain::SetMaxLodLevels(unsigned levels)
  188. {
  189. levels = Clamp(levels, MIN_LOD_LEVELS, MAX_LOD_LEVELS);
  190. if (levels != maxLodLevels_)
  191. {
  192. maxLodLevels_ = levels;
  193. lastPatchSize_ = 0; // Force full recreate
  194. CreateGeometry();
  195. MarkNetworkUpdate();
  196. }
  197. }
  198. void Terrain::SetOcclusionLodLevel(unsigned level)
  199. {
  200. if (level != occlusionLodLevel_)
  201. {
  202. occlusionLodLevel_ = level;
  203. lastPatchSize_ = 0; // Force full recreate
  204. CreateGeometry();
  205. MarkNetworkUpdate();
  206. }
  207. }
  208. void Terrain::SetSmoothing(bool enable)
  209. {
  210. if (enable != smoothing_)
  211. {
  212. smoothing_ = enable;
  213. CreateGeometry();
  214. MarkNetworkUpdate();
  215. }
  216. }
  217. bool Terrain::SetHeightMap(Image* image)
  218. {
  219. bool success = SetHeightMapInternal(image, true);
  220. MarkNetworkUpdate();
  221. return success;
  222. }
  223. void Terrain::SetMaterial(Material* material)
  224. {
  225. material_ = material;
  226. for (unsigned i = 0; i < patches_.Size(); ++i)
  227. {
  228. if (patches_[i])
  229. patches_[i]->SetMaterial(material);
  230. }
  231. MarkNetworkUpdate();
  232. }
  233. void Terrain::SetNorthNeighbor(Terrain* north)
  234. {
  235. if (north == north_)
  236. return;
  237. if (north_ && north_->GetNode())
  238. UnsubscribeFromEvent(north_->GetNode(), E_TERRAINCREATED);
  239. north_ = north;
  240. if (north_ && north_->GetNode())
  241. {
  242. northID_ = north_->GetNode()->GetID();
  243. SubscribeToEvent(north_->GetNode(), E_TERRAINCREATED, URHO3D_HANDLER(Terrain, HandleNeighborTerrainCreated));
  244. }
  245. UpdateEdgePatchNeighbors();
  246. MarkNetworkUpdate();
  247. }
  248. void Terrain::SetSouthNeighbor(Terrain* south)
  249. {
  250. if (south == south_)
  251. return;
  252. if (south_ && south_->GetNode())
  253. UnsubscribeFromEvent(south_->GetNode(), E_TERRAINCREATED);
  254. south_ = south;
  255. if (south_ && south_->GetNode())
  256. {
  257. southID_ = south_->GetNode()->GetID();
  258. SubscribeToEvent(south_->GetNode(), E_TERRAINCREATED, URHO3D_HANDLER(Terrain, HandleNeighborTerrainCreated));
  259. }
  260. UpdateEdgePatchNeighbors();
  261. MarkNetworkUpdate();
  262. }
  263. void Terrain::SetWestNeighbor(Terrain* west)
  264. {
  265. if (west == west_)
  266. return;
  267. if (west_ && west_->GetNode())
  268. UnsubscribeFromEvent(west_->GetNode(), E_TERRAINCREATED);
  269. west_ = west;
  270. if (west_ && west_->GetNode())
  271. {
  272. westID_ = west_->GetNode()->GetID();
  273. SubscribeToEvent(west_->GetNode(), E_TERRAINCREATED, URHO3D_HANDLER(Terrain, HandleNeighborTerrainCreated));
  274. }
  275. UpdateEdgePatchNeighbors();
  276. MarkNetworkUpdate();
  277. }
  278. void Terrain::SetEastNeighbor(Terrain* east)
  279. {
  280. if (east == east_)
  281. return;
  282. if (east_ && east_->GetNode())
  283. UnsubscribeFromEvent(east_->GetNode(), E_TERRAINCREATED);
  284. east_ = east;
  285. if (east_ && east_->GetNode())
  286. {
  287. eastID_ = east_->GetNode()->GetID();
  288. SubscribeToEvent(east_->GetNode(), E_TERRAINCREATED, URHO3D_HANDLER(Terrain, HandleNeighborTerrainCreated));
  289. }
  290. UpdateEdgePatchNeighbors();
  291. MarkNetworkUpdate();
  292. }
  293. void Terrain::SetNeighbors(Terrain* north, Terrain* south, Terrain* west, Terrain* east)
  294. {
  295. if (north_ && north_->GetNode())
  296. UnsubscribeFromEvent(north_->GetNode(), E_TERRAINCREATED);
  297. if (south_ && south_->GetNode())
  298. UnsubscribeFromEvent(south_->GetNode(), E_TERRAINCREATED);
  299. if (west_ && west_->GetNode())
  300. UnsubscribeFromEvent(west_->GetNode(), E_TERRAINCREATED);
  301. if (east_ && east_->GetNode())
  302. UnsubscribeFromEvent(east_->GetNode(), E_TERRAINCREATED);
  303. north_ = north;
  304. if (north_ && north_->GetNode())
  305. {
  306. northID_ = north_->GetNode()->GetID();
  307. SubscribeToEvent(north_->GetNode(), E_TERRAINCREATED, URHO3D_HANDLER(Terrain, HandleNeighborTerrainCreated));
  308. }
  309. south_ = south;
  310. if (south_ && south_->GetNode())
  311. {
  312. southID_ = south_->GetNode()->GetID();
  313. SubscribeToEvent(south_->GetNode(), E_TERRAINCREATED, URHO3D_HANDLER(Terrain, HandleNeighborTerrainCreated));
  314. }
  315. west_ = west;
  316. if (west_ && west_->GetNode())
  317. {
  318. westID_ = west_->GetNode()->GetID();
  319. SubscribeToEvent(west_->GetNode(), E_TERRAINCREATED, URHO3D_HANDLER(Terrain, HandleNeighborTerrainCreated));
  320. }
  321. east_ = east;
  322. if (east_ && east_->GetNode())
  323. {
  324. eastID_ = east_->GetNode()->GetID();
  325. SubscribeToEvent(east_->GetNode(), E_TERRAINCREATED, URHO3D_HANDLER(Terrain, HandleNeighborTerrainCreated));
  326. }
  327. UpdateEdgePatchNeighbors();
  328. MarkNetworkUpdate();
  329. }
  330. void Terrain::SetDrawDistance(float distance)
  331. {
  332. drawDistance_ = distance;
  333. for (unsigned i = 0; i < patches_.Size(); ++i)
  334. {
  335. if (patches_[i])
  336. patches_[i]->SetDrawDistance(distance);
  337. }
  338. MarkNetworkUpdate();
  339. }
  340. void Terrain::SetShadowDistance(float distance)
  341. {
  342. shadowDistance_ = distance;
  343. for (unsigned i = 0; i < patches_.Size(); ++i)
  344. {
  345. if (patches_[i])
  346. patches_[i]->SetShadowDistance(distance);
  347. }
  348. MarkNetworkUpdate();
  349. }
  350. void Terrain::SetLodBias(float bias)
  351. {
  352. lodBias_ = bias;
  353. for (unsigned i = 0; i < patches_.Size(); ++i)
  354. {
  355. if (patches_[i])
  356. patches_[i]->SetLodBias(bias);
  357. }
  358. MarkNetworkUpdate();
  359. }
  360. void Terrain::SetViewMask(unsigned mask)
  361. {
  362. viewMask_ = mask;
  363. for (unsigned i = 0; i < patches_.Size(); ++i)
  364. {
  365. if (patches_[i])
  366. patches_[i]->SetViewMask(mask);
  367. }
  368. MarkNetworkUpdate();
  369. }
  370. void Terrain::SetLightMask(unsigned mask)
  371. {
  372. lightMask_ = mask;
  373. for (unsigned i = 0; i < patches_.Size(); ++i)
  374. {
  375. if (patches_[i])
  376. patches_[i]->SetLightMask(mask);
  377. }
  378. MarkNetworkUpdate();
  379. }
  380. void Terrain::SetShadowMask(unsigned mask)
  381. {
  382. shadowMask_ = mask;
  383. for (unsigned i = 0; i < patches_.Size(); ++i)
  384. {
  385. if (patches_[i])
  386. patches_[i]->SetShadowMask(mask);
  387. }
  388. MarkNetworkUpdate();
  389. }
  390. void Terrain::SetZoneMask(unsigned mask)
  391. {
  392. zoneMask_ = mask;
  393. for (unsigned i = 0; i < patches_.Size(); ++i)
  394. {
  395. if (patches_[i])
  396. patches_[i]->SetZoneMask(mask);
  397. }
  398. MarkNetworkUpdate();
  399. }
  400. void Terrain::SetMaxLights(unsigned num)
  401. {
  402. maxLights_ = num;
  403. for (unsigned i = 0; i < patches_.Size(); ++i)
  404. {
  405. if (patches_[i])
  406. patches_[i]->SetMaxLights(num);
  407. }
  408. MarkNetworkUpdate();
  409. }
  410. void Terrain::SetCastShadows(bool enable)
  411. {
  412. castShadows_ = enable;
  413. for (unsigned i = 0; i < patches_.Size(); ++i)
  414. {
  415. if (patches_[i])
  416. patches_[i]->SetCastShadows(enable);
  417. }
  418. MarkNetworkUpdate();
  419. }
  420. void Terrain::SetOccluder(bool enable)
  421. {
  422. occluder_ = enable;
  423. for (unsigned i = 0; i < patches_.Size(); ++i)
  424. {
  425. if (patches_[i])
  426. patches_[i]->SetOccluder(enable);
  427. }
  428. MarkNetworkUpdate();
  429. }
  430. void Terrain::SetOccludee(bool enable)
  431. {
  432. occludee_ = enable;
  433. for (unsigned i = 0; i < patches_.Size(); ++i)
  434. {
  435. if (patches_[i])
  436. patches_[i]->SetOccludee(enable);
  437. }
  438. MarkNetworkUpdate();
  439. }
  440. void Terrain::ApplyHeightMap()
  441. {
  442. if (heightMap_)
  443. CreateGeometry();
  444. }
  445. Image* Terrain::GetHeightMap() const
  446. {
  447. return heightMap_;
  448. }
  449. Material* Terrain::GetMaterial() const
  450. {
  451. return material_;
  452. }
  453. TerrainPatch* Terrain::GetPatch(unsigned index) const
  454. {
  455. return index < patches_.Size() ? patches_[index] : nullptr;
  456. }
  457. TerrainPatch* Terrain::GetPatch(int x, int z) const
  458. {
  459. if (x < 0 || x >= numPatches_.x_ || z < 0 || z >= numPatches_.y_)
  460. return nullptr;
  461. else
  462. return GetPatch((unsigned)(z * numPatches_.x_ + x));
  463. }
  464. TerrainPatch* Terrain::GetNeighborPatch(int x, int z) const
  465. {
  466. if (z >= numPatches_.y_ && north_)
  467. return north_->GetPatch(x, z - numPatches_.y_);
  468. else if (z < 0 && south_)
  469. return south_->GetPatch(x, z + south_->GetNumPatches().y_);
  470. else if (x < 0 && west_)
  471. return west_->GetPatch(x + west_->GetNumPatches().x_, z);
  472. else if (x >= numPatches_.x_ && east_)
  473. return east_->GetPatch(x - numPatches_.x_, z);
  474. else
  475. return GetPatch(x, z);
  476. }
  477. float Terrain::GetHeight(const Vector3& worldPosition) const
  478. {
  479. if (node_)
  480. {
  481. Vector3 position = node_->GetWorldTransform().Inverse() * worldPosition;
  482. float xPos = (position.x_ - patchWorldOrigin_.x_) / spacing_.x_;
  483. float zPos = (position.z_ - patchWorldOrigin_.y_) / spacing_.z_;
  484. float xFrac = Fract(xPos);
  485. float zFrac = Fract(zPos);
  486. float h1, h2, h3;
  487. if (xFrac + zFrac >= 1.0f)
  488. {
  489. h1 = GetRawHeight((unsigned)xPos + 1, (unsigned)zPos + 1);
  490. h2 = GetRawHeight((unsigned)xPos, (unsigned)zPos + 1);
  491. h3 = GetRawHeight((unsigned)xPos + 1, (unsigned)zPos);
  492. xFrac = 1.0f - xFrac;
  493. zFrac = 1.0f - zFrac;
  494. }
  495. else
  496. {
  497. h1 = GetRawHeight((unsigned)xPos, (unsigned)zPos);
  498. h2 = GetRawHeight((unsigned)xPos + 1, (unsigned)zPos);
  499. h3 = GetRawHeight((unsigned)xPos, (unsigned)zPos + 1);
  500. }
  501. float h = h1 * (1.0f - xFrac - zFrac) + h2 * xFrac + h3 * zFrac;
  502. /// \todo This assumes that the terrain scene node is upright
  503. return node_->GetWorldScale().y_ * h + node_->GetWorldPosition().y_;
  504. }
  505. else
  506. return 0.0f;
  507. }
  508. Vector3 Terrain::GetNormal(const Vector3& worldPosition) const
  509. {
  510. if (node_)
  511. {
  512. Vector3 position = node_->GetWorldTransform().Inverse() * worldPosition;
  513. float xPos = (position.x_ - patchWorldOrigin_.x_) / spacing_.x_;
  514. float zPos = (position.z_ - patchWorldOrigin_.y_) / spacing_.z_;
  515. float xFrac = Fract(xPos);
  516. float zFrac = Fract(zPos);
  517. Vector3 n1, n2, n3;
  518. if (xFrac + zFrac >= 1.0f)
  519. {
  520. n1 = GetRawNormal((unsigned)xPos + 1, (unsigned)zPos + 1);
  521. n2 = GetRawNormal((unsigned)xPos, (unsigned)zPos + 1);
  522. n3 = GetRawNormal((unsigned)xPos + 1, (unsigned)zPos);
  523. xFrac = 1.0f - xFrac;
  524. zFrac = 1.0f - zFrac;
  525. }
  526. else
  527. {
  528. n1 = GetRawNormal((unsigned)xPos, (unsigned)zPos);
  529. n2 = GetRawNormal((unsigned)xPos + 1, (unsigned)zPos);
  530. n3 = GetRawNormal((unsigned)xPos, (unsigned)zPos + 1);
  531. }
  532. Vector3 n = (n1 * (1.0f - xFrac - zFrac) + n2 * xFrac + n3 * zFrac).Normalized();
  533. return node_->GetWorldRotation() * n;
  534. }
  535. else
  536. return Vector3::UP;
  537. }
  538. IntVector2 Terrain::WorldToHeightMap(const Vector3& worldPosition) const
  539. {
  540. if (!node_)
  541. return IntVector2::ZERO;
  542. Vector3 position = node_->GetWorldTransform().Inverse() * worldPosition;
  543. auto xPos = RoundToInt((position.x_ - patchWorldOrigin_.x_) / spacing_.x_);
  544. auto zPos = RoundToInt((position.z_ - patchWorldOrigin_.y_) / spacing_.z_);
  545. xPos = Clamp(xPos, 0, numVertices_.x_ - 1);
  546. zPos = Clamp(zPos, 0, numVertices_.y_ - 1);
  547. return IntVector2(xPos, numVertices_.y_ - 1 - zPos);
  548. }
  549. Vector3 Terrain::HeightMapToWorld(const IntVector2& pixelPosition) const
  550. {
  551. if (!node_)
  552. return Vector3::ZERO;
  553. IntVector2 pos(pixelPosition.x_, numVertices_.y_ - 1 - pixelPosition.y_);
  554. auto xPos = pos.x_ * spacing_.x_ + patchWorldOrigin_.x_;
  555. auto zPos = pos.y_ * spacing_.z_ + patchWorldOrigin_.y_;
  556. Vector3 lPos(xPos, 0.0f, zPos);
  557. Vector3 wPos = node_->GetWorldTransform() * lPos;
  558. wPos.y_ = GetHeight(wPos);
  559. return wPos;
  560. }
  561. void Terrain::CreatePatchGeometry(TerrainPatch* patch)
  562. {
  563. URHO3D_PROFILE(CreatePatchGeometry);
  564. auto row = (unsigned)(patchSize_ + 1);
  565. VertexBuffer* vertexBuffer = patch->GetVertexBuffer();
  566. Geometry* geometry = patch->GetGeometry();
  567. Geometry* maxLodGeometry = patch->GetMaxLodGeometry();
  568. Geometry* occlusionGeometry = patch->GetOcclusionGeometry();
  569. if (vertexBuffer->GetVertexCount() != row * row)
  570. vertexBuffer->SetSize(row * row, MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1 | MASK_TANGENT);
  571. SharedArrayPtr<unsigned char> cpuVertexData(new unsigned char[row * row * sizeof(Vector3)]);
  572. SharedArrayPtr<unsigned char> occlusionCpuVertexData(new unsigned char[row * row * sizeof(Vector3)]);
  573. auto* vertexData = (float*)vertexBuffer->Lock(0, vertexBuffer->GetVertexCount());
  574. auto* positionData = (float*)cpuVertexData.Get();
  575. auto* occlusionData = (float*)occlusionCpuVertexData.Get();
  576. BoundingBox box;
  577. unsigned occlusionLevel = occlusionLodLevel_;
  578. if (occlusionLevel > numLodLevels_ - 1)
  579. occlusionLevel = numLodLevels_ - 1;
  580. if (vertexData)
  581. {
  582. const IntVector2& coords = patch->GetCoordinates();
  583. unsigned lodExpand = (1u << (occlusionLevel)) - 1;
  584. unsigned halfLodExpand = (1u << (occlusionLevel)) / 2;
  585. for (unsigned z = 0; z <= patchSize_; ++z)
  586. {
  587. for (unsigned x = 0; x <= patchSize_; ++x)
  588. {
  589. int xPos = coords.x_ * patchSize_ + x;
  590. int zPos = coords.y_ * patchSize_ + z;
  591. // Position
  592. Vector3 position((float)x * spacing_.x_, GetRawHeight(xPos, zPos), (float)z * spacing_.z_);
  593. *vertexData++ = position.x_;
  594. *vertexData++ = position.y_;
  595. *vertexData++ = position.z_;
  596. *positionData++ = position.x_;
  597. *positionData++ = position.y_;
  598. *positionData++ = position.z_;
  599. box.Merge(position);
  600. // For vertices that are part of the occlusion LOD, calculate the minimum height in the neighborhood
  601. // to prevent false positive occlusion due to inaccuracy between occlusion LOD & visible LOD
  602. float minHeight = position.y_;
  603. if (halfLodExpand > 0 && (x & lodExpand) == 0 && (z & lodExpand) == 0)
  604. {
  605. int minX = Max(xPos - halfLodExpand, 0);
  606. int maxX = Min(xPos + halfLodExpand, numVertices_.x_ - 1);
  607. int minZ = Max(zPos - halfLodExpand, 0);
  608. int maxZ = Min(zPos + halfLodExpand, numVertices_.y_ - 1);
  609. for (int nZ = minZ; nZ <= maxZ; ++nZ)
  610. {
  611. for (int nX = minX; nX <= maxX; ++nX)
  612. minHeight = Min(minHeight, GetRawHeight(nX, nZ));
  613. }
  614. }
  615. *occlusionData++ = position.x_;
  616. *occlusionData++ = minHeight;
  617. *occlusionData++ = position.z_;
  618. // Normal
  619. Vector3 normal = GetRawNormal(xPos, zPos);
  620. *vertexData++ = normal.x_;
  621. *vertexData++ = normal.y_;
  622. *vertexData++ = normal.z_;
  623. // Texture coordinate
  624. Vector2 texCoord((float)xPos / (float)(numVertices_.x_ - 1), 1.0f - (float)zPos / (float)(numVertices_.y_ - 1));
  625. *vertexData++ = texCoord.x_;
  626. *vertexData++ = texCoord.y_;
  627. // Tangent
  628. Vector3 xyz = (Vector3::RIGHT - normal * normal.DotProduct(Vector3::RIGHT)).Normalized();
  629. *vertexData++ = xyz.x_;
  630. *vertexData++ = xyz.y_;
  631. *vertexData++ = xyz.z_;
  632. *vertexData++ = 1.0f;
  633. }
  634. }
  635. vertexBuffer->Unlock();
  636. vertexBuffer->ClearDataLost();
  637. }
  638. patch->SetBoundingBox(box);
  639. if (drawRanges_.Size())
  640. {
  641. unsigned occlusionDrawRange = occlusionLevel << 4u;
  642. geometry->SetIndexBuffer(indexBuffer_);
  643. geometry->SetDrawRange(TRIANGLE_LIST, drawRanges_[0].first_, drawRanges_[0].second_, false);
  644. geometry->SetRawVertexData(cpuVertexData, MASK_POSITION);
  645. maxLodGeometry->SetIndexBuffer(indexBuffer_);
  646. maxLodGeometry->SetDrawRange(TRIANGLE_LIST, drawRanges_[0].first_, drawRanges_[0].second_, false);
  647. maxLodGeometry->SetRawVertexData(cpuVertexData, MASK_POSITION);
  648. occlusionGeometry->SetIndexBuffer(indexBuffer_);
  649. occlusionGeometry->SetDrawRange(TRIANGLE_LIST, drawRanges_[occlusionDrawRange].first_, drawRanges_[occlusionDrawRange].second_, false);
  650. occlusionGeometry->SetRawVertexData(occlusionCpuVertexData, MASK_POSITION);
  651. }
  652. patch->ResetLod();
  653. }
  654. void Terrain::UpdatePatchLod(TerrainPatch* patch)
  655. {
  656. Geometry* geometry = patch->GetGeometry();
  657. // All LOD levels except the coarsest have 16 versions for stitching
  658. unsigned lodLevel = patch->GetLodLevel();
  659. unsigned drawRangeIndex = lodLevel << 4u;
  660. if (lodLevel < numLodLevels_ - 1)
  661. {
  662. TerrainPatch* north = patch->GetNorthPatch();
  663. TerrainPatch* south = patch->GetSouthPatch();
  664. TerrainPatch* west = patch->GetWestPatch();
  665. TerrainPatch* east = patch->GetEastPatch();
  666. if (north && north->GetLodLevel() > lodLevel)
  667. drawRangeIndex |= STITCH_NORTH;
  668. if (south && south->GetLodLevel() > lodLevel)
  669. drawRangeIndex |= STITCH_SOUTH;
  670. if (west && west->GetLodLevel() > lodLevel)
  671. drawRangeIndex |= STITCH_WEST;
  672. if (east && east->GetLodLevel() > lodLevel)
  673. drawRangeIndex |= STITCH_EAST;
  674. }
  675. if (drawRangeIndex < drawRanges_.Size())
  676. geometry->SetDrawRange(TRIANGLE_LIST, drawRanges_[drawRangeIndex].first_, drawRanges_[drawRangeIndex].second_, false);
  677. }
  678. void Terrain::SetMaterialAttr(const ResourceRef& value)
  679. {
  680. auto* cache = GetSubsystem<ResourceCache>();
  681. SetMaterial(cache->GetResource<Material>(value.name_));
  682. }
  683. void Terrain::SetHeightMapAttr(const ResourceRef& value)
  684. {
  685. auto* cache = GetSubsystem<ResourceCache>();
  686. auto* image = cache->GetResource<Image>(value.name_);
  687. SetHeightMapInternal(image, false);
  688. }
  689. void Terrain::SetPatchSizeAttr(int value)
  690. {
  691. if (value < MIN_PATCH_SIZE || value > MAX_PATCH_SIZE || !IsPowerOfTwo((unsigned)value))
  692. return;
  693. if (value != patchSize_)
  694. {
  695. patchSize_ = value;
  696. recreateTerrain_ = true;
  697. }
  698. }
  699. void Terrain::SetMaxLodLevelsAttr(unsigned value)
  700. {
  701. value = Clamp(value, MIN_LOD_LEVELS, MAX_LOD_LEVELS);
  702. if (value != maxLodLevels_)
  703. {
  704. maxLodLevels_ = value;
  705. lastPatchSize_ = 0; // Force full recreate
  706. recreateTerrain_ = true;
  707. }
  708. }
  709. void Terrain::SetOcclusionLodLevelAttr(unsigned value)
  710. {
  711. if (value != occlusionLodLevel_)
  712. {
  713. occlusionLodLevel_ = value;
  714. lastPatchSize_ = 0; // Force full recreate
  715. recreateTerrain_ = true;
  716. }
  717. }
  718. ResourceRef Terrain::GetMaterialAttr() const
  719. {
  720. return GetResourceRef(material_, Material::GetTypeStatic());
  721. }
  722. ResourceRef Terrain::GetHeightMapAttr() const
  723. {
  724. return GetResourceRef(heightMap_, Image::GetTypeStatic());
  725. }
  726. void Terrain::CreateGeometry()
  727. {
  728. recreateTerrain_ = false;
  729. if (!node_)
  730. return;
  731. URHO3D_PROFILE(CreateTerrainGeometry);
  732. unsigned prevNumPatches = patches_.Size();
  733. // Determine number of LOD levels
  734. auto lodSize = (unsigned)patchSize_;
  735. numLodLevels_ = 1;
  736. while (lodSize > MIN_PATCH_SIZE && numLodLevels_ < maxLodLevels_)
  737. {
  738. lodSize >>= 1;
  739. ++numLodLevels_;
  740. }
  741. // Determine total terrain size
  742. patchWorldSize_ = Vector2(spacing_.x_ * (float)patchSize_, spacing_.z_ * (float)patchSize_);
  743. bool updateAll = false;
  744. if (heightMap_)
  745. {
  746. numPatches_ = IntVector2((heightMap_->GetWidth() - 1) / patchSize_, (heightMap_->GetHeight() - 1) / patchSize_);
  747. numVertices_ = IntVector2(numPatches_.x_ * patchSize_ + 1, numPatches_.y_ * patchSize_ + 1);
  748. patchWorldOrigin_ =
  749. Vector2(-0.5f * (float)numPatches_.x_ * patchWorldSize_.x_, -0.5f * (float)numPatches_.y_ * patchWorldSize_.y_);
  750. if (numVertices_ != lastNumVertices_ || lastSpacing_ != spacing_ || patchSize_ != lastPatchSize_)
  751. updateAll = true;
  752. auto newDataSize = (unsigned)(numVertices_.x_ * numVertices_.y_);
  753. // Create new height data if terrain size changed
  754. if (!heightData_ || updateAll)
  755. heightData_ = new float[newDataSize];
  756. // Ensure that the source (unsmoothed) data exists if smoothing is active
  757. if (smoothing_ && (!sourceHeightData_ || updateAll))
  758. {
  759. sourceHeightData_ = new float[newDataSize];
  760. updateAll = true;
  761. }
  762. else if (!smoothing_)
  763. sourceHeightData_.Reset();
  764. }
  765. else
  766. {
  767. numPatches_ = IntVector2::ZERO;
  768. numVertices_ = IntVector2::ZERO;
  769. patchWorldOrigin_ = Vector2::ZERO;
  770. heightData_.Reset();
  771. sourceHeightData_.Reset();
  772. }
  773. lastNumVertices_ = numVertices_;
  774. lastPatchSize_ = patchSize_;
  775. lastSpacing_ = spacing_;
  776. // Remove old patch nodes which are not needed
  777. if (updateAll)
  778. {
  779. URHO3D_PROFILE(RemoveOldPatches);
  780. PODVector<Node*> oldPatchNodes;
  781. node_->GetChildrenWithComponent<TerrainPatch>(oldPatchNodes);
  782. for (PODVector<Node*>::Iterator i = oldPatchNodes.Begin(); i != oldPatchNodes.End(); ++i)
  783. {
  784. bool nodeOk = false;
  785. Vector<String> coords = (*i)->GetName().Substring(6).Split('_');
  786. if (coords.Size() == 2)
  787. {
  788. int x = ToInt(coords[0]);
  789. int z = ToInt(coords[1]);
  790. if (x < numPatches_.x_ && z < numPatches_.y_)
  791. nodeOk = true;
  792. }
  793. if (!nodeOk)
  794. node_->RemoveChild(*i);
  795. }
  796. }
  797. // Keep track of which patches actually need an update
  798. PODVector<bool> dirtyPatches((unsigned)(numPatches_.x_ * numPatches_.y_));
  799. for (unsigned i = 0; i < dirtyPatches.Size(); ++i)
  800. dirtyPatches[i] = updateAll;
  801. patches_.Clear();
  802. if (heightMap_)
  803. {
  804. // Copy heightmap data
  805. const unsigned char* src = heightMap_->GetData();
  806. float* dest = smoothing_ ? sourceHeightData_ : heightData_;
  807. unsigned imgComps = heightMap_->GetComponents();
  808. unsigned imgRow = heightMap_->GetWidth() * imgComps;
  809. IntRect updateRegion(-1, -1, -1, -1);
  810. if (imgComps == 1)
  811. {
  812. URHO3D_PROFILE(CopyHeightData);
  813. for (int z = 0; z < numVertices_.y_; ++z)
  814. {
  815. for (int x = 0; x < numVertices_.x_; ++x)
  816. {
  817. float newHeight = (float)src[imgRow * (numVertices_.y_ - 1 - z) + x] * spacing_.y_;
  818. if (updateAll)
  819. *dest = newHeight;
  820. else
  821. {
  822. if (*dest != newHeight)
  823. {
  824. *dest = newHeight;
  825. GrowUpdateRegion(updateRegion, x, z);
  826. }
  827. }
  828. ++dest;
  829. }
  830. }
  831. }
  832. else
  833. {
  834. URHO3D_PROFILE(CopyHeightData);
  835. // If more than 1 component, use the green channel for more accuracy
  836. for (int z = 0; z < numVertices_.y_; ++z)
  837. {
  838. for (int x = 0; x < numVertices_.x_; ++x)
  839. {
  840. float newHeight = ((float)src[imgRow * (numVertices_.y_ - 1 - z) + imgComps * x] +
  841. (float)src[imgRow * (numVertices_.y_ - 1 - z) + imgComps * x + 1] / 256.0f) * spacing_.y_;
  842. if (updateAll)
  843. *dest = newHeight;
  844. else
  845. {
  846. if (*dest != newHeight)
  847. {
  848. *dest = newHeight;
  849. GrowUpdateRegion(updateRegion, x, z);
  850. }
  851. }
  852. ++dest;
  853. }
  854. }
  855. }
  856. // If updating a region of the heightmap, check which patches change
  857. if (!updateAll)
  858. {
  859. int lodExpand = 1u << (numLodLevels_ - 1);
  860. // Expand the right & bottom 1 pixel more, as patches share vertices at the edge
  861. updateRegion.left_ -= lodExpand;
  862. updateRegion.right_ += lodExpand + 1;
  863. updateRegion.top_ -= lodExpand;
  864. updateRegion.bottom_ += lodExpand + 1;
  865. int sX = Max(updateRegion.left_ / patchSize_, 0);
  866. int eX = Min(updateRegion.right_ / patchSize_, numPatches_.x_ - 1);
  867. int sY = Max(updateRegion.top_ / patchSize_, 0);
  868. int eY = Min(updateRegion.bottom_ / patchSize_, numPatches_.y_ - 1);
  869. for (int y = sY; y <= eY; ++y)
  870. {
  871. for (int x = sX; x <= eX; ++x)
  872. dirtyPatches[y * numPatches_.x_ + x] = true;
  873. }
  874. }
  875. patches_.Reserve((unsigned)(numPatches_.x_ * numPatches_.y_));
  876. bool enabled = IsEnabledEffective();
  877. {
  878. URHO3D_PROFILE(CreatePatches);
  879. // Create patches and set node transforms
  880. for (int z = 0; z < numPatches_.y_; ++z)
  881. {
  882. for (int x = 0; x < numPatches_.x_; ++x)
  883. {
  884. String nodeName = "Patch_" + String(x) + "_" + String(z);
  885. Node* patchNode = node_->GetChild(nodeName);
  886. if (!patchNode)
  887. {
  888. // Create the patch scene node as local and temporary so that it is not unnecessarily serialized to either
  889. // file or replicated over the network
  890. patchNode = node_->CreateTemporaryChild(nodeName, LOCAL);
  891. }
  892. patchNode->SetPosition(Vector3(patchWorldOrigin_.x_ + (float)x * patchWorldSize_.x_, 0.0f,
  893. patchWorldOrigin_.y_ + (float)z * patchWorldSize_.y_));
  894. auto* patch = patchNode->GetComponent<TerrainPatch>();
  895. if (!patch)
  896. {
  897. patch = patchNode->CreateComponent<TerrainPatch>();
  898. patch->SetOwner(this);
  899. patch->SetCoordinates(IntVector2(x, z));
  900. // Copy initial drawable parameters
  901. patch->SetEnabled(enabled);
  902. patch->SetMaterial(material_);
  903. patch->SetDrawDistance(drawDistance_);
  904. patch->SetShadowDistance(shadowDistance_);
  905. patch->SetLodBias(lodBias_);
  906. patch->SetViewMask(viewMask_);
  907. patch->SetLightMask(lightMask_);
  908. patch->SetShadowMask(shadowMask_);
  909. patch->SetZoneMask(zoneMask_);
  910. patch->SetMaxLights(maxLights_);
  911. patch->SetCastShadows(castShadows_);
  912. patch->SetOccluder(occluder_);
  913. patch->SetOccludee(occludee_);
  914. }
  915. patches_.Push(WeakPtr<TerrainPatch>(patch));
  916. }
  917. }
  918. }
  919. // Create the shared index data
  920. if (updateAll)
  921. CreateIndexData();
  922. // Create vertex data for patches. First update smoothing to ensure normals are calculated correctly across patch borders
  923. if (smoothing_)
  924. {
  925. URHO3D_PROFILE(UpdateSmoothing);
  926. for (unsigned i = 0; i < patches_.Size(); ++i)
  927. {
  928. if (dirtyPatches[i])
  929. {
  930. TerrainPatch* patch = patches_[i];
  931. const IntVector2& coords = patch->GetCoordinates();
  932. int startX = coords.x_ * patchSize_;
  933. int endX = startX + patchSize_;
  934. int startZ = coords.y_ * patchSize_;
  935. int endZ = startZ + patchSize_;
  936. for (int z = startZ; z <= endZ; ++z)
  937. {
  938. for (int x = startX; x <= endX; ++x)
  939. {
  940. float smoothedHeight = (
  941. GetSourceHeight(x - 1, z - 1) + GetSourceHeight(x, z - 1) * 2.0f + GetSourceHeight(x + 1, z - 1) +
  942. GetSourceHeight(x - 1, z) * 2.0f + GetSourceHeight(x, z) * 4.0f + GetSourceHeight(x + 1, z) * 2.0f +
  943. GetSourceHeight(x - 1, z + 1) + GetSourceHeight(x, z + 1) * 2.0f + GetSourceHeight(x + 1, z + 1)
  944. ) / 16.0f;
  945. heightData_[z * numVertices_.x_ + x] = smoothedHeight;
  946. }
  947. }
  948. }
  949. }
  950. }
  951. for (unsigned i = 0; i < patches_.Size(); ++i)
  952. {
  953. TerrainPatch* patch = patches_[i];
  954. if (dirtyPatches[i])
  955. {
  956. CreatePatchGeometry(patch);
  957. CalculateLodErrors(patch);
  958. }
  959. SetPatchNeighbors(patch);
  960. }
  961. }
  962. // Send event only if new geometry was generated, or the old was cleared
  963. if (patches_.Size() || prevNumPatches)
  964. {
  965. using namespace TerrainCreated;
  966. VariantMap& eventData = GetEventDataMap();
  967. eventData[P_NODE] = node_;
  968. node_->SendEvent(E_TERRAINCREATED, eventData);
  969. }
  970. }
  971. void Terrain::CreateIndexData()
  972. {
  973. URHO3D_PROFILE(CreateIndexData);
  974. PODVector<unsigned short> indices;
  975. drawRanges_.Clear();
  976. auto row = (unsigned)(patchSize_ + 1);
  977. /* Build index data for each LOD level. Each LOD level except the lowest can stitch to the next lower LOD from the edges:
  978. north, south, west, east, or any combination of them, requiring 16 different versions of each LOD level's index data
  979. Normal edge: Stitched edge:
  980. +----+----+ +---------+
  981. |\ |\ | |\ /|
  982. | \ | \ | | \ / |
  983. | \ | \ | | \ / |
  984. | \| \| | \ / |
  985. +----+----+ +----+----+
  986. */
  987. for (unsigned i = 0; i < numLodLevels_; ++i)
  988. {
  989. unsigned combinations = (i < numLodLevels_ - 1) ? 16 : 1;
  990. int skip = 1u << i;
  991. for (unsigned j = 0; j < combinations; ++j)
  992. {
  993. unsigned indexStart = indices.Size();
  994. int zStart = 0;
  995. int xStart = 0;
  996. int zEnd = patchSize_;
  997. int xEnd = patchSize_;
  998. if (j & STITCH_NORTH)
  999. zEnd -= skip;
  1000. if (j & STITCH_SOUTH)
  1001. zStart += skip;
  1002. if (j & STITCH_WEST)
  1003. xStart += skip;
  1004. if (j & STITCH_EAST)
  1005. xEnd -= skip;
  1006. // Build the main grid
  1007. for (int z = zStart; z < zEnd; z += skip)
  1008. {
  1009. for (int x = xStart; x < xEnd; x += skip)
  1010. {
  1011. indices.Push((unsigned short)((z + skip) * row + x));
  1012. indices.Push((unsigned short)(z * row + x + skip));
  1013. indices.Push((unsigned short)(z * row + x));
  1014. indices.Push((unsigned short)((z + skip) * row + x));
  1015. indices.Push((unsigned short)((z + skip) * row + x + skip));
  1016. indices.Push((unsigned short)(z * row + x + skip));
  1017. }
  1018. }
  1019. // Build the north edge
  1020. if (j & STITCH_NORTH)
  1021. {
  1022. int z = patchSize_ - skip;
  1023. for (int x = 0; x < patchSize_; x += skip * 2)
  1024. {
  1025. if (x > 0 || (j & STITCH_WEST) == 0)
  1026. {
  1027. indices.Push((unsigned short)((z + skip) * row + x));
  1028. indices.Push((unsigned short)(z * row + x + skip));
  1029. indices.Push((unsigned short)(z * row + x));
  1030. }
  1031. indices.Push((unsigned short)((z + skip) * row + x));
  1032. indices.Push((unsigned short)((z + skip) * row + x + 2 * skip));
  1033. indices.Push((unsigned short)(z * row + x + skip));
  1034. if (x < patchSize_ - skip * 2 || (j & STITCH_EAST) == 0)
  1035. {
  1036. indices.Push((unsigned short)((z + skip) * row + x + 2 * skip));
  1037. indices.Push((unsigned short)(z * row + x + 2 * skip));
  1038. indices.Push((unsigned short)(z * row + x + skip));
  1039. }
  1040. }
  1041. }
  1042. // Build the south edge
  1043. if (j & STITCH_SOUTH)
  1044. {
  1045. int z = 0;
  1046. for (int x = 0; x < patchSize_; x += skip * 2)
  1047. {
  1048. if (x > 0 || (j & STITCH_WEST) == 0)
  1049. {
  1050. indices.Push((unsigned short)((z + skip) * row + x));
  1051. indices.Push((unsigned short)((z + skip) * row + x + skip));
  1052. indices.Push((unsigned short)(z * row + x));
  1053. }
  1054. indices.Push((unsigned short)(z * row + x));
  1055. indices.Push((unsigned short)((z + skip) * row + x + skip));
  1056. indices.Push((unsigned short)(z * row + x + 2 * skip));
  1057. if (x < patchSize_ - skip * 2 || (j & STITCH_EAST) == 0)
  1058. {
  1059. indices.Push((unsigned short)((z + skip) * row + x + skip));
  1060. indices.Push((unsigned short)((z + skip) * row + x + 2 * skip));
  1061. indices.Push((unsigned short)(z * row + x + 2 * skip));
  1062. }
  1063. }
  1064. }
  1065. // Build the west edge
  1066. if (j & STITCH_WEST)
  1067. {
  1068. int x = 0;
  1069. for (int z = 0; z < patchSize_; z += skip * 2)
  1070. {
  1071. if (z > 0 || (j & STITCH_SOUTH) == 0)
  1072. {
  1073. indices.Push((unsigned short)(z * row + x));
  1074. indices.Push((unsigned short)((z + skip) * row + x + skip));
  1075. indices.Push((unsigned short)(z * row + x + skip));
  1076. }
  1077. indices.Push((unsigned short)((z + 2 * skip) * row + x));
  1078. indices.Push((unsigned short)((z + skip) * row + x + skip));
  1079. indices.Push((unsigned short)(z * row + x));
  1080. if (z < patchSize_ - skip * 2 || (j & STITCH_NORTH) == 0)
  1081. {
  1082. indices.Push((unsigned short)((z + 2 * skip) * row + x));
  1083. indices.Push((unsigned short)((z + 2 * skip) * row + x + skip));
  1084. indices.Push((unsigned short)((z + skip) * row + x + skip));
  1085. }
  1086. }
  1087. }
  1088. // Build the east edge
  1089. if (j & STITCH_EAST)
  1090. {
  1091. int x = patchSize_ - skip;
  1092. for (int z = 0; z < patchSize_; z += skip * 2)
  1093. {
  1094. if (z > 0 || (j & STITCH_SOUTH) == 0)
  1095. {
  1096. indices.Push((unsigned short)(z * row + x));
  1097. indices.Push((unsigned short)((z + skip) * row + x));
  1098. indices.Push((unsigned short)(z * row + x + skip));
  1099. }
  1100. indices.Push((unsigned short)((z + skip) * row + x));
  1101. indices.Push((unsigned short)((z + 2 * skip) * row + x + skip));
  1102. indices.Push((unsigned short)(z * row + x + skip));
  1103. if (z < patchSize_ - skip * 2 || (j & STITCH_NORTH) == 0)
  1104. {
  1105. indices.Push((unsigned short)((z + skip) * row + x));
  1106. indices.Push((unsigned short)((z + 2 * skip) * row + x));
  1107. indices.Push((unsigned short)((z + 2 * skip) * row + x + skip));
  1108. }
  1109. }
  1110. }
  1111. drawRanges_.Push(MakePair(indexStart, indices.Size() - indexStart));
  1112. }
  1113. }
  1114. indexBuffer_->SetSize(indices.Size(), false);
  1115. indexBuffer_->SetData(&indices[0]);
  1116. }
  1117. float Terrain::GetRawHeight(int x, int z) const
  1118. {
  1119. if (!heightData_)
  1120. return 0.0f;
  1121. x = Clamp(x, 0, numVertices_.x_ - 1);
  1122. z = Clamp(z, 0, numVertices_.y_ - 1);
  1123. return heightData_[z * numVertices_.x_ + x];
  1124. }
  1125. float Terrain::GetSourceHeight(int x, int z) const
  1126. {
  1127. if (!sourceHeightData_)
  1128. return 0.0f;
  1129. x = Clamp(x, 0, numVertices_.x_ - 1);
  1130. z = Clamp(z, 0, numVertices_.y_ - 1);
  1131. return sourceHeightData_[z * numVertices_.x_ + x];
  1132. }
  1133. float Terrain::GetLodHeight(int x, int z, unsigned lodLevel) const
  1134. {
  1135. unsigned offset = 1u << lodLevel;
  1136. auto xFrac = (float)(x % offset) / offset;
  1137. auto zFrac = (float)(z % offset) / offset;
  1138. float h1, h2, h3;
  1139. if (xFrac + zFrac >= 1.0f)
  1140. {
  1141. h1 = GetRawHeight(x + offset, z + offset);
  1142. h2 = GetRawHeight(x, z + offset);
  1143. h3 = GetRawHeight(x + offset, z);
  1144. xFrac = 1.0f - xFrac;
  1145. zFrac = 1.0f - zFrac;
  1146. }
  1147. else
  1148. {
  1149. h1 = GetRawHeight(x, z);
  1150. h2 = GetRawHeight(x + offset, z);
  1151. h3 = GetRawHeight(x, z + offset);
  1152. }
  1153. return h1 * (1.0f - xFrac - zFrac) + h2 * xFrac + h3 * zFrac;
  1154. }
  1155. Vector3 Terrain::GetRawNormal(int x, int z) const
  1156. {
  1157. float baseHeight = GetRawHeight(x, z);
  1158. float nSlope = GetRawHeight(x, z - 1) - baseHeight;
  1159. float neSlope = GetRawHeight(x + 1, z - 1) - baseHeight;
  1160. float eSlope = GetRawHeight(x + 1, z) - baseHeight;
  1161. float seSlope = GetRawHeight(x + 1, z + 1) - baseHeight;
  1162. float sSlope = GetRawHeight(x, z + 1) - baseHeight;
  1163. float swSlope = GetRawHeight(x - 1, z + 1) - baseHeight;
  1164. float wSlope = GetRawHeight(x - 1, z) - baseHeight;
  1165. float nwSlope = GetRawHeight(x - 1, z - 1) - baseHeight;
  1166. float up = 0.5f * (spacing_.x_ + spacing_.z_);
  1167. return (Vector3(0.0f, up, nSlope) +
  1168. Vector3(-neSlope, up, neSlope) +
  1169. Vector3(-eSlope, up, 0.0f) +
  1170. Vector3(-seSlope, up, -seSlope) +
  1171. Vector3(0.0f, up, -sSlope) +
  1172. Vector3(swSlope, up, -swSlope) +
  1173. Vector3(wSlope, up, 0.0f) +
  1174. Vector3(nwSlope, up, nwSlope)).Normalized();
  1175. }
  1176. void Terrain::CalculateLodErrors(TerrainPatch* patch)
  1177. {
  1178. URHO3D_PROFILE(CalculateLodErrors);
  1179. const IntVector2& coords = patch->GetCoordinates();
  1180. PODVector<float>& lodErrors = patch->GetLodErrors();
  1181. lodErrors.Clear();
  1182. lodErrors.Reserve(numLodLevels_);
  1183. int xStart = coords.x_ * patchSize_;
  1184. int zStart = coords.y_ * patchSize_;
  1185. int xEnd = xStart + patchSize_;
  1186. int zEnd = zStart + patchSize_;
  1187. for (unsigned i = 0; i < numLodLevels_; ++i)
  1188. {
  1189. float maxError = 0.0f;
  1190. int divisor = 1u << i;
  1191. if (i > 0)
  1192. {
  1193. for (int z = zStart; z <= zEnd; ++z)
  1194. {
  1195. for (int x = xStart; x <= xEnd; ++x)
  1196. {
  1197. if (x % divisor || z % divisor)
  1198. {
  1199. float error = Abs(GetLodHeight(x, z, i) - GetRawHeight(x, z));
  1200. maxError = Max(error, maxError);
  1201. }
  1202. }
  1203. }
  1204. // Set error to be at least same as (half vertex spacing x LOD) to prevent horizontal stretches getting too inaccurate
  1205. maxError = Max(maxError, 0.25f * (spacing_.x_ + spacing_.z_) * (float)(1u << i));
  1206. }
  1207. lodErrors.Push(maxError);
  1208. }
  1209. }
  1210. void Terrain::SetPatchNeighbors(TerrainPatch* patch)
  1211. {
  1212. if (!patch)
  1213. return;
  1214. const IntVector2& coords = patch->GetCoordinates();
  1215. patch->SetNeighbors(GetNeighborPatch(coords.x_, coords.y_ + 1), GetNeighborPatch(coords.x_, coords.y_ - 1),
  1216. GetNeighborPatch(coords.x_ - 1, coords.y_), GetNeighborPatch(coords.x_ + 1, coords.y_));
  1217. }
  1218. bool Terrain::SetHeightMapInternal(Image* image, bool recreateNow)
  1219. {
  1220. if (image && image->IsCompressed())
  1221. {
  1222. URHO3D_LOGERROR("Can not use a compressed image as a terrain heightmap");
  1223. return false;
  1224. }
  1225. // Unsubscribe from the reload event of previous image (if any), then subscribe to the new
  1226. if (heightMap_)
  1227. UnsubscribeFromEvent(heightMap_, E_RELOADFINISHED);
  1228. if (image)
  1229. SubscribeToEvent(image, E_RELOADFINISHED, URHO3D_HANDLER(Terrain, HandleHeightMapReloadFinished));
  1230. heightMap_ = image;
  1231. if (recreateNow)
  1232. CreateGeometry();
  1233. else
  1234. recreateTerrain_ = true;
  1235. return true;
  1236. }
  1237. void Terrain::HandleHeightMapReloadFinished(StringHash /*eventType*/, VariantMap& eventData)
  1238. {
  1239. CreateGeometry();
  1240. }
  1241. void Terrain::HandleNeighborTerrainCreated(StringHash /*eventType*/, VariantMap& eventData)
  1242. {
  1243. UpdateEdgePatchNeighbors();
  1244. }
  1245. void Terrain::UpdateEdgePatchNeighbors()
  1246. {
  1247. for (int x = 1; x < numPatches_.x_ - 1; ++x)
  1248. {
  1249. SetPatchNeighbors(GetPatch(x, 0));
  1250. SetPatchNeighbors(GetPatch(x, numPatches_.y_ - 1));
  1251. }
  1252. for (int z = 1; z < numPatches_.y_ - 1; ++z)
  1253. {
  1254. SetPatchNeighbors(GetPatch(0, z));
  1255. SetPatchNeighbors(GetPatch(numPatches_.x_ - 1, z));
  1256. }
  1257. SetPatchNeighbors(GetPatch(0, 0));
  1258. SetPatchNeighbors(GetPatch(numPatches_.x_ - 1, 0));
  1259. SetPatchNeighbors(GetPatch(0, numPatches_.y_ - 1));
  1260. SetPatchNeighbors(GetPatch(numPatches_.x_ - 1, numPatches_.y_ - 1));
  1261. }
  1262. }