CCTerrain.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. /****************************************************************************
  2. Copyright (c) 2015-2016 Chukong Technologies Inc.
  3. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #ifndef CC_TERRAIN_H
  22. #define CC_TERRAIN_H
  23. #include <vector>
  24. #include "2d/CCNode.h"
  25. #include "2d/CCCamera.h"
  26. #include "renderer/CCTexture2D.h"
  27. #include "renderer/CCCustomCommand.h"
  28. #include "renderer/CCRenderState.h"
  29. #include "3d/CCAABB.h"
  30. #include "3d/CCRay.h"
  31. #include "base/CCEventListenerCustom.h"
  32. #include "base/CCEventDispatcher.h"
  33. NS_CC_BEGIN
  34. /**
  35. * @addtogroup _3d
  36. * @{
  37. */
  38. /**
  39. * the maximum amount of the chunks
  40. **/
  41. #define MAX_CHUNKES 256
  42. /**
  43. * Terrain
  44. * Defines a Terrain that is capable of rendering large landscapes from 2D heightmap images.
  45. * Terrains can be constructed from several different internal formats heightmap sources:
  46. * 1. RGB888
  47. * 2. RGBA8888
  48. * 3. Luminance(gray-scale)8
  49. *
  50. * Terrain use TerrainData struct to initialize.the TerrainData struct warp
  51. * all parameters that Terrain initialization need.
  52. * TerrainData provide several handy constructor for users
  53. *
  54. * Surface detail is provided via texture splatting, where multiple Detail texture layers can be added
  55. * along with alpha map to define how different Detail texture blend with each other. These DetailTexture
  56. * can be defined in TerrainData. The number of supported Detail texture is Four. although typically 2-3 levels is
  57. * sufficient. For simple usage ,surface detail also is provided via simple Texture.
  58. *
  59. * Internally, Terrain is divide into smaller, more manageable chunks, which can be culled
  60. * separately for more efficient rendering. The size of the terrain chunks can be controlled
  61. * via the chunkSize property in TerrainData.
  62. *
  63. * Chunks are managed under the QuadTree.As DE FACTO terminal Node of the QuadTree;
  64. * let us cull chunks efficiently to reduce drawCall amount And reduce the VBOs'Size that pass to the GPU.
  65. *
  66. * Level of detail (LOD) is supported using a technique that is similar to texture mipmapping -- called GeoMapping.
  67. * A distance-to-camera based test used to decide
  68. * the appropriate LOD for a terrain chunk. The number of LOD levels is 0 by default (which
  69. * means only the base level is used),the maximum number of LOD levels is 4. Of course ,you can hack the value individually.
  70. *
  71. * Finally, when LOD is enabled, cracks can begin to appear between terrain Chunks of
  72. * different LOD levels. An acceptable solution might be to simply reduce the lower LOD(high detail,smooth) chunks border,
  73. * And let the higher LOD(rough) chunks to seamlessly connect it.
  74. *
  75. * We can use ray-terrain intersection to pick a point of the terrain;
  76. * Also we can get an arbitrary point of the terrain's height and normal vector for convenience .
  77. **/
  78. class CC_DLL Terrain : public Node
  79. {
  80. public:
  81. /**the crack fix type. use to fix the gaps between different LOD chunks */
  82. enum class CrackFixedType{
  83. SKIRT,
  84. INCREASE_LOWER,
  85. };
  86. /**
  87. *DetailMap
  88. *this struct maintain a detail map data ,including source file ,detail size.
  89. *the DetailMap can use for terrain splatting
  90. **/
  91. struct CC_DLL DetailMap{
  92. /*Constructors*/
  93. DetailMap();
  94. DetailMap(const std::string& detailMapSrc, float size = 35);
  95. /*detail Image source file path*/
  96. std::string _detailMapSrc;
  97. /*detailMapSize determine how many tiles that Terrain represent*/
  98. float _detailMapSize;
  99. };
  100. /**
  101. * Triangle
  102. */
  103. struct Triangle
  104. {
  105. Triangle(const Vec3& p1, const Vec3& p2, const Vec3& p3);
  106. bool getIntersectPoint(const Ray& ray, Vec3& intersectPoint) const;
  107. /** @deprecated Use getIntersectPoint instead. */
  108. CC_DEPRECATED_ATTRIBUTE bool getInsterctPoint(const Ray& ray, Vec3& interScetPoint) const;
  109. void transform(const Mat4& matrix);
  110. Vec3 _p1, _p2, _p3;
  111. };
  112. /**
  113. *TerrainData
  114. *This TerrainData struct warp all parameter that Terrain need to create
  115. */
  116. struct CC_DLL TerrainData
  117. {
  118. /**empty constructor*/
  119. TerrainData();
  120. /**constructor, this constructor construct a simple terrain which only have 1 detailmap*/
  121. TerrainData(const std::string& heightMapsrc, const std::string& textureSrc, const Size & chunksize = Size(32,32), float mapHeight = 2, float mapScale = 0.1);
  122. /**constructor, this constructor construct a terrain which have 4 detailmaps, 1 alpha map*/
  123. TerrainData(const std::string& heightMapsrc, const std::string& alphamap, const DetailMap& detail1,const DetailMap& detail2, const DetailMap& detail3, const DetailMap& detail4, const Size & chunksize = Size(32,32), float mapHeight = 2, float mapScale = 0.1);
  124. /**constructor, this constructor construct a terrain which have 3 detailmaps, 1 alpha map*/
  125. TerrainData(const std::string& heightMapsrc, const std::string& alphamap, const DetailMap& detail1,const DetailMap& detail2, const DetailMap& detail3, const Size & chunksize = Size(32,32), float mapHeight = 2, float mapScale = 0.1);
  126. /**
  127. *determine the chunk size,chunk is the minimal subdivision of the Terrain
  128. */
  129. Size _chunkSize;
  130. /**height Map source path*/
  131. std::string _heightMapSrc;
  132. /**the source path of the alpha map*/
  133. std::string _alphaMapSrc;
  134. /**detail maps*/
  135. DetailMap _detailMaps[4];
  136. /**terrain Maximum height*/
  137. float _mapHeight;
  138. /**terrain scale factor,you can combine setScale later.*/
  139. float _mapScale;
  140. /**the amount of detailmap*/
  141. int _detailMapAmount;
  142. /**the skirt height ratio, only effect when terrain use skirt to fix crack*/
  143. float _skirtHeightRatio;
  144. };
  145. private:
  146. struct ChunkIndices
  147. {
  148. GLuint _indices;
  149. unsigned short _size;
  150. };
  151. struct ChunkLODIndices
  152. {
  153. int _relativeLod[5];
  154. ChunkIndices _chunkIndices;
  155. };
  156. struct ChunkLODIndicesSkirt
  157. {
  158. int _selfLod;
  159. ChunkIndices _chunkIndices;
  160. };
  161. /*
  162. *terrain vertices internal data format
  163. **/
  164. struct CC_DLL TerrainVertexData
  165. {
  166. /*constructor*/
  167. TerrainVertexData(){};
  168. TerrainVertexData(const Vec3& v1, const Tex2F& v2)
  169. {
  170. _position = v1;
  171. _texcoord = v2;
  172. }
  173. /*the vertex's attributes*/
  174. cocos2d::Vec3 _position;
  175. cocos2d::Tex2F _texcoord;
  176. cocos2d::Vec3 _normal;
  177. };
  178. struct CC_DLL QuadTree;
  179. /*
  180. *the terminal node of quad, use to subdivision terrain mesh and LOD
  181. **/
  182. struct Chunk
  183. {
  184. /**Constructor*/
  185. Chunk();
  186. /**destructor*/
  187. ~Chunk();
  188. /*vertices*/
  189. std::vector<TerrainVertexData> _originalVertices;
  190. /*LOD indices*/
  191. struct LOD{
  192. std::vector<GLushort> _indices;
  193. };
  194. GLuint _vbo;
  195. ChunkIndices _chunkIndices;
  196. /**we now support four levels of detail*/
  197. LOD _lod[4];
  198. /**AABB in local space*/
  199. AABB _aabb;
  200. /**setup Chunk data*/
  201. void generate(int map_width, int map_height, int m, int n, const unsigned char * data);
  202. /**calculateAABB*/
  203. void calculateAABB();
  204. /**internal use draw function*/
  205. void bindAndDraw();
  206. /**finish opengl setup*/
  207. void finish();
  208. /*use linear-sample vertices for LOD mesh*/
  209. void updateVerticesForLOD();
  210. /*updateIndices */
  211. void updateIndicesLOD();
  212. void updateIndicesLODSkirt();
  213. /**calculate the average slop of chunk*/
  214. void calculateSlope();
  215. bool getIntersectPointWithRay(const Ray& ray, Vec3& intersectPoint);
  216. /** @deprecated Use getIntersectPointWithRay instead. */
  217. CC_DEPRECATED_ATTRIBUTE bool getInsterctPointWithRay(const Ray& ray, Vec3& intersectPoint);
  218. /**current LOD of the chunk*/
  219. int _currentLod;
  220. int _oldLod;
  221. int _neighborOldLOD[4];
  222. /*the left,right,front,back neighbors*/
  223. Chunk * _left;
  224. Chunk * _right;
  225. Chunk * _front;
  226. Chunk * _back;
  227. QuadTree * _parent;
  228. /**the position X in terrain space*/
  229. int _posX;
  230. /**the position Y in terrain space*/
  231. int _posY;
  232. /**parent terrain*/
  233. Terrain * _terrain;
  234. /**chunk size*/
  235. Size _size;
  236. /**chunk's estimated slope*/
  237. float _slope;
  238. std::vector<TerrainVertexData> _currentVertices;
  239. std::vector<Triangle> _trianglesList;
  240. };
  241. /**
  242. *QuadTree
  243. * @brief use to hierarchically frustum culling and set LOD
  244. **/
  245. struct CC_DLL QuadTree
  246. {
  247. /**constructor*/
  248. QuadTree(int x, int y, int width, int height, Terrain * terrain);
  249. /**destructor*/
  250. ~QuadTree();
  251. /**recursively draw*/
  252. void draw();
  253. /**recursively set itself and its children is need to draw*/
  254. void resetNeedDraw(bool value);
  255. /**recursively potential visible culling*/
  256. void cullByCamera(const Camera * camera, const Mat4 & worldTransform);
  257. /**precalculate the AABB(In world space) of each quad*/
  258. void preCalculateAABB(const Mat4 & worldTransform);
  259. QuadTree * _tl;
  260. QuadTree * _tr;
  261. QuadTree * _bl;
  262. QuadTree * _br;
  263. /**A flag present current quadTree node whether a terminal node,the terminal node is de facto the chunk*/
  264. bool _isTerminal;
  265. Chunk * _chunk;
  266. int _posX;
  267. int _posY;
  268. int _height;
  269. int _width;
  270. QuadTree * _parent;
  271. /**AABB's cache (in local space)*/
  272. AABB _localAABB;
  273. /**AABB's cache (in world space)*/
  274. AABB _worldSpaceAABB;
  275. Terrain * _terrain;
  276. /** a flag determine whether a quadTree node need draw*/
  277. bool _needDraw;
  278. };
  279. friend QuadTree;
  280. friend Chunk;
  281. public:
  282. /** set light map texture */
  283. void setLightMap(const std::string& fileName);
  284. /**
  285. set directional light for the terrain
  286. @param lightDir The direction of directional light, Note that lightDir is in the terrain's local space. Most of the time terrain is placed at (0,0,0) and without rotation, so lightDir is also in the world space.
  287. */
  288. void setLightDir(const Vec3& lightDir);
  289. /*init function*/
  290. /**initialize all Properties which terrain need */
  291. bool initProperties();
  292. /**initialize heightMap data */
  293. bool initHeightMap(const std::string& heightMap);
  294. /**initialize alphaMap ,detailMaps textures*/
  295. bool initTextures();
  296. /**create entry*/
  297. static Terrain * create(TerrainData &parameter, CrackFixedType fixedType = CrackFixedType::INCREASE_LOWER);
  298. /**get specified position's height mapping to the terrain,use bi-linear interpolation method
  299. * @param x the X position
  300. * @param z the Z position
  301. * @param normal the specified position's normal vector in terrain . if this argument is NULL or nullptr,Normal calculation shall be skip.
  302. * @return the height value of the specified position of the terrain, if the (X,Z) position is out of the terrain bounds,it shall return 0;
  303. **/
  304. float getHeight(float x, float z, Vec3 * normal= nullptr) const;
  305. /**get specified position's height mapping to the terrain,use bi-linear interpolation method
  306. * @param pos the position (X,Z)
  307. * @param normal the specified position's normal vector in terrain . if this argument is NULL or nullptr,Normal calculation shall be skip.
  308. * @return the height value of the specified position of the terrain, if the (X,Z) position is out of the terrain bounds,it shall return 0;
  309. **/
  310. float getHeight(const Vec2& pos, Vec3* normal = nullptr) const;
  311. /**get the normal of the specified position in terrain
  312. * @return the normal vector of the specified position of the terrain.
  313. * @note the fast normal calculation may not get precise normal vector.
  314. **/
  315. Vec3 getNormal(int pixelX, int pixelY) const;
  316. /**get height from the raw height filed*/
  317. float getImageHeight(int pixelX, int pixelY) const;
  318. /**show the wireline instead of the surface,Debug Use only.
  319. * @Note only support desktop platform
  320. **/
  321. void setDrawWire(bool boolValue);
  322. /**
  323. * Set threshold distance of each LOD level,must equal or greater than the chunk size
  324. * @Note when invoke initHeightMap, the LOD distance will be automatic calculated.
  325. */
  326. void setLODDistance(float lod1, float lod2, float lod3);
  327. /**Switch frustum Culling Flag
  328. * @Note frustum culling will remarkable improve your terrain rendering performance.
  329. */
  330. void setIsEnableFrustumCull(bool boolValue);
  331. /** set the alpha map*/
  332. void setAlphaMap(cocos2d::Texture2D * newAlphaMapTexture);
  333. /**set the Detail Map */
  334. void setDetailMap(unsigned int index, DetailMap detailMap);
  335. // Overrides, internal use only
  336. virtual void draw(cocos2d::Renderer* renderer, const cocos2d::Mat4 &transform, uint32_t flags) override;
  337. /**
  338. * Ray-Terrain intersection.
  339. * @return the intersection point
  340. */
  341. Vec3 getIntersectionPoint(const Ray & ray) const;
  342. /**
  343. * Ray-Terrain intersection.
  344. * @param ray to hit the terrain
  345. * @param intersectionPoint hit point if hit
  346. * @return true if hit, false otherwise
  347. */
  348. bool getIntersectionPoint(const Ray & ray, Vec3 & intersectionPoint) const;
  349. /**
  350. * set the MaxDetailAmount.
  351. */
  352. void setMaxDetailMapAmount(int maxValue);
  353. /**
  354. * Convert a world Space position (X,Z) to terrain space position (X,Z)
  355. */
  356. Vec2 convertToTerrainSpace(const Vec2& worldSpace) const;
  357. /**
  358. * reset the heightmap data.
  359. */
  360. void resetHeightMap(const std::string& heightMap);
  361. /**
  362. * get the terrain's minimal height.
  363. */
  364. float getMinHeight();
  365. /**
  366. * get the terrain's maximal height.
  367. */
  368. float getMaxHeight();
  369. /**
  370. * get the terrain's AABB(in world space)
  371. */
  372. AABB getAABB();
  373. /**
  374. * set the skirt height ratio
  375. */
  376. void setSkirtHeightRatio(float ratio);
  377. /**
  378. * get the terrain's quad tree which is also the root node.
  379. */
  380. QuadTree * getQuadTree();
  381. void reload();
  382. /**
  383. * get the terrain's size
  384. */
  385. Size getTerrainSize() const { return Size(static_cast<float>(_imageWidth), static_cast<float>(_imageHeight)); }
  386. /**
  387. * get the terrain's height data
  388. */
  389. std::vector<float> getHeightData() const;
  390. CC_CONSTRUCTOR_ACCESS:
  391. Terrain();
  392. virtual ~Terrain();
  393. bool initWithTerrainData(TerrainData &parameter, CrackFixedType fixedType);
  394. protected:
  395. void onDraw(const Mat4 &transform, uint32_t flags);
  396. /**
  397. * recursively set each chunk's LOD
  398. * @param cameraPos the camera position in world space
  399. **/
  400. void setChunksLOD(const Vec3& cameraPos);
  401. /**
  402. * load Vertices from height filed for the whole terrain.
  403. **/
  404. void loadVertices();
  405. /**
  406. * calculate Normal Line for each Vertex
  407. **/
  408. void calculateNormal();
  409. //override
  410. virtual void onEnter() override;
  411. /**
  412. * cache all uniform locations in GLSL.
  413. **/
  414. void cacheUniformAttribLocation();
  415. //IBO generate & cache
  416. ChunkIndices lookForIndicesLODSkrit(int selfLod, bool * result);
  417. ChunkIndices lookForIndicesLOD(int neighborLod[4], int selfLod, bool * result);
  418. ChunkIndices insertIndicesLOD(int neighborLod[4], int selfLod, GLushort * indices, int size);
  419. ChunkIndices insertIndicesLODSkirt(int selfLod, GLushort * indices, int size);
  420. Chunk * getChunkByIndex(int x,int y) const;
  421. protected:
  422. std::vector <ChunkLODIndices> _chunkLodIndicesSet;
  423. std::vector<ChunkLODIndicesSkirt> _chunkLodIndicesSkirtSet;
  424. Mat4 _CameraMatrix;
  425. bool _isCameraViewChanged;
  426. TerrainData _terrainData;
  427. bool _isDrawWire;
  428. unsigned char * _data;
  429. float _lodDistance[3];
  430. Texture2D * _detailMapTextures[4];
  431. Texture2D * _alphaMap;
  432. Texture2D * _lightMap;
  433. Vec3 _lightDir;
  434. CustomCommand _customCommand;
  435. QuadTree * _quadRoot;
  436. Chunk * _chunkesArray[MAX_CHUNKES][MAX_CHUNKES];
  437. std::vector<TerrainVertexData> _vertices;
  438. std::vector<unsigned int> _indices;
  439. int _imageWidth;
  440. int _imageHeight;
  441. Size _chunkSize;
  442. bool _isEnableFrustumCull;
  443. int _maxDetailMapValue;
  444. cocos2d::Image * _heightMapImage;
  445. Mat4 _oldCameraModelMatrix;
  446. Mat4 _terrainModelMatrix;
  447. GLuint _normalLocation;
  448. GLuint _positionLocation;
  449. GLuint _texcoordLocation;
  450. float _maxHeight;
  451. float _minHeight;
  452. CrackFixedType _crackFixedType;
  453. float _skirtRatio;
  454. int _skirtVerticesOffset[4];
  455. GLint _detailMapLocation[4];
  456. GLint _alphaMapLocation;
  457. GLint _alphaIsHasAlphaMapLocation;
  458. GLint _lightMapCheckLocation;
  459. GLint _lightMapLocation;
  460. GLint _detailMapSizeLocation[4];
  461. GLint _lightDirLocation;
  462. RenderState::StateBlock* _stateBlock;
  463. #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
  464. EventListenerCustom* _backToForegroundListener;
  465. #endif
  466. };
  467. // end of actions group
  468. /// @}
  469. NS_CC_END
  470. #endif