RUMapRhombusGrid.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. //
  2. // BIMapRhombusGrid.cpp
  3. // CandyCookie
  4. //
  5. // Created by 冷晓霆 on 2022/2/22.
  6. //
  7. #include "RUMapRhombusGrid.h"
  8. #include <queue>
  9. #include "RUUtils.h"
  10. NS_RU_BEGIN
  11. #define GRID_POS_IS_VALID(x,y) ((x < _cntGridsInX*2) && (y < _cntGridsInY*2) && (x >= 0) && (y >= 0) && ((abs((int)x)+abs((int)y))%2 == 1))
  12. MapRhombusGrid* MapRhombusGrid::_instance = nullptr;
  13. int MapRhombusGrid::_nextId4Find = 1;
  14. // 表示到达某个网格的花费等信息
  15. struct OpenPoint {
  16. Vec2 posGrid;
  17. int cost; // 耗费值
  18. int pred; // 预测值
  19. int direction;
  20. OpenPoint* pFather;
  21. OpenPoint() = default;
  22. OpenPoint(const Vec2& posGrid, const Vec2& endPosGrid, int cost, int direction, OpenPoint* pFather)
  23. : cost(cost)
  24. , direction(direction)
  25. , posGrid(posGrid)
  26. , pFather(pFather) {
  27. Vec2 distance = endPosGrid - posGrid;//?
  28. this->pred = cost;
  29. //this->pred = max(abs(distance.x) ,abs(distance.y)) * 10 + (abs(distance.x)!=abs(distance.y))*50 + cost;
  30. // CCLOG("[rhombus] position added: (%d,%d), pred = %d", (int)posGrid.x, (int)posGrid.y, this->pred);
  31. }
  32. };
  33. struct OpenPointPtrCompare {
  34. bool operator()(OpenPoint* a, OpenPoint* b) {
  35. return a->pred > b->pred;
  36. }
  37. };
  38. MapRhombusGrid::MapRhombusGrid() {
  39. _occupiedFlag4Grid = nullptr;
  40. _pGridContainer = nullptr;
  41. _pDrawNode4Debug = nullptr;
  42. _cntGridsInX = 1;
  43. _cntGridsInY = 1;
  44. _bSupportStraight = false;
  45. }
  46. MapRhombusGrid::~MapRhombusGrid() {
  47. if (_occupiedFlag4Grid) {
  48. delete [] _occupiedFlag4Grid;
  49. }
  50. }
  51. void MapRhombusGrid::initialize(const cocos2d::Size& mapSize, const cocos2d::Size& rhombusSize, bool bSupportStraight) {
  52. _mapSize = mapSize;
  53. _rhombusSize = rhombusSize;
  54. _bSupportStraight = bSupportStraight;
  55. _cntGridsInX = _mapSize.width / _rhombusSize.width; // 最好考虑一下边界情况
  56. _cntGridsInY = _mapSize.height / _rhombusSize.height;
  57. _flagSize = _cntGridsInX*2 * _cntGridsInY*2 / 8;
  58. _occupiedFlag4Grid = new unsigned char[_flagSize];
  59. memset(_occupiedFlag4Grid, 0, _flagSize);
  60. _itemsOverlayInGrid.reserve(_cntGridsInX*_cntGridsInY/2);
  61. _itemsInGrid.reserve(_cntGridsInX*_cntGridsInY/2);
  62. }
  63. void MapRhombusGrid::addArea(const std::vector<Vec2>& area, int zOrderDefault) {
  64. RhomArea rhomArea;
  65. rhomArea.grid.insert(area.begin(), area.end());
  66. rhomArea.zOrderDefault = zOrderDefault;
  67. _areas.push_back(rhomArea);
  68. }
  69. void MapRhombusGrid::setDefaultZOrder(int zOrder) {
  70. _zOrderDefault = zOrder;
  71. }
  72. void MapRhombusGrid::itemRemoved(RhombusableItem* pItem) {
  73. for (const Vec2& pos : pItem->getPedestalArea()) {
  74. releaseGrid(pos);
  75. if (GRID_POS_IS_VALID(pos.x, pos.y)) {
  76. int idx = getGridIndex(pos);
  77. auto iter = _itemsInGrid.find(idx);
  78. if (iter != _itemsInGrid.end()) {
  79. iter->second.remove(pItem);
  80. }
  81. if (pItem->isCrossable()) {
  82. auto iter = _gridsCrossable.find(idx);
  83. if (iter != _gridsCrossable.end()) {
  84. if (iter->second == 1) {
  85. _gridsCrossable.erase(iter);
  86. } else {
  87. _gridsCrossable.insert({idx, iter->second - 1});
  88. }
  89. }
  90. }
  91. }
  92. }
  93. for (const Vec2& pos : pItem->getVisibleArea()) {
  94. if (GRID_POS_IS_VALID(pos.x, pos.y)) {
  95. int idx = getGridIndex(pos);
  96. auto iter = _itemsOverlayInGrid.find(idx);
  97. if (iter != _itemsOverlayInGrid.end()) {
  98. iter->second.remove(pItem);
  99. }
  100. iter = _itemsInGrid.find(idx);
  101. if (iter != _itemsInGrid.end()) {
  102. iter->second.remove(pItem);
  103. }
  104. }
  105. }
  106. for (const Vec2& pos : pItem->getWalkableArea()) {
  107. if (GRID_POS_IS_VALID(pos.x, pos.y)) {
  108. int idx = getGridIndex(pos);
  109. auto iter = _itemsInGrid.find(idx);
  110. if (iter != _itemsInGrid.end()) {
  111. iter->second.remove(pItem);
  112. }
  113. }
  114. }
  115. }
  116. bool MapRhombusGrid::itemAdded(RhombusableItem* pItem) {
  117. // 占用每一个底座区域 是否被占用 人物能否走过去 会从这里面取值
  118. for (const Vec2& pos : pItem->getPedestalArea()) {
  119. // drawGridWith(pos, Color4F::RED);
  120. if (GRID_POS_IS_VALID(pos.x, pos.y)) {
  121. int idx = getGridIndex(pos);
  122. // 如果该位置之前没有被占用,并且当前物件可穿行,则记录一下;否则清除
  123. if (pItem->isCrossable()) {
  124. if (!isGridOccupied(pos)) {
  125. auto iter = _gridsCrossable.find(idx);
  126. if (iter != _gridsCrossable.end()) {
  127. _gridsCrossable.insert({idx, iter->second + 1});
  128. } else {
  129. _gridsCrossable.insert({idx, 1});
  130. }
  131. }
  132. } else {
  133. _gridsCrossable.erase(idx);
  134. }
  135. occupyGrid(pos);
  136. auto iter = _itemsInGrid.find(idx);
  137. if (iter == _itemsInGrid.end()) {
  138. _itemsInGrid.insert(std::pair<int, std::list<RhombusableItem*>>(idx, std::list<RhombusableItem*>()));
  139. iter = _itemsInGrid.find(idx);
  140. }
  141. iter->second.push_back(pItem);
  142. }
  143. }
  144. // 记录每一个可视区域
  145. for (const Vec2& pos : pItem->getVisibleArea()) {
  146. // drawGridWith(pos, Color4F::BLUE);
  147. if (GRID_POS_IS_VALID(pos.x, pos.y)) {
  148. int idx = getGridIndex(pos);
  149. {
  150. auto iter = _itemsOverlayInGrid.find(idx);
  151. if (iter == _itemsOverlayInGrid.end()) {
  152. _itemsOverlayInGrid.insert(std::pair<int, std::list<RhombusableItem*>>(idx, std::list<RhombusableItem*>()));
  153. iter = _itemsOverlayInGrid.find(idx);
  154. }
  155. iter->second.push_back(pItem);
  156. }
  157. {
  158. // 也需要往基座中添加,但是不占用区域
  159. auto iter = _itemsInGrid.find(idx);
  160. if (iter == _itemsInGrid.end()) {
  161. _itemsInGrid.insert(std::pair<int, std::list<RhombusableItem*>>(idx, std::list<RhombusableItem*>()));
  162. iter = _itemsInGrid.find(idx);
  163. }
  164. iter->second.push_back(pItem);
  165. }
  166. }
  167. }
  168. // 记录可移动区域
  169. for (const Vec2& pos : pItem->getWalkableArea()) {
  170. // drawGridWith(pos, Color4F::GREEN);
  171. if (GRID_POS_IS_VALID(pos.x, pos.y)) {
  172. int idx = getGridIndex(pos);
  173. {
  174. // 也需要往基座中添加,但是不占用区域
  175. auto iter = _itemsInGrid.find(idx);
  176. if (iter == _itemsInGrid.end()) {
  177. _itemsInGrid.insert(std::pair<int, std::list<RhombusableItem*>>(idx, std::list<RhombusableItem*>()));
  178. iter = _itemsInGrid.find(idx);
  179. }
  180. iter->second.push_back(pItem);
  181. }
  182. }
  183. }
  184. return true;
  185. }
  186. RhombusableItem* MapRhombusGrid::getItem(const std::string& itemName)
  187. {
  188. for (auto items : _itemsInGrid) {
  189. for (auto item : items.second)
  190. {
  191. if (item->getRhombusableItemName().compare(itemName) == 0)
  192. {
  193. return item;
  194. }
  195. }
  196. }
  197. return nullptr;
  198. }
  199. int MapRhombusGrid::findFlyAPath(const Vec2& fromGrid, const Vec2& toGrid, std::list<RhombusPathNode>& path){
  200. UtilsLOG("want go to grid: %f, %f", toGrid.x, toGrid.y);
  201. if ((toGrid.x < 0 || toGrid.x > _cntGridsInX*2) || (toGrid.y < 0 || toGrid.y > _cntGridsInY*2)) {
  202. UtilsLOG("grid is out of sight");
  203. return 2;
  204. }
  205. findFlyAPathInternal(fromGrid, toGrid, path);
  206. return (path.size() > 0) ? 0 : 3;
  207. }
  208. // 找到一个最合适的路径,这里使用A*算法,具体的实现可以参见:https://www.runoob.com/data-structures/graph-theory-path.html
  209. // 各种寻路算法的演示:http://qiao.github.io/PathFinding.js/visual/
  210. int MapRhombusGrid::findAPath(const Vec2& fromGrid, const Vec2& toGrid, std::
  211. list<RhombusPathNode>& path, bool bIgnoreCharacter, bool bFlashToEndPos) {
  212. UtilsLOG("want go to grid: %f, %f", toGrid.x, toGrid.y);
  213. // 如果某个点是被占用的,则返回-1,表示路径不可达
  214. if (isGridOccupied(toGrid)) {
  215. UtilsLOG("grid is occupied");
  216. if(bFlashToEndPos){
  217. return 4;
  218. }
  219. else{
  220. return 1;
  221. }
  222. }
  223. if ((toGrid.x < 0 || toGrid.x > _cntGridsInX*2) || (toGrid.y < 0 || toGrid.y > _cntGridsInY*2)) {
  224. UtilsLOG("grid is out of sight");
  225. return 2;
  226. }
  227. if(bIgnoreCharacter){
  228. findAPathInternal(fromGrid, toGrid, path, true);
  229. return (path.size() > 0) ? 0 : 3;
  230. }
  231. findAPathInternal(fromGrid, toGrid, path, false);
  232. if (path.size() == 0) {
  233. // 再次尝试,忽略掉可穿行的物件
  234. findAPathInternal(fromGrid, toGrid, path, true);
  235. }
  236. return (path.size() > 0) ? 0 : 3;
  237. }
  238. /// 实际查找可飞行路线
  239. int MapRhombusGrid::findFlyAPathInternal(const Vec2& fromGrid, const Vec2& toGrid, std::list<RhombusPathNode>& path) {
  240. static Vec2 adj1[] = {Vec2(-1,1), Vec2(1,1), Vec2(1,-1), Vec2(-1,-1)}; // 斜着的上下左右四个方向
  241. static Vec2 adj2[] = {Vec2(-2,0), Vec2(2,0), Vec2(0,2), Vec2(0,-2)}; // 正着的上下左右四个方向
  242. std::list<OpenPoint> lstPoints;
  243. std::priority_queue<OpenPoint*, std::vector<OpenPoint*>, OpenPointPtrCompare> lstOpen; // 需要处理的节点
  244. std::map<Vec2, int> dis;
  245. // 将起始点设置为开始点,以后每次都从优先队列里面取值
  246. lstPoints.emplace_back(fromGrid, toGrid, 0, -1, nullptr);
  247. dis[fromGrid] = 0;
  248. lstOpen.push(&lstPoints.back());
  249. bool bGot = false;
  250. int cntTried = 10000;
  251. while (!lstOpen.empty() && cntTried-- > 0) {
  252. OpenPoint* curPoint = lstOpen.top();
  253. lstOpen.pop();
  254. // cout<<curPoint->posGrid.x<<" "<<curPoint->posGrid.y<<" "<<curPoint->cost<<endl;
  255. if(dis.find(curPoint->posGrid)!=dis.end() && dis[curPoint->posGrid]< curPoint->cost){
  256. continue;
  257. }
  258. // drawGridWith(curPoint->posGrid, Color4F::GREEN, true);
  259. if (curPoint->posGrid.equals(toGrid)) {
  260. bGot = true;
  261. lstPoints.emplace_back(curPoint->posGrid, toGrid, 0, -1, curPoint);
  262. lstOpen.push(&lstPoints.back());
  263. break; // 得到了一条路径
  264. }
  265. // 将周围的直接点都放入到优先级队列中
  266. for (int i=0; i<sizeof(adj1)/sizeof(adj1[0]); i++) {
  267. Vec2 newPos = curPoint->posGrid + adj1[i];
  268. // 新增direction cost
  269. int direction_cost = 0;
  270. if(curPoint->direction!=-1&&curPoint->direction!=i){
  271. direction_cost = 50;
  272. }
  273. int now_cost = curPoint->cost + 10 + direction_cost;
  274. if(dis.find(newPos)!=dis.end() && dis[newPos] <= now_cost){
  275. continue;
  276. }
  277. // cout<<newPos.x<<" "<<newPos.y<<" "<<now_cost;
  278. // if(dis.find(newPos)!=dis.end()){
  279. // cout<<" "<<dis[newPos]<<endl;
  280. // }else cout<<endl;
  281. // 加入到优先队列里面
  282. dis[newPos] = now_cost;
  283. lstPoints.emplace_back(newPos, toGrid, now_cost, i, curPoint);
  284. lstOpen.push(&lstPoints.back());
  285. }
  286. if (_bSupportStraight) {
  287. // 将周围的跨越点都放入到优先级队列中
  288. for (int i=0; i<sizeof(adj2)/sizeof(adj2[0]); i++) {
  289. Vec2 newPos = curPoint->posGrid + adj2[i];
  290. // if (!isGridOccupied(newPos) && (pointClosed.find(newPos) == pointClosed.end())) {
  291. if (!isGridOccupied(newPos)) {
  292. // FIXME 还需要判断路径上面2个点是否是空的
  293. // 检查该位置是否在物件点击区域范围内
  294. // 新增代码
  295. Vec2 mapPos = getGridCenter(newPos);
  296. // 新增direction cost
  297. int direction_cost = 0;
  298. if(curPoint->direction!=-1&&curPoint->direction!=4+i){
  299. direction_cost = 50;
  300. }
  301. int now_cost = curPoint->cost + 10 + direction_cost;
  302. if(dis.find(newPos)!=dis.end() && dis[newPos]<=now_cost){
  303. continue;
  304. }
  305. // cout<<newPos.x<<" "<<newPos.y<<" "<<now_cost;
  306. // if(dis.find(newPos)!=dis.end()){
  307. // cout<<" "<<dis[newPos]<<endl;
  308. // }else cout<<endl;
  309. dis[newPos] = now_cost;
  310. lstPoints.emplace_back(newPos, toGrid, now_cost, 4+i, curPoint);
  311. lstOpen.push(&lstPoints.back());
  312. // pointClosed.insert(newPos);
  313. }
  314. }
  315. }
  316. // 改点已经处理过了
  317. // pointClosed.insert(curPoint->posGrid);
  318. }
  319. // 从后往前将节点都放入到路径中
  320. if (bGot) {
  321. OpenPoint* curPoint = lstOpen.top();
  322. while (curPoint != nullptr) {
  323. RhombusPathNode& front = path.front();
  324. RhombusPathNode pathNode;
  325. Vec2 pos = curPoint->posGrid;
  326. pathNode.posGrid = pos;
  327. if (!front.posGrid.equals(pathNode.posGrid)) {
  328. path.push_front(pathNode);
  329. }
  330. curPoint = curPoint->pFather;
  331. }
  332. } else {
  333. UtilsLOG("no path found");
  334. return 1;
  335. }
  336. return 0;
  337. }
  338. int MapRhombusGrid::findAPathInternal(const Vec2& fromGrid, const Vec2& toGrid, std::list<RhombusPathNode>& path, bool bIgnoreCrossable) {
  339. static Vec2 adj1[] = {Vec2(-1,1), Vec2(1,1), Vec2(1,-1), Vec2(-1,-1)}; // 斜着的上下左右四个方向
  340. static Vec2 adj2[] = {Vec2(-2,0), Vec2(2,0), Vec2(0,2), Vec2(0,-2)}; // 正着的上下左右四个方向
  341. //std::set<Vec2> pointClosed; // 处理过的网格位置
  342. std::list<OpenPoint> lstPoints;
  343. std::priority_queue<OpenPoint*, std::vector<OpenPoint*>, OpenPointPtrCompare> lstOpen; // 需要处理的节点
  344. std::map<Vec2, int> dis;
  345. // 将起始点设置为开始点,以后每次都从优先队列里面取值
  346. lstPoints.emplace_back(fromGrid, toGrid, 0, -1, nullptr);
  347. dis[fromGrid] = 0;
  348. lstOpen.push(&lstPoints.back());
  349. // pointClosed.insert(fromGrid);
  350. bool bGot = false;
  351. int cntTried = 10000;
  352. while (!lstOpen.empty() && cntTried-- > 0) {
  353. OpenPoint* curPoint = lstOpen.top();
  354. lstOpen.pop();
  355. // cout<<curPoint->posGrid.x<<" "<<curPoint->posGrid.y<<" "<<curPoint->cost<<endl;
  356. if(dis.find(curPoint->posGrid)!=dis.end() && dis[curPoint->posGrid]< curPoint->cost){
  357. continue;
  358. }
  359. // drawGridWith(curPoint->posGrid, Color4F::GREEN, true);
  360. if (curPoint->posGrid.equals(toGrid)) {
  361. bGot = true;
  362. lstPoints.emplace_back(curPoint->posGrid, toGrid, 0, -1, curPoint);
  363. lstOpen.push(&lstPoints.back());
  364. break; // 得到了一条路径
  365. }
  366. // 将周围的直接点都放入到优先级队列中
  367. for (int i=0; i<sizeof(adj1)/sizeof(adj1[0]); i++) {
  368. Vec2 newPos = curPoint->posGrid + adj1[i];
  369. bool bValid = !isGridOccupied(newPos);
  370. if (!bValid && bIgnoreCrossable) {
  371. if (_gridsCrossable.find(getGridIndex(newPos)) != _gridsCrossable.end()) {
  372. bValid = true;
  373. }
  374. }
  375. if (bValid) {
  376. // 新增direction cost
  377. int direction_cost = 0;
  378. if(curPoint->direction!=-1&&curPoint->direction!=i){
  379. direction_cost = 50;
  380. }
  381. int now_cost = curPoint->cost + 10 + direction_cost;
  382. if(dis.find(newPos)!=dis.end() && dis[newPos] <= now_cost){
  383. continue;
  384. }
  385. // cout<<newPos.x<<" "<<newPos.y<<" "<<now_cost;
  386. // if(dis.find(newPos)!=dis.end()){
  387. // cout<<" "<<dis[newPos]<<endl;
  388. // }else cout<<endl;
  389. // 加入到优先队列里面
  390. dis[newPos] = now_cost;
  391. lstPoints.emplace_back(newPos, toGrid, now_cost, i, curPoint);
  392. lstOpen.push(&lstPoints.back());
  393. // pointClosed.insert(newPos);
  394. }
  395. }
  396. if (_bSupportStraight) {
  397. // 将周围的跨越点都放入到优先级队列中
  398. for (int i=0; i<sizeof(adj2)/sizeof(adj2[0]); i++) {
  399. Vec2 newPos = curPoint->posGrid + adj2[i];
  400. // if (!isGridOccupied(newPos) && (pointClosed.find(newPos) == pointClosed.end())) {
  401. if (!isGridOccupied(newPos)) {
  402. // FIXME 还需要判断路径上面2个点是否是空的
  403. // 检查该位置是否在物件点击区域范围内
  404. // 新增代码
  405. Vec2 mapPos = getGridCenter(newPos);
  406. // 新增direction cost
  407. int direction_cost = 0;
  408. if(curPoint->direction!=-1&&curPoint->direction!=4+i){
  409. direction_cost = 50;
  410. }
  411. int now_cost = curPoint->cost + 10 + direction_cost;
  412. if(dis.find(newPos)!=dis.end() && dis[newPos]<=now_cost){
  413. continue;
  414. }
  415. // cout<<newPos.x<<" "<<newPos.y<<" "<<now_cost;
  416. // if(dis.find(newPos)!=dis.end()){
  417. // cout<<" "<<dis[newPos]<<endl;
  418. // }else cout<<endl;
  419. dis[newPos] = now_cost;
  420. lstPoints.emplace_back(newPos, toGrid, now_cost, 4+i, curPoint);
  421. lstOpen.push(&lstPoints.back());
  422. // pointClosed.insert(newPos);
  423. }
  424. }
  425. }
  426. // 改点已经处理过了
  427. // pointClosed.insert(curPoint->posGrid);
  428. }
  429. // 从后往前将节点都放入到路径中
  430. if (bGot) {
  431. OpenPoint* curPoint = lstOpen.top();
  432. while (curPoint != nullptr) {
  433. RhombusPathNode pathNode;
  434. Vec2 pos = curPoint->posGrid;
  435. pathNode.posGrid = pos;
  436. path.push_front(pathNode);
  437. curPoint = curPoint->pFather;
  438. }
  439. } else {
  440. UtilsLOG("no path found");
  441. return 1;
  442. }
  443. return 0;
  444. }
  445. Vec2 MapRhombusGrid::getGridCenter(const Vec2& gridPos) {
  446. cocos2d::Vec2 ret = cocos2d::Vec2::ZERO;
  447. int intX = (int)gridPos.x;
  448. int intY = (int)gridPos.y;
  449. // 根据对棱形网格坐标的定义(x,y表示第几列,第几行),intX, intY 必须一个奇数,一个为偶数
  450. if ((((intX % 2) + (intY % 2)) % 2) != 0) {
  451. int signBitX = intX == 0 ? 1 : intX / std::abs(intX);
  452. int signBitY = intY == 0 ? 1 : intY / std::abs(intY);
  453. if ((intX % 2) != 0) {
  454. ret = cocos2d::Vec2((std::abs(intX) / 2 + 0.5) * _rhombusSize.width, std::abs(intY) / 2 * _rhombusSize.height);
  455. } else {
  456. ret = cocos2d::Vec2(std::abs(intX) / 2 * _rhombusSize.width, (std::abs(intY) / 2 + 0.5) * _rhombusSize.height);
  457. }
  458. ret.x *= signBitX;
  459. ret.y *= signBitY;
  460. }
  461. return ret;
  462. }
  463. Vec2 MapRhombusGrid::getGridPosition(const Vec2& pos) {
  464. // 先定位到由棱形格子一半大小分割的横竖方向的小格子里面:就是棱形网格的中心点和网格线交叉点形成的正规xy坐标系
  465. // 然后根据该小格子是被菱形格线正向切分还是反向切分判断出该点在切分线的上部还是下部,就可以得到该点的棱形网格的坐标
  466. static float halfWidth = _rhombusSize.width * 0.5f;
  467. static float halfHeight = _rhombusSize.height * 0.5f;
  468. static float aspc = _rhombusSize.height / _rhombusSize.width;
  469. int y = pos.y / halfHeight;
  470. int x = pos.x / halfWidth;
  471. Vec2 refPos = pos - Vec2(x * halfWidth, y * halfHeight);
  472. if (0 == (x + y) % 2) {
  473. // 这里面包含了所有的网格线的交汇点
  474. if(fabs(refPos.x-0.0) > 0.000001 && (refPos.y / refPos.x >= aspc)) {
  475. x --;
  476. y ++;
  477. }
  478. } else {
  479. static Vec2 m(halfWidth, 0);
  480. static Vec2 n(0, halfHeight);
  481. float cross = (refPos - m).cross(n - refPos);
  482. if(cross <= 0){
  483. x --;
  484. }else{
  485. y ++;
  486. }
  487. }
  488. return Vec2(x + 1, y);
  489. }
  490. int MapRhombusGrid::getDefaultZOrder(const Vec2& posGrid) {
  491. for (const RhomArea& area : _areas) {
  492. if (area.grid.find(posGrid) != area.grid.end()) {
  493. return area.zOrderDefault;
  494. }
  495. }
  496. return _zOrderDefault;
  497. }
  498. void MapRhombusGrid::setGridObstacle(const Vec2& posGrid){
  499. occupyGrid(posGrid);
  500. }
  501. int MapRhombusGrid::getGridIndex(const Vec2& posGrid) {
  502. return posGrid.y * _cntGridsInX * 2.0 + posGrid.x;
  503. }
  504. void MapRhombusGrid::occupyGrid(const Vec2& posGrid) {
  505. // if (posGrid.x == 94 && posGrid.y == 117) {
  506. // CCLOG(" ");
  507. // }
  508. int idx = getGridIndex(posGrid);
  509. if (idx > (_flagSize*8)) {
  510. return;
  511. }
  512. unsigned char* pGroup = _occupiedFlag4Grid + (idx / 8);
  513. unsigned char value = *pGroup;
  514. value = value | ((unsigned char)0x1 << (idx%8));
  515. *pGroup = value;
  516. }
  517. void MapRhombusGrid::releaseGrid(const Vec2& posGrid) {
  518. int idx = getGridIndex(posGrid);
  519. if (idx > (_flagSize*8)) {
  520. return;
  521. }
  522. unsigned char* pGroup = _occupiedFlag4Grid + (idx / 8);
  523. unsigned char value = *pGroup;
  524. unsigned char tmp = (unsigned char)0x1 << (idx%8);
  525. value = value & (~tmp);
  526. *pGroup = value;
  527. }
  528. bool MapRhombusGrid::isGridOccupied(const Vec2& posGrid) {
  529. if (GRID_POS_IS_VALID(posGrid.x, posGrid.y)) {
  530. int idx = getGridIndex(posGrid);
  531. if (idx > (_flagSize*8)) {
  532. return true;
  533. }
  534. unsigned char value = _occupiedFlag4Grid[idx/8];
  535. return (value & (0x1 << (idx%8))) != 0;
  536. } else {
  537. return true;
  538. }
  539. }
  540. int MapRhombusGrid::getCntInOverlay(const Vec2& gridPos) {
  541. auto iter = _itemsOverlayInGrid.find(getGridIndex(gridPos));
  542. if (iter == _itemsOverlayInGrid.end()) {
  543. return 0;
  544. } else {
  545. return (int)(iter->second.size());
  546. }
  547. }
  548. void MapRhombusGrid::findAdjEmptyPoses(RhombusableItem* pItem, const Vec2& centerPos, std::set<Vec2>& found) {
  549. if (!pItem) {
  550. return;
  551. }
  552. static Vec2 adj1[] = {Vec2(-1,1), Vec2(1,1), Vec2(1,-1), Vec2(-1,-1)}; // 斜着的上下左右四个方向
  553. for (const Vec2& p : pItem->getPedestalArea()) {
  554. for (Vec2& adj : adj1) {
  555. Vec2 t = adj + p;
  556. if (!isGridOccupied(t)) {
  557. found.insert(t);
  558. }
  559. }
  560. }
  561. return;
  562. }
  563. void MapRhombusGrid::drawGridNode(const Vec2& gridPos, Color4F color, bool isTemp, float removeNodeDelay) {
  564. if (!_pGridContainer) {
  565. return;
  566. }
  567. auto pTempDN = DrawNode::create();
  568. _pGridContainer->addChild(pTempDN);
  569. pTempDN->setLocalZOrder(100001);
  570. pTempDN->setPosition(Vec2(0,0));
  571. std::vector<Vec2> points = getGridPointsAt(gridPos);
  572. pTempDN->drawLine(points[0], points[1], color);
  573. pTempDN->drawLine(points[1], points[2], color);
  574. pTempDN->drawLine(points[2], points[3], color);
  575. pTempDN->drawLine(points[3], points[0], color);
  576. if (isTemp) {
  577. pTempDN->scheduleOnce([=](float dt) {
  578. pTempDN->removeFromParent();
  579. }, removeNodeDelay, "SCH_DRAWNODE_RM");
  580. }
  581. }
  582. void MapRhombusGrid::refreshDebugGrid(bool isEnable)
  583. {
  584. _isDebugEnable = isEnable;
  585. if (!_isDebugEnable)
  586. {
  587. if (_pDrawNode4Debug)
  588. _pDrawNode4Debug->clear();
  589. return;
  590. }
  591. if (_pDrawNode4Debug == nullptr) {
  592. _pDrawNode4Debug = DrawNode::create();
  593. _pGridContainer->addChild(_pDrawNode4Debug);
  594. _pDrawNode4Debug->setLocalZOrder(100000);
  595. _pDrawNode4Debug->setPosition(Vec2(0,0));
  596. } else {
  597. _pDrawNode4Debug->clear();
  598. }
  599. // 对于每一个网格点,绘制四条边
  600. for (int i=0; i<_cntGridsInX*2; i++) {
  601. for (int j=0; j<_cntGridsInY*2; j++) {
  602. // 根据对棱形网格坐标的定义(x,y表示第几列,第几行),intX, intY 必须一个奇数,一个为偶数
  603. if ((((i%2) + (j%2)) % 2) == 0) {
  604. continue;
  605. }
  606. drawGridWith(Vec2(i, j), Color4F(127, 127, 127, 100));
  607. }
  608. }
  609. // for (auto items : _itemsInGrid) {
  610. // for (auto pItem : items.second) {
  611. // // 占用每一个底座区域
  612. // for (const Vec2& pos : pItem->getPedestalArea()) {
  613. // drawGridWith(pos, Color4F::RED, true);
  614. // }
  615. // // 记录每一个可视区域
  616. // for (const Vec2& pos : pItem->getVisibleArea()) {
  617. // drawGridWith(pos, Color4F::BLUE, true);
  618. // }
  619. // }
  620. // }
  621. }
  622. void MapRhombusGrid::debugGridAt(Node* pGridContainer) {
  623. _pGridContainer = pGridContainer;
  624. if (!_isDebugEnable)
  625. return;
  626. if (_pDrawNode4Debug == nullptr) {
  627. _pDrawNode4Debug = DrawNode::create();
  628. pGridContainer->addChild(_pDrawNode4Debug);
  629. _pDrawNode4Debug->setLocalZOrder(100000000);
  630. _pDrawNode4Debug->setPosition(Vec2(0,0));
  631. }
  632. // 对于每一个网格点,绘制四条边
  633. for (int i=0; i<_cntGridsInX*2; i++) {
  634. for (int j=0; j<_cntGridsInY*2; j++) {
  635. // 根据对棱形网格坐标的定义(x,y表示第几列,第几行),intX, intY 必须一个奇数,一个为偶数
  636. if ((((i%2) + (j%2)) % 2) == 0) {
  637. continue;
  638. }
  639. drawGridWith(Vec2(i, j),Color4F::GRAY);
  640. }
  641. }
  642. }
  643. void MapRhombusGrid::drawGridWith(const Vec2& gridPos, Color4F color, bool fill) {
  644. if (!_isDebugEnable)
  645. return;
  646. std::vector<Vec2> points = getGridPointsAt(gridPos);
  647. if (!fill) {
  648. _pDrawNode4Debug->drawLine(points[0], points[1], color);
  649. _pDrawNode4Debug->drawLine(points[1], points[2], color);
  650. _pDrawNode4Debug->drawLine(points[2], points[3], color);
  651. _pDrawNode4Debug->drawLine(points[3], points[0], color);
  652. } else {
  653. Vec2 tmp_points[4]={points[0],points[1],points[2],points[3]};
  654. _pDrawNode4Debug->drawSolidPoly(tmp_points, 4, color);
  655. }
  656. }
  657. std::vector<Vec2> MapRhombusGrid::getGridPointsAt(const Vec2& gridPos) {
  658. std::vector<Vec2> points;
  659. Vec2 centerPos = getGridCenter(gridPos);
  660. points.push_back(Vec2(centerPos+Vec2(-_rhombusSize.width/2, 0)));
  661. points.push_back(Vec2(centerPos+Vec2(0, _rhombusSize.height/2)));
  662. points.push_back(Vec2(centerPos+Vec2(_rhombusSize.width/2, 0)));
  663. points.push_back(Vec2(centerPos+Vec2(0, -_rhombusSize.height/2)));
  664. return points;
  665. }
  666. int MapRhombusGrid::getGridZorder(const Vec2& gridPos, bool& bIsOverlayed, RhombusableItem* pTargetItem, bool bFlyMode) {
  667. // 往下找3个位置,避免和可能的另外一个人物重叠,留出富余量给可能的另外的角色
  668. // 包括了人物本身的位置,这样如果该位置被其他物件所遮罩的话,就能正确得到zorder
  669. static Vec2 downwards[] = {Vec2(0,0), Vec2(0,-2), Vec2(0,-4), Vec2(0,-6)};
  670. RhombusableItem* pItemWithMinZOrder = nullptr;
  671. int zOrderMin = 0x7fffffff;
  672. Vec2 posWithMinZOrder(0,0);
  673. int defaultZOrder = getDefaultZOrder(gridPos);
  674. for (int i=0; i<sizeof(downwards)/sizeof(Vec2); i++) {
  675. // 1: 是碰到被占用的区域返回
  676. // 2: 是默认越近的zorder应该越小,所以只要找到就返回
  677. if (isGridOccupied(gridPos + downwards[i])) {
  678. break;
  679. }
  680. auto iter = _itemsOverlayInGrid.find(getGridIndex(gridPos + downwards[i]));
  681. if (iter != _itemsOverlayInGrid.end()) {
  682. for (RhombusableItem* pItem : iter->second) {
  683. if (((pItem != pTargetItem) && (pItem->getCurZOrder() < zOrderMin))) {
  684. bool bItemIsOk = true;
  685. if (i == 0) {
  686. if (!isBehindItem(gridPos, pItem)) {
  687. bItemIsOk = false;
  688. }
  689. }
  690. if(pItem->getCurZOrder() < defaultZOrder){
  691. bItemIsOk = false;
  692. }
  693. if (bItemIsOk) {
  694. //设置一个最小的zorder
  695. zOrderMin = pItem->getCurZOrder();
  696. pItemWithMinZOrder = pItem;
  697. posWithMinZOrder = gridPos + downwards[i];
  698. }
  699. }
  700. }
  701. if (pItemWithMinZOrder) {
  702. break;
  703. }
  704. }
  705. }
  706. if (pItemWithMinZOrder != nullptr) {
  707. bIsOverlayed = true;
  708. int zOrder = pItemWithMinZOrder->getCurZOrder() - (int)(gridPos.y - posWithMinZOrder.y) - 1;
  709. if(zOrder < defaultZOrder) zOrder = defaultZOrder; ///家具的zorder比地毯值要大
  710. if(!bFlyMode) return zOrder;
  711. }
  712. // 如果没有,则往上找3个位置
  713. // 要盖住上面的元素
  714. static Vec2 upwards[] = {Vec2(-1,1), Vec2(1,1), Vec2(0,2), Vec2(-1,3), Vec2(1,3), Vec2(0,4), Vec2(-1,5), Vec2(1,5), Vec2(0,6), Vec2(-1,7), Vec2(1,7), Vec2(0,8)};
  715. RhombusableItem* pItemWithMaxZOrder = nullptr;
  716. int zOrderMax = getDefaultZOrder(gridPos);
  717. Vec2 posWithMaxZOrder(0,0);
  718. for (int i=0; i<sizeof(upwards)/sizeof(Vec2); i++) {
  719. auto iter = _itemsInGrid.find(getGridIndex(gridPos + upwards[i]));
  720. if (iter != _itemsInGrid.end()) {
  721. for (RhombusableItem* pItem : iter->second) {
  722. if ((pItem != pTargetItem) && (pItem->getCurZOrder() > zOrderMax)) {
  723. bool bItemIsOk = true;
  724. if (bItemIsOk) {
  725. //设置一个最大的zorder
  726. zOrderMax = pItem->getCurZOrder();
  727. pItemWithMaxZOrder = pItem;
  728. posWithMaxZOrder = gridPos + upwards[i];
  729. }
  730. }
  731. }
  732. }
  733. }
  734. int zOrder = 0;
  735. if (pItemWithMaxZOrder != nullptr) {
  736. ///留50个可移动的空位
  737. zOrder = pItemWithMaxZOrder->getCurZOrder() + (int)(posWithMaxZOrder.y - gridPos.y) + (BLOCK_GRID_SPACE - 1);
  738. } else {
  739. // 默认的zorder, 这个值要保证比解析item时设置的最大的zorder要大
  740. zOrder = getDefaultZOrder(gridPos) + (BLOCK_GRID_SPACE - 1);
  741. }
  742. bIsOverlayed = false;
  743. return zOrder;
  744. }
  745. bool MapRhombusGrid::isBehindItem(const Vec2& posGrid, RhombusableItem* pItem) {
  746. // 如果该物件有某个底座网格处在posgrid的正前方,则返回true
  747. for (const auto& p : pItem->getPedestalArea()) {
  748. if (p.x == posGrid.x && p.y < posGrid.y) {
  749. return true;
  750. }
  751. }
  752. return false;
  753. }
  754. std::list<std::string> MapRhombusGrid::getItemsInGrid(const Vec2& gridPos) {
  755. std::list<std::string> items;
  756. auto iter = _itemsInGrid.find(getGridIndex(gridPos));
  757. if (iter == _itemsInGrid.end()) {
  758. return items;
  759. }
  760. for (auto& pItem : iter->second) {
  761. for (auto& p : pItem->getPedestalArea()) {
  762. if (gridPos.equals(p)) {
  763. items.push_back(pItem->getRhombusableItemName());
  764. break;
  765. }
  766. }
  767. }
  768. return items;
  769. }
  770. NS_RU_END