Terrain.cpp 41 KB

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