Terrain.cpp 40 KB

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