Terrain.cpp 44 KB

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