Terrain.cpp 33 KB

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