Terrain.cpp 50 KB

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