Terrain.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Context.h"
  25. #include "DrawableEvents.h"
  26. #include "Geometry.h"
  27. #include "Image.h"
  28. #include "IndexBuffer.h"
  29. #include "Log.h"
  30. #include "Material.h"
  31. #include "Node.h"
  32. #include "Octree.h"
  33. #include "Profiler.h"
  34. #include "ResourceCache.h"
  35. #include "ResourceEvents.h"
  36. #include "Scene.h"
  37. #include "StringUtils.h"
  38. #include "Terrain.h"
  39. #include "TerrainPatch.h"
  40. #include "VertexBuffer.h"
  41. #include "DebugNew.h"
  42. OBJECTTYPESTATIC(Terrain);
  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 = 64;
  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. Terrain::Terrain(Context* context) :
  53. Component(context),
  54. indexBuffer_(new IndexBuffer(context)),
  55. spacing_(DEFAULT_SPACING),
  56. patchWorldSize_(Vector2::ZERO),
  57. patchWorldOrigin_(Vector2::ZERO),
  58. numVertices_(IntVector2::ZERO),
  59. numPatches_(IntVector2::ZERO),
  60. numLodLevels_(1),
  61. patchSize_(DEFAULT_PATCH_SIZE),
  62. visible_(true),
  63. castShadows_(false),
  64. occluder_(false),
  65. occludee_(true),
  66. viewMask_(DEFAULT_VIEWMASK),
  67. lightMask_(DEFAULT_LIGHTMASK),
  68. shadowMask_(DEFAULT_SHADOWMASK),
  69. zoneMask_(DEFAULT_ZONEMASK),
  70. drawDistance_(0.0f),
  71. shadowDistance_(0.0f),
  72. lodBias_(1.0f),
  73. maxLights_(0),
  74. recreateTerrain_(false)
  75. {
  76. indexBuffer_->SetShadowed(true);
  77. }
  78. Terrain::~Terrain()
  79. {
  80. }
  81. void Terrain::RegisterObject(Context* context)
  82. {
  83. context->RegisterFactory<Terrain>();
  84. ACCESSOR_ATTRIBUTE(Terrain, VAR_RESOURCEREF, "Height Map", GetHeightMapAttr, SetHeightMapAttr, ResourceRef, ResourceRef(Image::GetTypeStatic()), AM_DEFAULT);
  85. ACCESSOR_ATTRIBUTE(Terrain, VAR_RESOURCEREF, "Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()), AM_DEFAULT);
  86. ATTRIBUTE(Terrain, VAR_VECTOR3, "Vertex Spacing", spacing_, DEFAULT_SPACING, AM_DEFAULT);
  87. ACCESSOR_ATTRIBUTE(Terrain, VAR_INT, "Patch Size", GetPatchSize, SetPatchSizeAttr, int, DEFAULT_PATCH_SIZE, AM_DEFAULT);
  88. ACCESSOR_ATTRIBUTE(Terrain, VAR_BOOL, "Is Visible", IsVisible, SetVisible, bool, true, AM_DEFAULT);
  89. ACCESSOR_ATTRIBUTE(Terrain, VAR_BOOL, "Is Occluder", IsOccluder, SetOccluder, bool, false, AM_DEFAULT);
  90. ACCESSOR_ATTRIBUTE(Terrain, VAR_BOOL, "Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  91. ACCESSOR_ATTRIBUTE(Terrain, VAR_BOOL, "Cast Shadows", GetCastShadows, SetCastShadows, bool, false, AM_DEFAULT);
  92. ACCESSOR_ATTRIBUTE(Terrain, VAR_FLOAT, "Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  93. ACCESSOR_ATTRIBUTE(Terrain, VAR_FLOAT, "Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  94. ACCESSOR_ATTRIBUTE(Terrain, VAR_FLOAT, "LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
  95. ACCESSOR_ATTRIBUTE(Terrain, VAR_INT, "Max Lights", GetMaxLights, SetMaxLights, unsigned, 0, AM_DEFAULT);
  96. ACCESSOR_ATTRIBUTE(Terrain, VAR_INT, "View Mask", GetViewMask, SetViewMask, unsigned, DEFAULT_VIEWMASK, AM_DEFAULT);
  97. ACCESSOR_ATTRIBUTE(Terrain, VAR_INT, "Light Mask", GetLightMask, SetLightMask, unsigned, DEFAULT_LIGHTMASK, AM_DEFAULT);
  98. ACCESSOR_ATTRIBUTE(Terrain, VAR_INT, "Shadow Mask", GetShadowMask, SetShadowMask, unsigned, DEFAULT_SHADOWMASK, AM_DEFAULT);
  99. ACCESSOR_ATTRIBUTE(Terrain, VAR_INT, "Zone Mask", GetZoneMask, SetZoneMask, unsigned, DEFAULT_SHADOWMASK, AM_DEFAULT);
  100. }
  101. void Terrain::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  102. {
  103. Component::OnSetAttribute(attr, src);
  104. // Change of any non-accessor attribute requires recreation of the terrain
  105. if (!attr.accessor_)
  106. recreateTerrain_ = true;
  107. }
  108. void Terrain::ApplyAttributes()
  109. {
  110. if (recreateTerrain_)
  111. {
  112. CreateGeometry();
  113. recreateTerrain_ = false;
  114. }
  115. }
  116. void Terrain::SetSpacing(const Vector3& spacing)
  117. {
  118. if (spacing != spacing_)
  119. {
  120. spacing_ = spacing;
  121. CreateGeometry();
  122. MarkNetworkUpdate();
  123. }
  124. }
  125. void Terrain::SetPatchSize(int size)
  126. {
  127. if (size < MIN_PATCH_SIZE || size > MAX_PATCH_SIZE || !IsPowerOfTwo(size))
  128. return;
  129. if (size != patchSize_)
  130. {
  131. patchSize_ = size;
  132. CreateGeometry();
  133. MarkNetworkUpdate();
  134. }
  135. }
  136. bool Terrain::SetHeightMap(Image* image)
  137. {
  138. bool success = SetHeightMapInternal(image, true);
  139. MarkNetworkUpdate();
  140. return success;
  141. }
  142. void Terrain::SetMaterial(Material* material)
  143. {
  144. material_ = material;
  145. for (unsigned i = 0; i < patches_.Size(); ++i)
  146. {
  147. if (patches_[i])
  148. patches_[i]->SetMaterial(material);
  149. }
  150. MarkNetworkUpdate();
  151. }
  152. void Terrain::SetDrawDistance(float distance)
  153. {
  154. drawDistance_ = distance;
  155. for (unsigned i = 0; i < patches_.Size(); ++i)
  156. {
  157. if (patches_[i])
  158. patches_[i]->SetDrawDistance(distance);
  159. }
  160. MarkNetworkUpdate();
  161. }
  162. void Terrain::SetShadowDistance(float distance)
  163. {
  164. shadowDistance_ = distance;
  165. for (unsigned i = 0; i < patches_.Size(); ++i)
  166. {
  167. if (patches_[i])
  168. patches_[i]->SetShadowDistance(distance);
  169. }
  170. MarkNetworkUpdate();
  171. }
  172. void Terrain::SetLodBias(float bias)
  173. {
  174. lodBias_ = bias;
  175. for (unsigned i = 0; i < patches_.Size(); ++i)
  176. {
  177. if (patches_[i])
  178. patches_[i]->SetLodBias(bias);
  179. }
  180. MarkNetworkUpdate();
  181. }
  182. void Terrain::SetViewMask(unsigned mask)
  183. {
  184. viewMask_ = mask;
  185. for (unsigned i = 0; i < patches_.Size(); ++i)
  186. {
  187. if (patches_[i])
  188. patches_[i]->SetViewMask(mask);
  189. }
  190. MarkNetworkUpdate();
  191. }
  192. void Terrain::SetLightMask(unsigned mask)
  193. {
  194. lightMask_ = mask;
  195. for (unsigned i = 0; i < patches_.Size(); ++i)
  196. {
  197. if (patches_[i])
  198. patches_[i]->SetLightMask(mask);
  199. }
  200. MarkNetworkUpdate();
  201. }
  202. void Terrain::SetShadowMask(unsigned mask)
  203. {
  204. shadowMask_ = mask;
  205. for (unsigned i = 0; i < patches_.Size(); ++i)
  206. {
  207. if (patches_[i])
  208. patches_[i]->SetShadowMask(mask);
  209. }
  210. MarkNetworkUpdate();
  211. }
  212. void Terrain::SetZoneMask(unsigned mask)
  213. {
  214. zoneMask_ = mask;
  215. for (unsigned i = 0; i < patches_.Size(); ++i)
  216. {
  217. if (patches_[i])
  218. patches_[i]->SetZoneMask(mask);
  219. }
  220. MarkNetworkUpdate();
  221. }
  222. void Terrain::SetMaxLights(unsigned num)
  223. {
  224. maxLights_ = num;
  225. for (unsigned i = 0; i < patches_.Size(); ++i)
  226. {
  227. if (patches_[i])
  228. patches_[i]->SetMaxLights(num);
  229. }
  230. MarkNetworkUpdate();
  231. }
  232. void Terrain::SetVisible(bool enable)
  233. {
  234. visible_ = enable;
  235. for (unsigned i = 0; i < patches_.Size(); ++i)
  236. {
  237. if (patches_[i])
  238. patches_[i]->SetVisible(enable);
  239. }
  240. MarkNetworkUpdate();
  241. }
  242. void Terrain::SetCastShadows(bool enable)
  243. {
  244. castShadows_ = enable;
  245. for (unsigned i = 0; i < patches_.Size(); ++i)
  246. {
  247. if (patches_[i])
  248. patches_[i]->SetCastShadows(enable);
  249. }
  250. MarkNetworkUpdate();
  251. }
  252. void Terrain::SetOccluder(bool enable)
  253. {
  254. occluder_ = enable;
  255. for (unsigned i = 0; i < patches_.Size(); ++i)
  256. {
  257. if (patches_[i])
  258. patches_[i]->SetOccluder(enable);
  259. }
  260. MarkNetworkUpdate();
  261. }
  262. void Terrain::SetOccludee(bool enable)
  263. {
  264. occluder_ = enable;
  265. for (unsigned i = 0; i < patches_.Size(); ++i)
  266. {
  267. if (patches_[i])
  268. patches_[i]->SetOccludee(enable);
  269. }
  270. MarkNetworkUpdate();
  271. }
  272. Image* Terrain::GetHeightMap() const
  273. {
  274. return heightMap_;
  275. }
  276. Material* Terrain::GetMaterial() const
  277. {
  278. return material_;
  279. }
  280. TerrainPatch* Terrain::GetPatch(unsigned index) const
  281. {
  282. return index < patches_.Size() ? patches_[index] : (TerrainPatch*)0;
  283. }
  284. TerrainPatch* Terrain::GetPatch(int x, int z) const
  285. {
  286. if (x < 0 || x >= numPatches_.x_ || z < 0 || z >= numPatches_.y_)
  287. return 0;
  288. else
  289. return GetPatch(z * numPatches_.x_ + x);
  290. }
  291. float Terrain::GetHeight(const Vector3& worldPosition) const
  292. {
  293. if (node_)
  294. {
  295. Vector3 position = node_->GetWorldTransform().Inverse() * worldPosition;
  296. float xPos = (position.x_ - patchWorldOrigin_.x_) / spacing_.x_;
  297. float zPos = (position.z_ - patchWorldOrigin_.y_) / spacing_.z_;
  298. float xFrac = xPos - floorf(xPos);
  299. float zFrac = zPos - floorf(zPos);
  300. float h1, h2, h3;
  301. if (xFrac + zFrac >= 1.0f)
  302. {
  303. h1 = GetRawHeight((unsigned)xPos + 1, (unsigned)zPos + 1);
  304. h2 = GetRawHeight((unsigned)xPos, (unsigned)zPos + 1);
  305. h3 = GetRawHeight((unsigned)xPos + 1, (unsigned)zPos);
  306. xFrac = 1.0f - xFrac;
  307. zFrac = 1.0f - zFrac;
  308. }
  309. else
  310. {
  311. h1 = GetRawHeight((unsigned)xPos, (unsigned)zPos);
  312. h2 = GetRawHeight((unsigned)xPos + 1, (unsigned)zPos);
  313. h3 = GetRawHeight((unsigned)xPos, (unsigned)zPos + 1);
  314. }
  315. float h = h1 * (1.0f - xFrac - zFrac) + h2 * xFrac + h3 * zFrac;
  316. /// \todo This assumes that the terrain scene node is upright
  317. return node_->GetWorldScale().y_ * h + node_->GetWorldPosition().y_;
  318. }
  319. else
  320. return 0.0f;
  321. }
  322. void Terrain::CreatePatchGeometry(TerrainPatch* patch)
  323. {
  324. unsigned row = patchSize_ + 1;
  325. VertexBuffer* vertexBuffer = patch->GetVertexBuffer();
  326. Geometry* geometry = patch->GetGeometry();
  327. Geometry* maxLodGeometry = patch->GetMaxLodGeometry();
  328. if (vertexBuffer->GetVertexCount() != row * row)
  329. vertexBuffer->SetSize(row * row, MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1 | MASK_TANGENT);
  330. SharedArrayPtr<unsigned char> cpuVertexData(new unsigned char[row * row * sizeof(Vector3)]);
  331. float* vertexData = (float*)vertexBuffer->Lock(0, vertexBuffer->GetVertexCount());
  332. float* positionData = (float*)cpuVertexData.Get();
  333. BoundingBox box;
  334. if (vertexData)
  335. {
  336. const IntVector2& coords = patch->GetCoordinates();
  337. for (int z1 = 0; z1 <= patchSize_; ++z1)
  338. {
  339. for (int x1 = 0; x1 <= patchSize_; ++x1)
  340. {
  341. int xPos = coords.x_ * patchSize_ + x1;
  342. int zPos = coords.y_ * patchSize_ + z1;
  343. // Position
  344. Vector3 position((float)x1 * spacing_.x_, GetRawHeight(xPos, zPos), (float)z1 * spacing_.z_);
  345. *vertexData++ = position.x_;
  346. *vertexData++ = position.y_;
  347. *vertexData++ = position.z_;
  348. *positionData++ = position.x_;
  349. *positionData++ = position.y_;
  350. *positionData++ = position.z_;
  351. box.Merge(position);
  352. // Normal
  353. Vector3 normal = GetNormal(xPos, zPos);
  354. *vertexData++ = normal.x_;
  355. *vertexData++ = normal.y_;
  356. *vertexData++ = normal.z_;
  357. // Texture coordinate
  358. Vector2 texCoord((float)xPos / (float)numVertices_.x_, 1.0f - (float)zPos / (float)numVertices_.y_);
  359. *vertexData++ = texCoord.x_;
  360. *vertexData++ = texCoord.y_;
  361. // Tangent
  362. Vector3 xyz = (Vector3::RIGHT - normal * normal.DotProduct(Vector3::RIGHT)).Normalized();
  363. *vertexData++ = xyz.x_;
  364. *vertexData++ = xyz.y_;
  365. *vertexData++ = xyz.z_;
  366. *vertexData++ = 1.0f;
  367. }
  368. }
  369. vertexBuffer->Unlock();
  370. vertexBuffer->ClearDataLost();
  371. }
  372. patch->SetBoundingBox(box);
  373. if (drawRanges_.Size())
  374. {
  375. patch->ResetLod();
  376. geometry->SetIndexBuffer(indexBuffer_);
  377. geometry->SetDrawRange(TRIANGLE_LIST, drawRanges_[0].first_, drawRanges_[0].second_);
  378. geometry->SetRawVertexData(cpuVertexData, sizeof(Vector3), MASK_POSITION);
  379. maxLodGeometry->SetIndexBuffer(indexBuffer_);
  380. maxLodGeometry->SetDrawRange(TRIANGLE_LIST, drawRanges_[0].first_, drawRanges_[0].second_);
  381. maxLodGeometry->SetRawVertexData(cpuVertexData, sizeof(Vector3), MASK_POSITION);
  382. }
  383. }
  384. void Terrain::UpdatePatchLod(TerrainPatch* patch)
  385. {
  386. Geometry* geometry = patch->GetGeometry();
  387. // All LOD levels except the coarsest have 16 versions for stitching
  388. unsigned lodLevel = patch->GetLodLevel();
  389. unsigned drawRangeIndex = lodLevel << 4;
  390. if (lodLevel < numLodLevels_ - 1)
  391. {
  392. if (patch->GetNorthPatch() && patch->GetNorthPatch()->GetLodLevel() > lodLevel)
  393. drawRangeIndex |= STITCH_NORTH;
  394. if (patch->GetSouthPatch() && patch->GetSouthPatch()->GetLodLevel() > lodLevel)
  395. drawRangeIndex |= STITCH_SOUTH;
  396. if (patch->GetWestPatch() && patch->GetWestPatch()->GetLodLevel() > lodLevel)
  397. drawRangeIndex |= STITCH_WEST;
  398. if (patch->GetEastPatch() && patch->GetEastPatch()->GetLodLevel() > lodLevel)
  399. drawRangeIndex |= STITCH_EAST;
  400. }
  401. if (drawRangeIndex < drawRanges_.Size())
  402. geometry->SetDrawRange(TRIANGLE_LIST, drawRanges_[drawRangeIndex].first_, drawRanges_[drawRangeIndex].second_);
  403. }
  404. void Terrain::SetMaterialAttr(ResourceRef value)
  405. {
  406. ResourceCache* cache = GetSubsystem<ResourceCache>();
  407. SetMaterial(cache->GetResource<Material>(value.id_));
  408. }
  409. void Terrain::SetHeightMapAttr(ResourceRef value)
  410. {
  411. ResourceCache* cache = GetSubsystem<ResourceCache>();
  412. Image* image = cache->GetResource<Image>(value.id_);
  413. SetHeightMapInternal(image, false);
  414. }
  415. void Terrain::SetPatchSizeAttr(int value)
  416. {
  417. if (value < MIN_PATCH_SIZE || value > MAX_PATCH_SIZE || !IsPowerOfTwo(value))
  418. return;
  419. if (value != patchSize_)
  420. {
  421. patchSize_ = value;
  422. recreateTerrain_ = true;
  423. }
  424. }
  425. ResourceRef Terrain::GetMaterialAttr() const
  426. {
  427. return GetResourceRef(material_, Material::GetTypeStatic());
  428. }
  429. ResourceRef Terrain::GetHeightMapAttr() const
  430. {
  431. return GetResourceRef(heightMap_, Image::GetTypeStatic());
  432. }
  433. void Terrain::CreateGeometry()
  434. {
  435. recreateTerrain_ = false;
  436. if (!node_)
  437. return;
  438. PROFILE(CreateTerrainGeometry);
  439. unsigned prevNumPatches = patches_.Size();
  440. // Determine number of LOD levels
  441. unsigned lodSize = patchSize_;
  442. numLodLevels_ = 1;
  443. while (lodSize > MIN_PATCH_SIZE && numLodLevels_ < MAX_LOD_LEVELS)
  444. {
  445. lodSize >>= 1;
  446. ++numLodLevels_;
  447. }
  448. // Determine total terrain size
  449. patchWorldSize_ = Vector2(spacing_.x_ * (float)patchSize_, spacing_.z_ * (float)patchSize_);
  450. if (heightMap_)
  451. {
  452. numPatches_ = IntVector2((heightMap_->GetWidth() - 1) / patchSize_, (heightMap_->GetHeight() - 1) / patchSize_);
  453. numVertices_ = IntVector2(numPatches_.x_ * patchSize_ + 1, numPatches_.y_ * patchSize_ + 1);
  454. patchWorldOrigin_ = Vector2(-0.5f * (float)numPatches_.x_ * patchWorldSize_.x_, -0.5f * (float)numPatches_.y_ *
  455. patchWorldSize_.y_);
  456. heightData_ = new float[numVertices_.x_ * numVertices_.y_];
  457. }
  458. else
  459. {
  460. numPatches_ = IntVector2::ZERO;
  461. numVertices_ = IntVector2::ZERO;
  462. patchWorldOrigin_ = Vector2::ZERO;
  463. heightData_.Reset();
  464. }
  465. // Remove old patch nodes which are not needed
  466. PODVector<Node*> oldPatchNodes;
  467. node_->GetChildrenWithComponent<TerrainPatch>(oldPatchNodes);
  468. for (PODVector<Node*>::Iterator i = oldPatchNodes.Begin(); i != oldPatchNodes.End(); ++i)
  469. {
  470. bool nodeOk = false;
  471. Vector<String> coords = (*i)->GetName().Substring(6).Split('_');
  472. if (coords.Size() == 2)
  473. {
  474. int x = ToInt(coords[0]);
  475. int z = ToInt(coords[1]);
  476. if (x < numPatches_.x_ && z < numPatches_.y_)
  477. nodeOk = true;
  478. }
  479. if (!nodeOk)
  480. node_->RemoveChild(*i);
  481. }
  482. patches_.Clear();
  483. if (heightMap_)
  484. {
  485. // Copy heightmap data
  486. const unsigned char* src = heightMap_->GetData();
  487. float* dest = heightData_;
  488. unsigned imgComps = heightMap_->GetComponents();
  489. unsigned imgRow = heightMap_->GetWidth() * imgComps;
  490. for (int z = 0; z < numVertices_.y_; ++z)
  491. {
  492. for (int x = 0; x < numVertices_.x_; ++x)
  493. *dest++ = (float)src[imgRow * (numVertices_.y_ - 1 - z) + imgComps * x] * spacing_.y_;
  494. }
  495. // Create patches and set node transforms
  496. for (int z = 0; z < numPatches_.y_; ++z)
  497. {
  498. for (int x = 0; x < numPatches_.x_; ++x)
  499. {
  500. String nodeName = "Patch_" + String(x) + "_" + String(z);
  501. Node* patchNode = node_->GetChild(nodeName);
  502. if (!patchNode)
  503. patchNode = node_->CreateChild(nodeName, LOCAL);
  504. patchNode->SetPosition(Vector3(patchWorldOrigin_.x_ + (float)x * patchWorldSize_.x_, 0.0f, patchWorldOrigin_.y_ +
  505. (float)z * patchWorldSize_.y_));
  506. TerrainPatch* patch = patchNode->GetOrCreateComponent<TerrainPatch>();
  507. patch->SetOwner(this);
  508. patch->SetCoordinates(IntVector2(x, z));
  509. // Copy initial drawable parameters
  510. patch->SetMaterial(material_);
  511. patch->SetDrawDistance(drawDistance_);
  512. patch->SetShadowDistance(shadowDistance_);
  513. patch->SetLodBias(lodBias_);
  514. patch->SetViewMask(viewMask_);
  515. patch->SetLightMask(lightMask_);
  516. patch->SetShadowMask(shadowMask_);
  517. patch->SetZoneMask(zoneMask_);
  518. patch->SetMaxLights(maxLights_);
  519. patch->SetVisible(visible_);
  520. patch->SetCastShadows(castShadows_);
  521. patch->SetOccluder(occluder_);
  522. patch->SetOccludee(occludee_);
  523. patches_.Push(WeakPtr<TerrainPatch>(patch));
  524. }
  525. }
  526. // Create the shared index data
  527. CreateIndexData();
  528. // Create vertex data for patches
  529. for (Vector<WeakPtr<TerrainPatch> >::Iterator i = patches_.Begin(); i != patches_.End(); ++i)
  530. {
  531. CreatePatchGeometry(*i);
  532. CalculateLodErrors(*i);
  533. SetNeighbors(*i);
  534. }
  535. }
  536. // Send event only if new geometry was generated, or the old was cleared
  537. if (patches_.Size() || prevNumPatches)
  538. {
  539. using namespace TerrainCreated;
  540. VariantMap eventData;
  541. eventData[P_NODE] = (void*)node_;
  542. node_->SendEvent(E_TERRAINCREATED, eventData);
  543. }
  544. }
  545. void Terrain::CreateIndexData()
  546. {
  547. PODVector<unsigned short> indices;
  548. drawRanges_.Clear();
  549. unsigned row = patchSize_ + 1;
  550. for (unsigned i = 0; i < numLodLevels_; ++i)
  551. {
  552. unsigned combinations = (i < numLodLevels_ - 1) ? 16 : 1;
  553. int skip = 1 << i;
  554. for (unsigned j = 0; j < combinations; ++j)
  555. {
  556. unsigned indexStart = indices.Size();
  557. int zStart = 0;
  558. int xStart = 0;
  559. int zEnd = patchSize_;
  560. int xEnd = patchSize_;
  561. if (j & STITCH_NORTH)
  562. zEnd -= skip;
  563. if (j & STITCH_SOUTH)
  564. zStart += skip;
  565. if (j & STITCH_WEST)
  566. xStart += skip;
  567. if (j & STITCH_EAST)
  568. xEnd -= skip;
  569. // Build the main grid
  570. for (int z = zStart; z < zEnd; z += skip)
  571. {
  572. for (int x = xStart; x < xEnd; x += skip)
  573. {
  574. indices.Push((z + skip) * row + x);
  575. indices.Push(z * row + x + skip);
  576. indices.Push(z * row + x);
  577. indices.Push((z + skip) * row + x);
  578. indices.Push((z + skip) * row + x + skip);
  579. indices.Push(z * row + x + skip);
  580. }
  581. }
  582. // Build the north edge
  583. if (j & STITCH_NORTH)
  584. {
  585. int z = patchSize_ - skip;
  586. for (int x = 0; x < patchSize_; x += skip * 2)
  587. {
  588. if (x > 0 || (j & STITCH_WEST) == 0)
  589. {
  590. indices.Push((z + skip) * row + x);
  591. indices.Push(z * row + x + skip);
  592. indices.Push(z * row + x);
  593. }
  594. indices.Push((z + skip) * row + x);
  595. indices.Push((z + skip) * row + x + 2 * skip);
  596. indices.Push(z * row + x + skip);
  597. if (x < patchSize_ - skip * 2 || (j & STITCH_EAST) == 0)
  598. {
  599. indices.Push((z + skip) * row + x + 2 * skip);
  600. indices.Push(z * row + x + 2 * skip);
  601. indices.Push(z * row + x + skip);
  602. }
  603. }
  604. }
  605. // Build the south edge
  606. if (j & STITCH_SOUTH)
  607. {
  608. int z = 0;
  609. for (int x = 0; x < patchSize_; x += skip * 2)
  610. {
  611. if (x > 0 || (j & STITCH_WEST) == 0)
  612. {
  613. indices.Push((z + skip) * row + x);
  614. indices.Push((z + skip) * row + x + skip);
  615. indices.Push(z * row + x);
  616. }
  617. indices.Push(z * row + x);
  618. indices.Push((z + skip) * row + x + skip);
  619. indices.Push(z * row + x + 2 * skip);
  620. if (x < patchSize_ - skip * 2 || (j & STITCH_EAST) == 0)
  621. {
  622. indices.Push((z + skip) * row + x + skip);
  623. indices.Push((z + skip) * row + x + 2 * skip);
  624. indices.Push(z * row + x + 2 * skip);
  625. }
  626. }
  627. }
  628. // Build the west edge
  629. if (j & STITCH_WEST)
  630. {
  631. int x = 0;
  632. for (int z = 0; z < patchSize_; z += skip * 2)
  633. {
  634. if (z > 0 || (j & STITCH_SOUTH) == 0)
  635. {
  636. indices.Push(z * row + x);
  637. indices.Push((z + skip) * row + x + skip);
  638. indices.Push(z * row + x + skip);
  639. }
  640. indices.Push((z + 2 * skip) * row + x);
  641. indices.Push((z + skip) * row + x + skip);
  642. indices.Push(z * row + x);
  643. if (x < patchSize_ - skip * 2 || (j & STITCH_NORTH) == 0)
  644. {
  645. indices.Push((z + 2 * skip) * row + x);
  646. indices.Push((z + 2 * skip) * row + x + skip);
  647. indices.Push((z + skip) * row + x + skip);
  648. }
  649. }
  650. }
  651. // Build the east edge
  652. if (j & STITCH_EAST)
  653. {
  654. int x = patchSize_ - skip;
  655. for (int z = 0; z < patchSize_; z += skip * 2)
  656. {
  657. if (z > 0 || (j & STITCH_SOUTH) == 0)
  658. {
  659. indices.Push(z * row + x);
  660. indices.Push((z + skip) * row + x);
  661. indices.Push(z * row + x + skip);
  662. }
  663. indices.Push((z + skip) * row + x);
  664. indices.Push((z + 2 * skip) * row + x + skip);
  665. indices.Push(z * row + x + skip);
  666. if (z < patchSize_ - skip * 2 || (j & STITCH_NORTH) == 0)
  667. {
  668. indices.Push((z + skip) * row + x);
  669. indices.Push((z + 2 * skip) * row + x);
  670. indices.Push((z + 2 * skip) * row + x + skip);
  671. }
  672. }
  673. }
  674. drawRanges_.Push(MakePair(indexStart, indices.Size() - indexStart));
  675. }
  676. }
  677. indexBuffer_->SetSize(indices.Size(), false);
  678. unsigned short* indexData = (unsigned short*)indexBuffer_->Lock(0, indices.Size());
  679. if (indexData)
  680. {
  681. memcpy(indexData, &indices[0], indices.Size() * sizeof(unsigned short));
  682. indexBuffer_->Unlock();
  683. }
  684. }
  685. float Terrain::GetRawHeight(int x, int z) const
  686. {
  687. if (!heightData_)
  688. return 0.0f;
  689. x = Clamp(x, 0, numVertices_.x_ - 1);
  690. z = Clamp(z, 0, numVertices_.y_ - 1);
  691. return heightData_[z * numVertices_.x_ + x];
  692. }
  693. float Terrain::GetLodHeight(int x, int z, unsigned lodLevel) const
  694. {
  695. unsigned offset = 1 << lodLevel;
  696. float divisor = (float)offset;
  697. float xFrac = (float)(x % offset) / divisor;
  698. float zFrac = (float)(x % offset) / divisor;
  699. float h1, h2, h3;
  700. if (xFrac + zFrac >= 1.0f)
  701. {
  702. h1 = GetRawHeight(x + offset, z + offset);
  703. h2 = GetRawHeight(x, z + offset);
  704. h3 = GetRawHeight(x + offset, z);
  705. xFrac = 1.0f - xFrac;
  706. zFrac = 1.0f - zFrac;
  707. }
  708. else
  709. {
  710. h1 = GetRawHeight(x, z);
  711. h2 = GetRawHeight(x + offset, z);
  712. h3 = GetRawHeight(x, z + offset);
  713. }
  714. return h1 * (1.0f - xFrac - zFrac) + h2 * xFrac + h3 * zFrac;
  715. }
  716. Vector3 Terrain::GetNormal(int x, int z) const
  717. {
  718. float baseHeight = GetRawHeight(x, z);
  719. float nSlope = GetRawHeight(x, z - 1) - baseHeight;
  720. float neSlope = GetRawHeight(x + 1, z - 1) - baseHeight;
  721. float eSlope = GetRawHeight(x + 1, z) - baseHeight;
  722. float seSlope = GetRawHeight(x + 1, z + 1) - baseHeight;
  723. float sSlope = GetRawHeight(x, z + 1) - baseHeight;
  724. float swSlope = GetRawHeight(x - 1, z + 1) - baseHeight;
  725. float wSlope = GetRawHeight(x - 1, z) - baseHeight;
  726. float nwSlope = GetRawHeight(x - 1, z - 1) - baseHeight;
  727. float up = 0.5f * (spacing_.x_ + spacing_.z_);
  728. return (Vector3(0.0f, up, nSlope) +
  729. Vector3(-neSlope, up, neSlope) +
  730. Vector3(-eSlope, up, 0.0f) +
  731. Vector3(-seSlope, up, -seSlope) +
  732. Vector3(0.0f, up, -sSlope) +
  733. Vector3(swSlope, up, -swSlope) +
  734. Vector3(wSlope, up, 0.0f) +
  735. Vector3(nwSlope, up, nwSlope)).Normalized();
  736. }
  737. void Terrain::CalculateLodErrors(TerrainPatch* patch)
  738. {
  739. PROFILE(CalculateLodErrors);
  740. const IntVector2& coords = patch->GetCoordinates();
  741. PODVector<float>& lodErrors = patch->GetLodErrors();
  742. lodErrors.Clear();
  743. int xStart = coords.x_ * patchSize_;
  744. int zStart = coords.y_ * patchSize_;
  745. int xEnd = xStart + patchSize_;
  746. int zEnd = zStart + patchSize_;
  747. for (unsigned i = 0; i < numLodLevels_; ++i)
  748. {
  749. float maxError = 0.0f;
  750. int divisor = 1 << i;
  751. if (i > 0)
  752. {
  753. for (int z = zStart; z <= zEnd; ++z)
  754. {
  755. for (int x = xStart; x <= xEnd; ++x)
  756. {
  757. if (x % divisor || z % divisor)
  758. {
  759. float error = Abs(GetLodHeight(x, z, i) - GetRawHeight(x, z));
  760. maxError = Max(error, maxError);
  761. }
  762. }
  763. }
  764. // Set error to be at least same as (half vertex spacing x LOD) to prevent horizontal stretches getting too inaccurate
  765. maxError = Max(maxError, 0.25f * (spacing_.x_ + spacing_.z_) * (float)(1 << i));
  766. }
  767. lodErrors.Push(maxError);
  768. }
  769. }
  770. void Terrain::SetNeighbors(TerrainPatch* patch)
  771. {
  772. const IntVector2& coords = patch->GetCoordinates();
  773. patch->SetNeighbors(GetPatch(coords.x_, coords.y_ + 1), GetPatch(coords.x_, coords.y_ - 1),
  774. GetPatch(coords.x_ - 1, coords.y_), GetPatch(coords.x_ + 1, coords.y_));
  775. }
  776. bool Terrain::SetHeightMapInternal(Image* image, bool recreateNow)
  777. {
  778. if (image && image->IsCompressed())
  779. {
  780. LOGERROR("Can not use a compressed image as a terrain heightmap");
  781. return false;
  782. }
  783. // Unsubscribe from the reload event of previous image (if any), then subscribe to the new
  784. if (heightMap_)
  785. UnsubscribeFromEvent(heightMap_, E_RELOADFINISHED);
  786. if (image)
  787. SubscribeToEvent(image, E_RELOADFINISHED, HANDLER(Terrain, HandleHeightMapReloadFinished));
  788. heightMap_ = image;
  789. if (recreateNow)
  790. CreateGeometry();
  791. else
  792. recreateTerrain_ = true;
  793. return true;
  794. }
  795. void Terrain::HandleHeightMapReloadFinished(StringHash eventType, VariantMap& eventData)
  796. {
  797. CreateGeometry();
  798. }