Terrain.cpp 43 KB

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