Terrain.cpp 32 KB

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