Terrain.cpp 34 KB

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