tile_map_layer.cpp 154 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921
  1. /**************************************************************************/
  2. /* tile_map_layer.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "tile_map_layer.h"
  31. #include "core/io/marshalls.h"
  32. #include "core/math/geometry_2d.h"
  33. #include "core/math/random_pcg.h"
  34. #include "core/templates/a_hash_map.h"
  35. #include "scene/2d/tile_map.h"
  36. #include "scene/gui/control.h"
  37. #include "scene/resources/2d/navigation_mesh_source_geometry_data_2d.h"
  38. #include "scene/resources/material.h"
  39. #include "scene/resources/world_2d.h"
  40. #ifndef PHYSICS_2D_DISABLED
  41. #include "servers/physics_2d/physics_server_2d.h"
  42. #endif // PHYSICS_3D_DISABLED
  43. #ifndef NAVIGATION_2D_DISABLED
  44. #include "servers/navigation_2d/navigation_server_2d.h"
  45. Callable TileMapLayer::_navmesh_source_geometry_parsing_callback;
  46. RID TileMapLayer::_navmesh_source_geometry_parser;
  47. #endif // NAVIGATION_2D_DISABLED
  48. Vector2i TileMapLayer::_coords_to_quadrant_coords(const Vector2i &p_coords, const int p_quadrant_size) const {
  49. return Vector2i(
  50. p_coords.x > 0 ? p_coords.x / p_quadrant_size : (p_coords.x - (p_quadrant_size - 1)) / p_quadrant_size,
  51. p_coords.y > 0 ? p_coords.y / p_quadrant_size : (p_coords.y - (p_quadrant_size - 1)) / p_quadrant_size);
  52. }
  53. #ifdef DEBUG_ENABLED
  54. /////////////////////////////// Debug //////////////////////////////////////////
  55. constexpr int TILE_MAP_DEBUG_QUADRANT_SIZE = 16;
  56. void TileMapLayer::_debug_update(bool p_force_cleanup) {
  57. RenderingServer *rs = RenderingServer::get_singleton();
  58. // Check if we should cleanup everything.
  59. bool forced_cleanup = p_force_cleanup || !enabled || tile_set.is_null() || !is_visible_in_tree();
  60. if (forced_cleanup && _debug_was_cleaned_up) {
  61. return;
  62. }
  63. if (forced_cleanup) {
  64. for (KeyValue<Vector2i, Ref<DebugQuadrant>> &kv : debug_quadrant_map) {
  65. // Free the quadrant.
  66. Ref<DebugQuadrant> &debug_quadrant = kv.value;
  67. if (debug_quadrant->canvas_item.is_valid()) {
  68. rs->free_rid(debug_quadrant->canvas_item);
  69. }
  70. if (debug_quadrant->physics_mesh.is_valid()) {
  71. rs->free_rid(debug_quadrant->physics_mesh);
  72. }
  73. }
  74. debug_quadrant_map.clear();
  75. _debug_was_cleaned_up = true;
  76. return;
  77. }
  78. // Check if anything is dirty, in such a case, redraw debug.
  79. bool anything_changed = false;
  80. for (int i = 0; i < DIRTY_FLAGS_MAX; i++) {
  81. if (dirty.flags[i]) {
  82. anything_changed = true;
  83. break;
  84. }
  85. }
  86. // List all debug quadrants to update.
  87. HashSet<Vector2i> quadrants_to_updates;
  88. if (_debug_was_cleaned_up || anything_changed) {
  89. // Update all cells.
  90. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  91. CellData &cell_data = kv.value;
  92. quadrants_to_updates.insert(_coords_to_quadrant_coords(cell_data.coords, TILE_MAP_DEBUG_QUADRANT_SIZE));
  93. #ifndef PHYSICS_2D_DISABLED
  94. // Physics quadrants are drawn from their origin.
  95. Vector2i physics_quadrant_origin = _coords_to_quadrant_coords(cell_data.coords, physics_quadrant_size) * physics_quadrant_size;
  96. quadrants_to_updates.insert(_coords_to_quadrant_coords(physics_quadrant_origin, TILE_MAP_DEBUG_QUADRANT_SIZE));
  97. #endif // PHYSICS_2D_DISABLED
  98. }
  99. } else {
  100. // Update dirty cells.
  101. for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  102. CellData &cell_data = *cell_data_list_element->self();
  103. quadrants_to_updates.insert(_coords_to_quadrant_coords(cell_data.coords, TILE_MAP_DEBUG_QUADRANT_SIZE));
  104. #ifndef PHYSICS_2D_DISABLED
  105. // Physics quadrants are drawn from their origin.
  106. Vector2i physics_quadrant_origin = _coords_to_quadrant_coords(cell_data.coords, physics_quadrant_size) * physics_quadrant_size;
  107. quadrants_to_updates.insert(_coords_to_quadrant_coords(physics_quadrant_origin, TILE_MAP_DEBUG_QUADRANT_SIZE));
  108. #endif // PHYSICS_2D_DISABLED
  109. }
  110. }
  111. // Create new quadrants if needed.
  112. for (const Vector2i &quadrant_coords : quadrants_to_updates) {
  113. if (!debug_quadrant_map.has(quadrant_coords)) {
  114. // Create a new quadrant and add it to the quadrant map.
  115. Ref<DebugQuadrant> new_quadrant;
  116. new_quadrant.instantiate();
  117. new_quadrant->quadrant_coords = quadrant_coords;
  118. debug_quadrant_map[quadrant_coords] = new_quadrant;
  119. }
  120. }
  121. // Second pass on modified cells to update the list of cells per quandrant.
  122. if (_debug_was_cleaned_up || anything_changed) {
  123. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  124. CellData &cell_data = kv.value;
  125. Ref<DebugQuadrant> debug_quadrant = debug_quadrant_map[_coords_to_quadrant_coords(cell_data.coords, TILE_MAP_DEBUG_QUADRANT_SIZE)];
  126. if (!cell_data.debug_quadrant_list_element.in_list()) {
  127. debug_quadrant->cells.add(&cell_data.debug_quadrant_list_element);
  128. }
  129. }
  130. } else {
  131. for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  132. CellData &cell_data = *cell_data_list_element->self();
  133. Ref<DebugQuadrant> debug_quadrant = debug_quadrant_map[_coords_to_quadrant_coords(cell_data.coords, TILE_MAP_DEBUG_QUADRANT_SIZE)];
  134. if (!cell_data.debug_quadrant_list_element.in_list()) {
  135. debug_quadrant->cells.add(&cell_data.debug_quadrant_list_element);
  136. }
  137. }
  138. }
  139. // Update those quadrants.
  140. bool needs_set_not_interpolated = is_inside_tree() && get_tree()->is_physics_interpolation_enabled() && !is_physics_interpolated();
  141. for (const Vector2i &quadrant_coords : quadrants_to_updates) {
  142. Ref<DebugQuadrant> debug_quadrant = debug_quadrant_map[quadrant_coords];
  143. // Update the quadrant's canvas item.
  144. RID &ci = debug_quadrant->canvas_item;
  145. if (ci.is_valid()) {
  146. rs->canvas_item_clear(ci);
  147. } else {
  148. ci = rs->canvas_item_create();
  149. if (needs_set_not_interpolated) {
  150. rs->canvas_item_set_interpolated(ci, false);
  151. }
  152. rs->canvas_item_set_z_index(ci, RS::CANVAS_ITEM_Z_MAX - 1);
  153. rs->canvas_item_set_parent(ci, get_canvas_item());
  154. }
  155. const Vector2 quadrant_pos = tile_set->map_to_local(debug_quadrant->quadrant_coords * TILE_MAP_DEBUG_QUADRANT_SIZE);
  156. Transform2D xform(0, quadrant_pos);
  157. rs->canvas_item_set_transform(ci, xform);
  158. #ifndef PHYSICS_2D_DISABLED
  159. // Draw physics.
  160. _physics_draw_quadrant_debug(ci, *debug_quadrant.ptr());
  161. #endif // PHYSICS_2D_DISABLED
  162. // Draw debug info.
  163. for (SelfList<CellData> *cell_data_list_element = debug_quadrant->cells.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  164. CellData &cell_data = *cell_data_list_element->self();
  165. if (cell_data.cell.source_id != TileSet::INVALID_SOURCE) {
  166. _rendering_draw_cell_debug(ci, quadrant_pos, cell_data);
  167. #ifndef NAVIGATION_2D_DISABLED
  168. _navigation_draw_cell_debug(ci, quadrant_pos, cell_data);
  169. #endif // NAVIGATION_2D_DISABLED
  170. _scenes_draw_cell_debug(ci, quadrant_pos, cell_data);
  171. debug_quadrant->drawn_to = true;
  172. }
  173. }
  174. // Free the quadrants that were not drawn to.
  175. if (!debug_quadrant->drawn_to) {
  176. // Free the quadrant.
  177. if (ci.is_valid()) {
  178. rs->free_rid(ci);
  179. }
  180. debug_quadrant_map.erase(quadrant_coords);
  181. }
  182. }
  183. _debug_was_cleaned_up = false;
  184. }
  185. #endif // DEBUG_ENABLED
  186. Color TileMapLayer::_highlight_color(const Color &p_modulate) const {
  187. if (highlight_mode == HIGHLIGHT_MODE_BELOW) {
  188. return p_modulate.darkened(0.5);
  189. }
  190. if (highlight_mode == HIGHLIGHT_MODE_ABOVE) {
  191. Color c = p_modulate.darkened(0.5);
  192. c.a *= 0.3;
  193. return c;
  194. }
  195. return p_modulate;
  196. }
  197. /////////////////////////////// Rendering //////////////////////////////////////
  198. void TileMapLayer::_rendering_update(bool p_force_cleanup) {
  199. RenderingServer *rs = RenderingServer::get_singleton();
  200. // Check if we should cleanup everything.
  201. bool forced_cleanup = p_force_cleanup || !enabled || tile_set.is_null() || !is_visible_in_tree();
  202. if (forced_cleanup && _rendering_was_cleaned_up) {
  203. return;
  204. }
  205. // ----------- Layer level processing -----------
  206. // Modulate the layer.
  207. Color layer_modulate = get_self_modulate();
  208. #ifdef TOOLS_ENABLED
  209. if (!forced_cleanup) {
  210. layer_modulate = _highlight_color(layer_modulate);
  211. rs->canvas_item_set_self_modulate(get_canvas_item(), layer_modulate);
  212. }
  213. #endif // TOOLS_ENABLED
  214. // ----------- Quadrants processing -----------
  215. // List all rendering quadrants to update, creating new ones if needed.
  216. SelfList<RenderingQuadrant>::List dirty_rendering_quadrant_list;
  217. // Check if anything changed that might change the quadrant shape.
  218. // If so, recreate everything.
  219. bool quadrant_shape_changed = dirty.flags[DIRTY_FLAGS_LAYER_Y_SORT_ENABLED] || dirty.flags[DIRTY_FLAGS_TILE_SET] ||
  220. (is_y_sort_enabled() && (dirty.flags[DIRTY_FLAGS_LAYER_Y_SORT_ORIGIN] || dirty.flags[DIRTY_FLAGS_LAYER_X_DRAW_ORDER_REVERSED] || dirty.flags[DIRTY_FLAGS_LAYER_LOCAL_TRANSFORM])) ||
  221. (!is_y_sort_enabled() && dirty.flags[DIRTY_FLAGS_LAYER_RENDERING_QUADRANT_SIZE]);
  222. // Free all quadrants.
  223. if (!_rendering_was_cleaned_up && (forced_cleanup || quadrant_shape_changed)) {
  224. for (const KeyValue<Vector2i, Ref<RenderingQuadrant>> &kv : rendering_quadrant_map) {
  225. for (const RID &ci : kv.value->canvas_items) {
  226. if (ci.is_valid()) {
  227. rs->free_rid(ci);
  228. }
  229. }
  230. kv.value->cells.clear();
  231. }
  232. rendering_quadrant_map.clear();
  233. _rendering_was_cleaned_up = true;
  234. }
  235. if (!forced_cleanup) {
  236. // List all quadrants to update, recreating them if needed.
  237. if (dirty.flags[DIRTY_FLAGS_TILE_SET] || dirty.flags[DIRTY_FLAGS_LAYER_IN_TREE] || _rendering_was_cleaned_up) {
  238. // Update all cells.
  239. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  240. CellData &cell_data = kv.value;
  241. _rendering_quadrants_update_cell(cell_data, dirty_rendering_quadrant_list);
  242. }
  243. } else {
  244. // Update dirty cells.
  245. for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  246. CellData &cell_data = *cell_data_list_element->self();
  247. _rendering_quadrants_update_cell(cell_data, dirty_rendering_quadrant_list);
  248. }
  249. }
  250. // Update all dirty quadrants.
  251. bool needs_set_not_interpolated = SceneTree::is_fti_enabled() && !is_physics_interpolated();
  252. for (SelfList<RenderingQuadrant> *quadrant_list_element = dirty_rendering_quadrant_list.first(); quadrant_list_element;) {
  253. SelfList<RenderingQuadrant> *next_quadrant_list_element = quadrant_list_element->next(); // "Hack" to clear the list while iterating.
  254. const Ref<RenderingQuadrant> &rendering_quadrant = quadrant_list_element->self();
  255. // Check if the quadrant has a tile.
  256. bool has_a_tile = false;
  257. for (SelfList<CellData> *cell_data_list_element = rendering_quadrant->cells.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  258. CellData &cell_data = *cell_data_list_element->self();
  259. if (cell_data.cell.source_id != TileSet::INVALID_SOURCE) {
  260. has_a_tile = true;
  261. break;
  262. }
  263. }
  264. if (has_a_tile) {
  265. // Process the quadrant.
  266. // First, clear the quadrant's canvas items.
  267. for (RID &ci : rendering_quadrant->canvas_items) {
  268. rs->free_rid(ci);
  269. }
  270. rendering_quadrant->canvas_items.clear();
  271. // Sort the quadrant cells.
  272. if (is_y_sort_enabled() && x_draw_order_reversed) {
  273. rendering_quadrant->cells.sort_custom<CellDataYSortedXReversedComparator>();
  274. } else {
  275. rendering_quadrant->cells.sort();
  276. }
  277. // Those allow to group cell per material or z-index.
  278. Ref<Material> prev_material;
  279. int prev_z_index = 0;
  280. RID prev_ci;
  281. for (SelfList<CellData> *cell_data_quadrant_list_element = rendering_quadrant->cells.first(); cell_data_quadrant_list_element; cell_data_quadrant_list_element = cell_data_quadrant_list_element->next()) {
  282. CellData &cell_data = *cell_data_quadrant_list_element->self();
  283. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(*tile_set->get_source(cell_data.cell.source_id));
  284. // Get the tile data.
  285. const TileData *tile_data;
  286. if (cell_data.runtime_tile_data_cache) {
  287. tile_data = cell_data.runtime_tile_data_cache;
  288. } else {
  289. tile_data = atlas_source->get_tile_data(cell_data.cell.get_atlas_coords(), cell_data.cell.alternative_tile);
  290. }
  291. Ref<Material> mat = tile_data->get_material();
  292. int tile_z_index = tile_data->get_z_index();
  293. // Quandrant pos.
  294. // --- CanvasItems ---
  295. RID ci;
  296. // Check if the material or the z_index changed.
  297. if (prev_ci == RID() || prev_material != mat || prev_z_index != tile_z_index) {
  298. // If so, create a new CanvasItem.
  299. ci = rs->canvas_item_create();
  300. if (needs_set_not_interpolated) {
  301. rs->canvas_item_set_interpolated(ci, false);
  302. }
  303. if (mat.is_valid()) {
  304. rs->canvas_item_set_material(ci, mat->get_rid());
  305. }
  306. rs->canvas_item_set_parent(ci, get_canvas_item());
  307. rs->canvas_item_set_use_parent_material(ci, mat.is_null());
  308. Transform2D xform(0, rendering_quadrant->canvas_items_position);
  309. rs->canvas_item_set_transform(ci, xform);
  310. rs->canvas_item_set_light_mask(ci, get_light_mask());
  311. rs->canvas_item_set_z_as_relative_to_parent(ci, true);
  312. rs->canvas_item_set_z_index(ci, tile_z_index);
  313. rs->canvas_item_set_self_modulate(ci, layer_modulate);
  314. rs->canvas_item_set_default_texture_filter(ci, RS::CanvasItemTextureFilter(get_texture_filter_in_tree()));
  315. rs->canvas_item_set_default_texture_repeat(ci, RS::CanvasItemTextureRepeat(get_texture_repeat_in_tree()));
  316. rendering_quadrant->canvas_items.push_back(ci);
  317. prev_ci = ci;
  318. prev_material = mat;
  319. prev_z_index = tile_z_index;
  320. } else {
  321. // Keep the same canvas_item to draw on.
  322. ci = prev_ci;
  323. }
  324. const Vector2 local_tile_pos = tile_set->map_to_local(cell_data.coords);
  325. // Random animation offset.
  326. real_t random_animation_offset = 0.0;
  327. if (atlas_source->get_tile_animation_mode(cell_data.cell.get_atlas_coords()) != TileSetAtlasSource::TILE_ANIMATION_MODE_DEFAULT) {
  328. Array to_hash = { local_tile_pos, get_instance_id() }; // Use instance id as a random hash
  329. random_animation_offset = RandomPCG(to_hash.hash()).randf();
  330. }
  331. // Drawing the tile in the canvas item.
  332. draw_tile(ci, local_tile_pos - rendering_quadrant->canvas_items_position, tile_set, cell_data.cell.source_id, cell_data.cell.get_atlas_coords(), cell_data.cell.alternative_tile, -1, tile_data, random_animation_offset);
  333. }
  334. // Reset physics interpolation for any recreated canvas items.
  335. if (is_physics_interpolated_and_enabled() && is_visible_in_tree()) {
  336. for (const RID &ci : rendering_quadrant->canvas_items) {
  337. rs->canvas_item_reset_physics_interpolation(ci);
  338. }
  339. }
  340. } else {
  341. // Free the quadrant.
  342. for (const RID &ci : rendering_quadrant->canvas_items) {
  343. if (ci.is_valid()) {
  344. rs->free_rid(ci);
  345. }
  346. }
  347. rendering_quadrant->cells.clear();
  348. rendering_quadrant_map.erase(rendering_quadrant->quadrant_coords);
  349. }
  350. quadrant_list_element = next_quadrant_list_element;
  351. }
  352. dirty_rendering_quadrant_list.clear();
  353. // Reset the drawing indices.
  354. {
  355. int index = -(int64_t)0x80000000; // Always must be drawn below children.
  356. // Sort the quadrants coords per local coordinates.
  357. LocalVector<Pair<Vector2, Ref<RenderingQuadrant>>> sortable_quadrant_keys;
  358. sortable_quadrant_keys.reserve(rendering_quadrant_map.size());
  359. for (KeyValue<Vector2i, Ref<RenderingQuadrant>> &kv : rendering_quadrant_map) {
  360. Vector2 local_coords = tile_set->map_to_local(kv.value->quadrant_coords);
  361. sortable_quadrant_keys.push_back(Pair<Vector2, Ref<RenderingQuadrant>>(local_coords, kv.value));
  362. }
  363. struct PairedQuadrantSorter {
  364. RenderingQuadrant::CoordsWorldComparator comparator;
  365. _ALWAYS_INLINE_ bool operator()(const Pair<Vector2, Ref<RenderingQuadrant>> &p_a, const Pair<Vector2, Ref<RenderingQuadrant>> &p_b) const {
  366. return comparator(p_a.first, p_b.first);
  367. }
  368. };
  369. sortable_quadrant_keys.sort_custom<PairedQuadrantSorter>();
  370. // Set the draw indices.
  371. for (const Pair<Vector2, Ref<RenderingQuadrant>> &E : sortable_quadrant_keys) {
  372. for (const RID &ci : E.second->canvas_items) {
  373. RS::get_singleton()->canvas_item_set_draw_index(ci, index++);
  374. }
  375. }
  376. }
  377. // Updates on rendering changes.
  378. if (dirty.flags[DIRTY_FLAGS_LAYER_LIGHT_MASK] ||
  379. dirty.flags[DIRTY_FLAGS_LAYER_TEXTURE_FILTER] ||
  380. dirty.flags[DIRTY_FLAGS_LAYER_TEXTURE_REPEAT] ||
  381. dirty.flags[DIRTY_FLAGS_LAYER_SELF_MODULATE] ||
  382. dirty.flags[DIRTY_FLAGS_LAYER_HIGHLIGHT_MODE]) {
  383. for (KeyValue<Vector2i, Ref<RenderingQuadrant>> &kv : rendering_quadrant_map) {
  384. Ref<RenderingQuadrant> &rendering_quadrant = kv.value;
  385. for (const RID &ci : rendering_quadrant->canvas_items) {
  386. rs->canvas_item_set_light_mask(ci, get_light_mask());
  387. rs->canvas_item_set_default_texture_filter(ci, RS::CanvasItemTextureFilter(get_texture_filter_in_tree()));
  388. rs->canvas_item_set_default_texture_repeat(ci, RS::CanvasItemTextureRepeat(get_texture_repeat_in_tree()));
  389. rs->canvas_item_set_self_modulate(ci, layer_modulate);
  390. }
  391. }
  392. }
  393. }
  394. // -----------
  395. // Mark the rendering state as up to date.
  396. _rendering_was_cleaned_up = forced_cleanup;
  397. // ----------- Occluders processing -----------
  398. bool cleanup_occlusion = forced_cleanup || !occlusion_enabled;
  399. if (cleanup_occlusion && _occlusion_was_cleaned_up) {
  400. return;
  401. }
  402. if (cleanup_occlusion) {
  403. // Clean everything.
  404. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  405. _rendering_occluders_clear_cell(kv.value);
  406. }
  407. } else {
  408. if (_occlusion_was_cleaned_up || dirty.flags[DIRTY_FLAGS_TILE_SET]) {
  409. // Update all cells.
  410. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  411. _rendering_occluders_update_cell(kv.value);
  412. }
  413. } else {
  414. // Update dirty cells.
  415. for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  416. CellData &cell_data = *cell_data_list_element->self();
  417. _rendering_occluders_update_cell(cell_data);
  418. }
  419. }
  420. }
  421. // -----------
  422. // Mark the occlusion state as up to date.
  423. _occlusion_was_cleaned_up = cleanup_occlusion;
  424. }
  425. void TileMapLayer::_rendering_notification(int p_what) {
  426. RenderingServer *rs = RenderingServer::get_singleton();
  427. if (p_what == NOTIFICATION_TRANSFORM_CHANGED || p_what == NOTIFICATION_ENTER_CANVAS || p_what == NOTIFICATION_VISIBILITY_CHANGED) {
  428. if (tile_set.is_valid()) {
  429. Transform2D tilemap_xform = get_global_transform();
  430. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  431. const CellData &cell_data = kv.value;
  432. for (const LocalVector<RID> &polygons : cell_data.occluders) {
  433. for (const RID &rid : polygons) {
  434. if (rid.is_null()) {
  435. continue;
  436. }
  437. Transform2D xform(0, tile_set->map_to_local(kv.key));
  438. rs->canvas_light_occluder_attach_to_canvas(rid, get_canvas());
  439. rs->canvas_light_occluder_set_transform(rid, tilemap_xform * xform);
  440. }
  441. }
  442. }
  443. }
  444. } else if (p_what == NOTIFICATION_RESET_PHYSICS_INTERPOLATION) {
  445. if (is_physics_interpolated_and_enabled() && is_visible_in_tree()) {
  446. for (const KeyValue<Vector2i, Ref<RenderingQuadrant>> &kv : rendering_quadrant_map) {
  447. for (const RID &ci : kv.value->canvas_items) {
  448. if (ci.is_valid()) {
  449. rs->canvas_item_reset_physics_interpolation(ci);
  450. }
  451. }
  452. }
  453. }
  454. }
  455. }
  456. void TileMapLayer::_rendering_quadrants_update_cell(CellData &r_cell_data, SelfList<RenderingQuadrant>::List &r_dirty_rendering_quadrant_list) {
  457. // Check if the cell is valid and retrieve its y_sort_origin.
  458. bool is_valid = false;
  459. int tile_y_sort_origin = 0;
  460. TileSetSource *source;
  461. if (tile_set->has_source(r_cell_data.cell.source_id)) {
  462. source = *tile_set->get_source(r_cell_data.cell.source_id);
  463. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
  464. if (atlas_source && atlas_source->has_tile(r_cell_data.cell.get_atlas_coords()) && atlas_source->has_alternative_tile(r_cell_data.cell.get_atlas_coords(), r_cell_data.cell.alternative_tile)) {
  465. is_valid = true;
  466. const TileData *tile_data;
  467. if (r_cell_data.runtime_tile_data_cache) {
  468. tile_data = r_cell_data.runtime_tile_data_cache;
  469. } else {
  470. tile_data = atlas_source->get_tile_data(r_cell_data.cell.get_atlas_coords(), r_cell_data.cell.alternative_tile);
  471. }
  472. tile_y_sort_origin = tile_data->get_y_sort_origin();
  473. }
  474. }
  475. if (is_valid) {
  476. // Get the quadrant coords.
  477. Vector2 canvas_items_position;
  478. Vector2i quadrant_coords;
  479. if (is_y_sort_enabled()) {
  480. canvas_items_position = Vector2(0, tile_set->map_to_local(r_cell_data.coords).y + tile_y_sort_origin + y_sort_origin);
  481. quadrant_coords = canvas_items_position * 100;
  482. } else {
  483. const Vector2i &coords = r_cell_data.coords;
  484. // Rounding down, instead of simply rounding towards zero (truncating).
  485. quadrant_coords = _coords_to_quadrant_coords(coords, rendering_quadrant_size);
  486. canvas_items_position = tile_set->map_to_local(rendering_quadrant_size * quadrant_coords);
  487. }
  488. Ref<RenderingQuadrant> rendering_quadrant;
  489. if (rendering_quadrant_map.has(quadrant_coords)) {
  490. // Reuse existing rendering quadrant.
  491. rendering_quadrant = rendering_quadrant_map[quadrant_coords];
  492. } else {
  493. // Create a new rendering quadrant.
  494. rendering_quadrant.instantiate();
  495. rendering_quadrant->quadrant_coords = quadrant_coords;
  496. rendering_quadrant->canvas_items_position = canvas_items_position;
  497. rendering_quadrant_map[quadrant_coords] = rendering_quadrant;
  498. }
  499. // Mark the old quadrant as dirty (if it exists).
  500. if (r_cell_data.rendering_quadrant.is_valid()) {
  501. if (!r_cell_data.rendering_quadrant->dirty_quadrant_list_element.in_list()) {
  502. r_dirty_rendering_quadrant_list.add(&r_cell_data.rendering_quadrant->dirty_quadrant_list_element);
  503. }
  504. }
  505. // Remove the cell from that quadrant.
  506. if (r_cell_data.rendering_quadrant_list_element.in_list()) {
  507. r_cell_data.rendering_quadrant_list_element.remove_from_list();
  508. }
  509. // Add the cell to its new quadrant.
  510. r_cell_data.rendering_quadrant = rendering_quadrant;
  511. r_cell_data.rendering_quadrant->cells.add(&r_cell_data.rendering_quadrant_list_element);
  512. // Add the new quadrant to the dirty quadrant list.
  513. if (!rendering_quadrant->dirty_quadrant_list_element.in_list()) {
  514. r_dirty_rendering_quadrant_list.add(&rendering_quadrant->dirty_quadrant_list_element);
  515. }
  516. } else {
  517. Ref<RenderingQuadrant> rendering_quadrant = r_cell_data.rendering_quadrant;
  518. // Remove the cell from its quadrant.
  519. r_cell_data.rendering_quadrant = Ref<RenderingQuadrant>();
  520. if (r_cell_data.rendering_quadrant_list_element.in_list()) {
  521. rendering_quadrant->cells.remove(&r_cell_data.rendering_quadrant_list_element);
  522. }
  523. if (rendering_quadrant.is_valid()) {
  524. // Add the quadrant to the dirty quadrant list.
  525. if (!rendering_quadrant->dirty_quadrant_list_element.in_list()) {
  526. r_dirty_rendering_quadrant_list.add(&rendering_quadrant->dirty_quadrant_list_element);
  527. }
  528. }
  529. }
  530. }
  531. void TileMapLayer::_rendering_occluders_clear_cell(CellData &r_cell_data) {
  532. RenderingServer *rs = RenderingServer::get_singleton();
  533. // Free the occluders.
  534. for (const LocalVector<RID> &polygons : r_cell_data.occluders) {
  535. for (const RID &rid : polygons) {
  536. rs->free_rid(rid);
  537. }
  538. }
  539. r_cell_data.occluders.clear();
  540. }
  541. void TileMapLayer::_rendering_occluders_update_cell(CellData &r_cell_data) {
  542. RenderingServer *rs = RenderingServer::get_singleton();
  543. // Free unused occluders then resize the occluder array.
  544. for (uint32_t i = tile_set->get_occlusion_layers_count(); i < r_cell_data.occluders.size(); i++) {
  545. for (const RID &occluder_id : r_cell_data.occluders[i]) {
  546. if (occluder_id.is_valid()) {
  547. rs->free_rid(occluder_id);
  548. }
  549. }
  550. }
  551. r_cell_data.occluders.resize(tile_set->get_occlusion_layers_count());
  552. TileSetSource *source;
  553. if (tile_set->has_source(r_cell_data.cell.source_id)) {
  554. source = *tile_set->get_source(r_cell_data.cell.source_id);
  555. if (source->has_tile(r_cell_data.cell.get_atlas_coords()) && source->has_alternative_tile(r_cell_data.cell.get_atlas_coords(), r_cell_data.cell.alternative_tile)) {
  556. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
  557. if (atlas_source) {
  558. // Get the tile data.
  559. const TileData *tile_data;
  560. if (r_cell_data.runtime_tile_data_cache) {
  561. tile_data = r_cell_data.runtime_tile_data_cache;
  562. } else {
  563. tile_data = atlas_source->get_tile_data(r_cell_data.cell.get_atlas_coords(), r_cell_data.cell.alternative_tile);
  564. }
  565. // Transform flags.
  566. bool flip_h = (r_cell_data.cell.alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_H);
  567. bool flip_v = (r_cell_data.cell.alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_V);
  568. bool transpose = (r_cell_data.cell.alternative_tile & TileSetAtlasSource::TRANSFORM_TRANSPOSE);
  569. // Create, update or clear occluders.
  570. bool needs_set_not_interpolated = SceneTree::is_fti_enabled() && !is_physics_interpolated();
  571. for (uint32_t occlusion_layer_index = 0; occlusion_layer_index < r_cell_data.occluders.size(); occlusion_layer_index++) {
  572. LocalVector<RID> &occluders = r_cell_data.occluders[occlusion_layer_index];
  573. // Free unused occluders then resize the occluders array.
  574. for (uint32_t i = tile_data->get_occluder_polygons_count(occlusion_layer_index); i < r_cell_data.occluders[occlusion_layer_index].size(); i++) {
  575. RID occluder_id = occluders[i];
  576. if (occluder_id.is_valid()) {
  577. rs->free_rid(occluder_id);
  578. }
  579. }
  580. occluders.resize(tile_data->get_occluder_polygons_count(occlusion_layer_index));
  581. for (uint32_t occlusion_polygon_index = 0; occlusion_polygon_index < occluders.size(); occlusion_polygon_index++) {
  582. RID &occluder = occluders[occlusion_polygon_index];
  583. Ref<OccluderPolygon2D> occluder_polygon = tile_data->get_occluder_polygon(occlusion_layer_index, occlusion_polygon_index);
  584. if (occluder_polygon.is_valid()) {
  585. // Create or update occluder.
  586. Transform2D xform;
  587. xform.set_origin(tile_set->map_to_local(r_cell_data.coords));
  588. if (!occluder.is_valid()) {
  589. occluder = rs->canvas_light_occluder_create();
  590. if (needs_set_not_interpolated) {
  591. rs->canvas_light_occluder_set_interpolated(occluder, false);
  592. }
  593. }
  594. rs->canvas_light_occluder_set_transform(occluder, get_global_transform() * xform);
  595. rs->canvas_light_occluder_set_polygon(occluder, tile_data->get_occluder_polygon(occlusion_layer_index, occlusion_polygon_index, flip_h, flip_v, transpose)->get_rid());
  596. rs->canvas_light_occluder_attach_to_canvas(occluder, get_canvas());
  597. rs->canvas_light_occluder_set_light_mask(occluder, tile_set->get_occlusion_layer_light_mask(occlusion_layer_index));
  598. rs->canvas_light_occluder_set_as_sdf_collision(occluder, tile_set->get_occlusion_layer_sdf_collision(occlusion_layer_index));
  599. } else {
  600. // Clear occluder.
  601. if (occluder.is_valid()) {
  602. rs->free_rid(occluder);
  603. occluder = RID();
  604. }
  605. }
  606. }
  607. }
  608. return;
  609. }
  610. }
  611. }
  612. // If we did not return earlier, clear the cell.
  613. _rendering_occluders_clear_cell(r_cell_data);
  614. }
  615. #ifdef DEBUG_ENABLED
  616. void TileMapLayer::_rendering_draw_cell_debug(const RID &p_canvas_item, const Vector2 &p_quadrant_pos, const CellData &r_cell_data) {
  617. ERR_FAIL_COND(tile_set.is_null());
  618. if (!Engine::get_singleton()->is_editor_hint()) {
  619. return;
  620. }
  621. // Draw a placeholder for tiles needing one.
  622. RenderingServer *rs = RenderingServer::get_singleton();
  623. const TileMapCell &c = r_cell_data.cell;
  624. TileSetSource *source;
  625. if (tile_set->has_source(c.source_id)) {
  626. source = *tile_set->get_source(c.source_id);
  627. if (source->has_tile(c.get_atlas_coords()) && source->has_alternative_tile(c.get_atlas_coords(), c.alternative_tile)) {
  628. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
  629. if (atlas_source) {
  630. Vector2i grid_size = atlas_source->get_atlas_grid_size();
  631. if (atlas_source->get_runtime_texture().is_null() || c.get_atlas_coords().x >= grid_size.x || c.get_atlas_coords().y >= grid_size.y) {
  632. // Generate a random color from the hashed values of the tiles.
  633. Array to_hash = { c.source_id, c.get_atlas_coords(), c.alternative_tile };
  634. uint32_t hash = RandomPCG(to_hash.hash()).rand();
  635. Color color;
  636. color = color.from_hsv(
  637. (float)((hash >> 24) & 0xFF) / 256.0,
  638. Math::lerp(0.5, 1.0, (float)((hash >> 16) & 0xFF) / 256.0),
  639. Math::lerp(0.5, 1.0, (float)((hash >> 8) & 0xFF) / 256.0),
  640. 0.8);
  641. // Draw a placeholder tile.
  642. Transform2D cell_to_quadrant;
  643. cell_to_quadrant.set_origin(tile_set->map_to_local(r_cell_data.coords) - p_quadrant_pos);
  644. rs->canvas_item_add_set_transform(p_canvas_item, cell_to_quadrant);
  645. rs->canvas_item_add_circle(p_canvas_item, Vector2(), MIN(tile_set->get_tile_size().x, tile_set->get_tile_size().y) / 4.0, color);
  646. }
  647. }
  648. }
  649. }
  650. }
  651. #endif // DEBUG_ENABLED
  652. /////////////////////////////// Physics //////////////////////////////////////
  653. #ifndef PHYSICS_2D_DISABLED
  654. void TileMapLayer::_physics_update(bool p_force_cleanup) {
  655. PhysicsServer2D *ps = PhysicsServer2D::get_singleton();
  656. // Check if we should cleanup everything.
  657. bool forced_cleanup = p_force_cleanup || !enabled || !collision_enabled || !is_inside_tree() || tile_set.is_null();
  658. if (forced_cleanup && _physics_was_cleaned_up) {
  659. return;
  660. }
  661. // ----------- Quadrants processing -----------
  662. // List all physics quadrants to update, creating new ones if needed.
  663. SelfList<PhysicsQuadrant>::List dirty_physics_quadrant_list;
  664. // Check if anything changed that might change the quadrant shape.
  665. // If so, recreate everything.
  666. bool quadrant_shape_changed = dirty.flags[DIRTY_FLAGS_TILE_SET] || dirty.flags[DIRTY_FLAGS_LAYER_PHYSICS_QUADRANT_SIZE];
  667. // Free all quadrants.
  668. if (!_physics_was_cleaned_up && (forced_cleanup || quadrant_shape_changed)) {
  669. for (const KeyValue<Vector2i, Ref<PhysicsQuadrant>> &kv : physics_quadrant_map) {
  670. // Clear bodies.
  671. for (KeyValue<PhysicsQuadrant::PhysicsBodyKey, PhysicsQuadrant::PhysicsBodyValue> &kvbody : kv.value->bodies) {
  672. if (kvbody.value.body.is_valid()) {
  673. bodies_coords.erase(kvbody.value.body);
  674. ps->free_rid(kvbody.value.body);
  675. }
  676. }
  677. kv.value->bodies.clear();
  678. kv.value->cells.clear();
  679. }
  680. physics_quadrant_map.clear();
  681. _physics_was_cleaned_up = true;
  682. }
  683. if (!forced_cleanup) {
  684. RID space = get_world_2d()->get_space();
  685. Transform2D gl_transform = get_global_transform();
  686. // List all quadrants to update, recreating them if needed.
  687. if (dirty.flags[DIRTY_FLAGS_LAYER_IN_TREE] || _physics_was_cleaned_up) {
  688. // Update all cells.
  689. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  690. CellData &cell_data = kv.value;
  691. _physics_quadrants_update_cell(cell_data, dirty_physics_quadrant_list);
  692. }
  693. } else {
  694. // Update dirty cells.
  695. for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  696. CellData &cell_data = *cell_data_list_element->self();
  697. _physics_quadrants_update_cell(cell_data, dirty_physics_quadrant_list);
  698. }
  699. }
  700. // Update all dirty quadrants.
  701. for (SelfList<PhysicsQuadrant> *quadrant_list_element = dirty_physics_quadrant_list.first(); quadrant_list_element;) {
  702. SelfList<PhysicsQuadrant> *next_quadrant_list_element = quadrant_list_element->next(); // "Hack" to clear the list while iterating.
  703. const Ref<PhysicsQuadrant> &physics_quadrant = quadrant_list_element->self();
  704. // Check if the quadrant has a tile.
  705. bool has_a_tile = false;
  706. for (SelfList<CellData> *cell_data_list_element = physics_quadrant->cells.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  707. CellData &cell_data = *cell_data_list_element->self();
  708. if (cell_data.cell.source_id != TileSet::INVALID_SOURCE) {
  709. has_a_tile = true;
  710. break;
  711. }
  712. }
  713. if (has_a_tile) {
  714. // Process the quadrant.
  715. // First, clear the quadrant bodies.
  716. for (KeyValue<PhysicsQuadrant::PhysicsBodyKey, PhysicsQuadrant::PhysicsBodyValue> &kvbody : physics_quadrant->bodies) {
  717. RID &body = kvbody.value.body;
  718. if (body.is_valid()) {
  719. bodies_coords.erase(body);
  720. ps->free_rid(body);
  721. body = RID();
  722. }
  723. }
  724. physics_quadrant->bodies.clear();
  725. physics_quadrant->shapes.clear();
  726. // Quadrant origin
  727. Vector2 quadrant_origin = tile_set->map_to_local(physics_quadrant->quadrant_coords);
  728. // Recreate the quadrant bodies.
  729. for (uint32_t tile_set_physics_layer = 0; tile_set_physics_layer < (uint32_t)tile_set->get_physics_layers_count(); tile_set_physics_layer++) {
  730. Ref<PhysicsMaterial> physics_material = tile_set->get_physics_layer_physics_material(tile_set_physics_layer);
  731. uint32_t physics_layer = tile_set->get_physics_layer_collision_layer(tile_set_physics_layer);
  732. uint32_t physics_mask = tile_set->get_physics_layer_collision_mask(tile_set_physics_layer);
  733. // Merge polygons together for each quadrant.
  734. for (SelfList<CellData> *cell_data_quadrant_list_element = physics_quadrant->cells.first(); cell_data_quadrant_list_element; cell_data_quadrant_list_element = cell_data_quadrant_list_element->next()) {
  735. CellData &cell_data = *cell_data_quadrant_list_element->self();
  736. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(*tile_set->get_source(cell_data.cell.source_id));
  737. // Get the tile data.
  738. const TileData *tile_data;
  739. if (cell_data.runtime_tile_data_cache) {
  740. tile_data = cell_data.runtime_tile_data_cache;
  741. } else {
  742. tile_data = atlas_source->get_tile_data(cell_data.cell.get_atlas_coords(), cell_data.cell.alternative_tile);
  743. }
  744. // Transform flags.
  745. bool flip_h = (cell_data.cell.alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_H);
  746. bool flip_v = (cell_data.cell.alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_V);
  747. bool transpose = (cell_data.cell.alternative_tile & TileSetAtlasSource::TRANSFORM_TRANSPOSE);
  748. Vector2 linear_velocity = tile_data->get_constant_linear_velocity(tile_set_physics_layer);
  749. real_t angular_velocity = tile_data->get_constant_angular_velocity(tile_set_physics_layer);
  750. // Setup polygons for merge.
  751. for (int polygon_index = 0; polygon_index < tile_data->get_collision_polygons_count(tile_set_physics_layer); polygon_index++) {
  752. // Iterate over the polygons.
  753. int shapes_count = tile_data->get_collision_polygon_shapes_count(tile_set_physics_layer, polygon_index);
  754. // Check if we need to create a new body.
  755. PhysicsQuadrant::PhysicsBodyKey physics_body_key;
  756. physics_body_key.physics_layer = tile_set_physics_layer;
  757. physics_body_key.linear_velocity = linear_velocity;
  758. physics_body_key.angular_velocity = angular_velocity;
  759. physics_body_key.one_way_collision = tile_data->is_collision_polygon_one_way(tile_set_physics_layer, polygon_index);
  760. physics_body_key.one_way_collision_margin = tile_data->get_collision_polygon_one_way_margin(tile_set_physics_layer, polygon_index);
  761. physics_body_key.y_origin = map_to_local(cell_data.coords).y;
  762. if (!physics_quadrant->bodies.has(physics_body_key)) {
  763. RID body = ps->body_create();
  764. physics_quadrant->bodies[physics_body_key] = {};
  765. physics_quadrant->bodies[physics_body_key].body = body;
  766. bodies_coords[body] = physics_quadrant->quadrant_coords;
  767. // Create or update the body.
  768. ps->body_set_mode(body, use_kinematic_bodies ? PhysicsServer2D::BODY_MODE_KINEMATIC : PhysicsServer2D::BODY_MODE_STATIC);
  769. ps->body_set_space(body, space);
  770. Transform2D xform;
  771. xform.set_origin(quadrant_origin);
  772. xform = gl_transform * xform;
  773. ps->body_set_state(body, PhysicsServer2D::BODY_STATE_TRANSFORM, xform);
  774. ps->body_attach_object_instance_id(body, tile_map_node ? tile_map_node->get_instance_id() : get_instance_id());
  775. ps->body_set_collision_layer(body, physics_layer);
  776. ps->body_set_collision_mask(body, physics_mask);
  777. ps->body_set_pickable(body, false);
  778. ps->body_set_state(body, PhysicsServer2D::BODY_STATE_LINEAR_VELOCITY, linear_velocity);
  779. ps->body_set_state(body, PhysicsServer2D::BODY_STATE_ANGULAR_VELOCITY, angular_velocity);
  780. if (!physics_material.is_valid()) {
  781. ps->body_set_param(body, PhysicsServer2D::BODY_PARAM_BOUNCE, 0);
  782. ps->body_set_param(body, PhysicsServer2D::BODY_PARAM_FRICTION, 1);
  783. } else {
  784. ps->body_set_param(body, PhysicsServer2D::BODY_PARAM_BOUNCE, physics_material->computed_bounce());
  785. ps->body_set_param(body, PhysicsServer2D::BODY_PARAM_FRICTION, physics_material->computed_friction());
  786. }
  787. }
  788. for (int shape_index = 0; shape_index < shapes_count; shape_index++) {
  789. Ref<ConvexPolygonShape2D> shape = tile_data->get_collision_polygon_shape(tile_set_physics_layer, polygon_index, shape_index, flip_h, flip_v, transpose);
  790. // Translate the polygon.
  791. Vector<Vector2> convex_polygon = shape->get_points();
  792. for (int i = 0; i < convex_polygon.size(); i++) {
  793. convex_polygon.set(i, convex_polygon[i] + tile_set->map_to_local(cell_data.coords) - quadrant_origin);
  794. }
  795. physics_quadrant->bodies[physics_body_key].polygons.push_back(convex_polygon);
  796. }
  797. }
  798. }
  799. }
  800. // Iterate over the bodies
  801. for (const KeyValue<PhysicsQuadrant::PhysicsBodyKey, PhysicsQuadrant::PhysicsBodyValue> &kvbody : physics_quadrant->bodies) {
  802. // Actually merge the polygons.
  803. Vector<Vector<Vector2>> out_polygons;
  804. Vector<Vector<Vector2>> out_holes;
  805. Geometry2D::merge_many_polygons(kvbody.value.polygons, out_polygons, out_holes);
  806. // Create shapes for each polygon.
  807. int body_shape_index = 0;
  808. Vector<Vector<Vector2>> convex_polygons = Geometry2D::decompose_many_polygons_in_convex(out_polygons, out_holes);
  809. for (Vector<Vector2> &convex_polygon : convex_polygons) {
  810. Ref<ConvexPolygonShape2D> shape;
  811. shape.instantiate();
  812. shape->set_points(convex_polygon);
  813. ps->body_add_shape(kvbody.value.body, shape->get_rid());
  814. ps->body_set_shape_as_one_way_collision(kvbody.value.body, body_shape_index, kvbody.key.one_way_collision, kvbody.key.one_way_collision_margin);
  815. physics_quadrant->shapes.push_back(shape);
  816. body_shape_index++;
  817. }
  818. }
  819. } else {
  820. // Free the quadrant.
  821. for (KeyValue<PhysicsQuadrant::PhysicsBodyKey, PhysicsQuadrant::PhysicsBodyValue> &kv : physics_quadrant->bodies) {
  822. RID &body = kv.value.body;
  823. if (body.is_valid()) {
  824. bodies_coords.erase(body);
  825. ps->free_rid(body);
  826. }
  827. }
  828. physics_quadrant->bodies.clear();
  829. physics_quadrant->cells.clear();
  830. physics_quadrant_map.erase(physics_quadrant->quadrant_coords);
  831. }
  832. quadrant_list_element = next_quadrant_list_element;
  833. }
  834. dirty_physics_quadrant_list.clear();
  835. // Updates on physics changes.
  836. if (dirty.flags[DIRTY_FLAGS_LAYER_USE_KINEMATIC_BODIES]) {
  837. for (KeyValue<Vector2i, Ref<PhysicsQuadrant>> &kv : physics_quadrant_map) {
  838. Ref<PhysicsQuadrant> &physics_quadrant = kv.value;
  839. for (const KeyValue<PhysicsQuadrant::PhysicsBodyKey, PhysicsQuadrant::PhysicsBodyValue> &kvbody : physics_quadrant->bodies) {
  840. ps->body_set_mode(kvbody.value.body, use_kinematic_bodies ? PhysicsServer2D::BODY_MODE_KINEMATIC : PhysicsServer2D::BODY_MODE_STATIC);
  841. }
  842. }
  843. }
  844. }
  845. // -----------
  846. // Mark the physics state as up to date.
  847. _physics_was_cleaned_up = forced_cleanup;
  848. }
  849. void TileMapLayer::_physics_quadrants_update_cell(CellData &r_cell_data, SelfList<PhysicsQuadrant>::List &r_dirty_physics_quadrant_list) {
  850. // Check if the cell is valid and retrieve its y_sort_origin.
  851. bool is_valid = false;
  852. TileSetSource *source;
  853. if (tile_set->has_source(r_cell_data.cell.source_id)) {
  854. source = *tile_set->get_source(r_cell_data.cell.source_id);
  855. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
  856. if (atlas_source && atlas_source->has_tile(r_cell_data.cell.get_atlas_coords()) && atlas_source->has_alternative_tile(r_cell_data.cell.get_atlas_coords(), r_cell_data.cell.alternative_tile)) {
  857. is_valid = true;
  858. }
  859. }
  860. if (is_valid) {
  861. // Get the quadrant coords.
  862. const Vector2i &coords = r_cell_data.coords;
  863. Vector2i quadrant_coords = _coords_to_quadrant_coords(coords, physics_quadrant_size);
  864. Ref<PhysicsQuadrant> physics_quadrant;
  865. if (physics_quadrant_map.has(quadrant_coords)) {
  866. // Reuse existing physics quadrant.
  867. physics_quadrant = physics_quadrant_map[quadrant_coords];
  868. } else {
  869. // Create a new physics quadrant.
  870. physics_quadrant.instantiate();
  871. physics_quadrant->quadrant_coords = quadrant_coords;
  872. physics_quadrant_map[quadrant_coords] = physics_quadrant;
  873. }
  874. // Mark the old quadrant as dirty (if it exists).
  875. if (r_cell_data.physics_quadrant.is_valid()) {
  876. if (!r_cell_data.physics_quadrant->dirty_quadrant_list_element.in_list()) {
  877. r_dirty_physics_quadrant_list.add(&r_cell_data.physics_quadrant->dirty_quadrant_list_element);
  878. }
  879. }
  880. // Remove the cell from that quadrant.
  881. if (r_cell_data.physics_quadrant_list_element.in_list()) {
  882. r_cell_data.physics_quadrant_list_element.remove_from_list();
  883. }
  884. // Add the cell to its new quadrant.
  885. r_cell_data.physics_quadrant = physics_quadrant;
  886. r_cell_data.physics_quadrant->cells.add(&r_cell_data.physics_quadrant_list_element);
  887. // Add the new quadrant to the dirty quadrant list.
  888. if (!physics_quadrant->dirty_quadrant_list_element.in_list()) {
  889. r_dirty_physics_quadrant_list.add(&physics_quadrant->dirty_quadrant_list_element);
  890. }
  891. } else {
  892. Ref<PhysicsQuadrant> physics_quadrant = r_cell_data.physics_quadrant;
  893. // Remove the cell from its quadrant.
  894. r_cell_data.physics_quadrant = Ref<PhysicsQuadrant>();
  895. if (r_cell_data.physics_quadrant_list_element.in_list()) {
  896. physics_quadrant->cells.remove(&r_cell_data.physics_quadrant_list_element);
  897. }
  898. if (physics_quadrant.is_valid()) {
  899. // Add the quadrant to the dirty quadrant list.
  900. if (!physics_quadrant->dirty_quadrant_list_element.in_list()) {
  901. r_dirty_physics_quadrant_list.add(&physics_quadrant->dirty_quadrant_list_element);
  902. }
  903. }
  904. }
  905. }
  906. void TileMapLayer::_physics_notification(int p_what) {
  907. Transform2D gl_transform = get_global_transform();
  908. PhysicsServer2D *ps = PhysicsServer2D::get_singleton();
  909. switch (p_what) {
  910. case NOTIFICATION_TRANSFORM_CHANGED:
  911. // Move the collisison shapes along with the TileMap.
  912. if (is_inside_tree() && tile_set.is_valid()) {
  913. for (KeyValue<Vector2i, Ref<PhysicsQuadrant>> &kv : physics_quadrant_map) {
  914. for (const KeyValue<PhysicsQuadrant::PhysicsBodyKey, PhysicsQuadrant::PhysicsBodyValue> &kvbody : kv.value->bodies) {
  915. const RID &body = kvbody.value.body;
  916. Transform2D xform(0, tile_set->map_to_local(kv.key));
  917. xform = gl_transform * xform;
  918. ps->body_set_state(body, PhysicsServer2D::BODY_STATE_TRANSFORM, xform);
  919. }
  920. }
  921. }
  922. break;
  923. case NOTIFICATION_ENTER_TREE:
  924. // Changes in the tree may cause the space to change (e.g. when reparenting to a SubViewport).
  925. if (is_inside_tree()) {
  926. RID space = get_world_2d()->get_space();
  927. for (KeyValue<Vector2i, Ref<PhysicsQuadrant>> &kv : physics_quadrant_map) {
  928. for (const KeyValue<PhysicsQuadrant::PhysicsBodyKey, PhysicsQuadrant::PhysicsBodyValue> &kvbody : kv.value->bodies) {
  929. const RID &body = kvbody.value.body;
  930. ps->body_set_space(body, space);
  931. }
  932. }
  933. }
  934. }
  935. }
  936. #ifdef DEBUG_ENABLED
  937. void TileMapLayer::_physics_draw_quadrant_debug(const RID &p_canvas_item, DebugQuadrant &r_debug_quadrant) {
  938. // Draw the debug collision shapes.
  939. ERR_FAIL_COND(tile_set.is_null());
  940. if (!get_tree()) {
  941. return;
  942. }
  943. bool show_collision = false;
  944. switch (collision_visibility_mode) {
  945. case TileMapLayer::DEBUG_VISIBILITY_MODE_DEFAULT:
  946. show_collision = !Engine::get_singleton()->is_editor_hint() && get_tree()->is_debugging_collisions_hint();
  947. break;
  948. case TileMapLayer::DEBUG_VISIBILITY_MODE_FORCE_HIDE:
  949. show_collision = false;
  950. break;
  951. case TileMapLayer::DEBUG_VISIBILITY_MODE_FORCE_SHOW:
  952. show_collision = true;
  953. break;
  954. }
  955. if (!show_collision) {
  956. return;
  957. }
  958. RenderingServer *rs = RenderingServer::get_singleton();
  959. PhysicsServer2D *ps = PhysicsServer2D::get_singleton();
  960. const Color &debug_collision_color = get_tree()->get_debug_collisions_color();
  961. RandomPCG rand;
  962. rand.seed(hash_murmur3_one_real(r_debug_quadrant.quadrant_coords.y, hash_murmur3_one_real(r_debug_quadrant.quadrant_coords.x)));
  963. // Create a mesh.
  964. if (!r_debug_quadrant.physics_mesh.is_valid()) {
  965. r_debug_quadrant.physics_mesh = rs->mesh_create();
  966. }
  967. rs->mesh_clear(r_debug_quadrant.physics_mesh);
  968. // Redraw all shapes from the physics quadrants
  969. Rect2i covered_cell_area = Rect2i(r_debug_quadrant.quadrant_coords * TILE_MAP_DEBUG_QUADRANT_SIZE, Vector2i(TILE_MAP_DEBUG_QUADRANT_SIZE, TILE_MAP_DEBUG_QUADRANT_SIZE));
  970. Vector2i first_physics_quadrant_coords = _coords_to_quadrant_coords(covered_cell_area.get_position() - Vector2i(1, 1), physics_quadrant_size) + Vector2i(1, 1);
  971. Vector2i last_physics_quadrant_coords = _coords_to_quadrant_coords(covered_cell_area.get_end() - Vector2i(1, 1), physics_quadrant_size) + Vector2i(1, 1);
  972. LocalVector<Vector2> face_vertex_array;
  973. LocalVector<Color> face_color_array;
  974. LocalVector<int32_t> face_index_array;
  975. LocalVector<Vector2> line_vertex_array;
  976. LocalVector<Color> line_color_array;
  977. AHashMap<Vector2, int> vertex_map;
  978. // Arrays to generate a mesh.
  979. for (int x = first_physics_quadrant_coords.x; x < last_physics_quadrant_coords.x; x++) {
  980. for (int y = first_physics_quadrant_coords.y; y < last_physics_quadrant_coords.y; y++) {
  981. const Vector2i physics_quadrant_coords = Vector2i(x, y);
  982. if (!physics_quadrant_map.has(physics_quadrant_coords)) {
  983. continue;
  984. }
  985. r_debug_quadrant.drawn_to = true;
  986. Ref<PhysicsQuadrant> physics_quadrant = physics_quadrant_map[physics_quadrant_coords];
  987. const Vector2 debug_quadrant_pos = tile_set->map_to_local(r_debug_quadrant.quadrant_coords * TILE_MAP_DEBUG_QUADRANT_SIZE);
  988. Transform2D global_to_debug_quadrant = (get_global_transform() * Transform2D(0, debug_quadrant_pos)).affine_inverse();
  989. // Clear arrays for new quadrant while keeping allocated memory.
  990. face_vertex_array.clear();
  991. face_color_array.clear();
  992. face_index_array.clear();
  993. line_vertex_array.clear();
  994. line_color_array.clear();
  995. vertex_map.clear();
  996. for (const KeyValue<PhysicsQuadrant::PhysicsBodyKey, PhysicsQuadrant::PhysicsBodyValue> &kvbody : physics_quadrant->bodies) {
  997. const RID &body = kvbody.value.body;
  998. int shape_count = ps->body_get_shape_count(body);
  999. if (shape_count == 0) {
  1000. continue;
  1001. }
  1002. const Transform2D body_to_quadrant = global_to_debug_quadrant * Transform2D(ps->body_get_state(body, PhysicsServer2D::BODY_STATE_TRANSFORM));
  1003. Color face_random_variation_color;
  1004. face_random_variation_color.set_hsv(
  1005. debug_collision_color.get_h() + rand.random(-1.0, 1.0) * 0.05,
  1006. debug_collision_color.get_s(),
  1007. debug_collision_color.get_v() + rand.random(-1.0, 1.0) * 0.1,
  1008. debug_collision_color.a);
  1009. const Color line_random_variation_color = face_random_variation_color.lightened(0.2);
  1010. for (int shape_index = 0; shape_index < shape_count; shape_index++) {
  1011. const RID &shape = ps->body_get_shape(body, shape_index);
  1012. const Transform2D &shape_xform = ps->body_get_shape_transform(body, shape_index);
  1013. const PhysicsServer2D::ShapeType &type = ps->shape_get_type(shape);
  1014. if (type == PhysicsServer2D::SHAPE_CONVEX_POLYGON) {
  1015. PackedVector2Array outline = ps->shape_get_data(shape);
  1016. const int outline_size = outline.size();
  1017. if (outline_size < 3) {
  1018. continue;
  1019. }
  1020. const Transform2D outline_xform = body_to_quadrant * shape_xform;
  1021. // Adds debug mesh lines.
  1022. Vector2 previous_line_vertex = outline_xform.xform(outline[outline_size - 1]);
  1023. for (int i = 0; i < outline_size; i++) {
  1024. Vector2 line_vertex = outline_xform.xform(outline[i]);
  1025. line_vertex_array.push_back(previous_line_vertex);
  1026. line_vertex_array.push_back(line_vertex);
  1027. previous_line_vertex = line_vertex;
  1028. line_color_array.push_back(line_random_variation_color);
  1029. line_color_array.push_back(line_random_variation_color);
  1030. }
  1031. // Adds debug mesh faces.
  1032. const Vector2 vertex1 = outline_xform.xform(outline[0]);
  1033. const Vector2 vertex2 = outline_xform.xform(outline[1]);
  1034. Vector2 vertex3;
  1035. int vertex1_index = -1;
  1036. int vertex2_index = -1;
  1037. int vertex3_index = -1;
  1038. int last_vertex3_index = -1;
  1039. // Find triangle fan anchor vertex1 index.
  1040. {
  1041. AHashMap<Vector2, int>::Iterator E = vertex_map.find(vertex1);
  1042. if (!E) {
  1043. E = vertex_map.insert(vertex1, vertex_map.size());
  1044. face_vertex_array.push_back(vertex1);
  1045. face_color_array.push_back(face_random_variation_color);
  1046. }
  1047. vertex1_index = E->value;
  1048. }
  1049. // Find starting vertex2 index.
  1050. {
  1051. AHashMap<Vector2, int>::Iterator E = vertex_map.find(vertex2);
  1052. if (!E) {
  1053. E = vertex_map.insert(vertex2, vertex_map.size());
  1054. face_vertex_array.push_back(vertex2);
  1055. face_color_array.push_back(face_random_variation_color);
  1056. }
  1057. vertex2_index = E->value;
  1058. }
  1059. // Create mesh triangle face fan from outline vertices using vertex_map indices.
  1060. for (int i = 1; i < outline_size - 1; i++) {
  1061. if (i > 1) {
  1062. vertex2_index = last_vertex3_index;
  1063. }
  1064. vertex3 = outline_xform.xform(outline[i + 1]);
  1065. {
  1066. AHashMap<Vector2, int>::Iterator E = vertex_map.find(vertex3);
  1067. if (!E) {
  1068. E = vertex_map.insert(vertex3, vertex_map.size());
  1069. face_vertex_array.push_back(vertex3);
  1070. face_color_array.push_back(face_random_variation_color);
  1071. }
  1072. vertex3_index = E->value;
  1073. last_vertex3_index = vertex3_index;
  1074. }
  1075. face_index_array.push_back(vertex1_index);
  1076. face_index_array.push_back(vertex2_index);
  1077. face_index_array.push_back(vertex3_index);
  1078. }
  1079. } else {
  1080. WARN_PRINT("Wrong shape type for a tile, should be SHAPE_CONVEX_POLYGON.");
  1081. }
  1082. }
  1083. }
  1084. if (face_index_array.size() > 2) {
  1085. Array face_mesh_array;
  1086. face_mesh_array.resize(RS::ARRAY_MAX);
  1087. face_mesh_array[RS::ARRAY_VERTEX] = Vector<Vector2>(face_vertex_array);
  1088. face_mesh_array[RS::ARRAY_INDEX] = Vector<int32_t>(face_index_array);
  1089. face_mesh_array[RS::ARRAY_COLOR] = Vector<Color>(face_color_array);
  1090. rs->mesh_add_surface_from_arrays(r_debug_quadrant.physics_mesh, RS::PRIMITIVE_TRIANGLES, face_mesh_array, Array(), Dictionary(), RS::ARRAY_FLAG_USE_2D_VERTICES);
  1091. Array line_mesh_array;
  1092. line_mesh_array.resize(RS::ARRAY_MAX);
  1093. line_mesh_array[RS::ARRAY_VERTEX] = Vector<Vector2>(line_vertex_array);
  1094. line_mesh_array[RS::ARRAY_COLOR] = Vector<Color>(line_color_array);
  1095. rs->mesh_add_surface_from_arrays(r_debug_quadrant.physics_mesh, RS::PRIMITIVE_LINES, line_mesh_array, Array(), Dictionary(), RS::ARRAY_FLAG_USE_2D_VERTICES);
  1096. }
  1097. }
  1098. }
  1099. rs->canvas_item_add_mesh(p_canvas_item, r_debug_quadrant.physics_mesh, Transform2D());
  1100. }
  1101. #endif // DEBUG_ENABLED
  1102. #endif // PHYSICS_2D_DISABLED
  1103. #ifndef NAVIGATION_2D_DISABLED
  1104. /////////////////////////////// Navigation //////////////////////////////////////
  1105. void TileMapLayer::_navigation_update(bool p_force_cleanup) {
  1106. ERR_FAIL_NULL(NavigationServer2D::get_singleton());
  1107. NavigationServer2D *ns = NavigationServer2D::get_singleton();
  1108. // Check if we should cleanup everything.
  1109. bool forced_cleanup = p_force_cleanup || !enabled || !navigation_enabled || !is_inside_tree() || tile_set.is_null();
  1110. if (forced_cleanup && _navigation_was_cleaned_up) {
  1111. return;
  1112. }
  1113. // ----------- Layer level processing -----------
  1114. // All this processing is kept for compatibility with the TileMap node.
  1115. // Otherwise, layers shall use the World2D navigation map or define a custom one with set_navigation_map(...).
  1116. if (tile_map_node) {
  1117. if (forced_cleanup) {
  1118. if (navigation_map_override.is_valid()) {
  1119. ns->free_rid(navigation_map_override);
  1120. navigation_map_override = RID();
  1121. }
  1122. } else {
  1123. // Update navigation maps.
  1124. if (!navigation_map_override.is_valid()) {
  1125. if (layer_index_in_tile_map_node > 0) {
  1126. // Create a dedicated map for each layer.
  1127. RID new_layer_map = ns->map_create();
  1128. // Set the default NavigationPolygon cell_size on the new map as a mismatch causes an error.
  1129. ns->map_set_cell_size(new_layer_map, NavigationDefaults2D::NAV_MESH_CELL_SIZE);
  1130. ns->map_set_active(new_layer_map, true);
  1131. navigation_map_override = new_layer_map;
  1132. }
  1133. }
  1134. }
  1135. }
  1136. // ----------- Navigation regions processing -----------
  1137. if (forced_cleanup) {
  1138. // Clean everything.
  1139. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  1140. _navigation_clear_cell(kv.value);
  1141. }
  1142. } else {
  1143. if (_navigation_was_cleaned_up || dirty.flags[DIRTY_FLAGS_TILE_SET] || dirty.flags[DIRTY_FLAGS_LAYER_IN_TREE] || dirty.flags[DIRTY_FLAGS_LAYER_NAVIGATION_MAP]) {
  1144. // Update all cells.
  1145. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  1146. _navigation_update_cell(kv.value);
  1147. }
  1148. } else {
  1149. // Update dirty cells.
  1150. for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  1151. CellData &cell_data = *cell_data_list_element->self();
  1152. _navigation_update_cell(cell_data);
  1153. }
  1154. }
  1155. }
  1156. // -----------
  1157. // Mark the navigation state as up to date.
  1158. _navigation_was_cleaned_up = forced_cleanup;
  1159. }
  1160. void TileMapLayer::_navigation_notification(int p_what) {
  1161. if (p_what == NOTIFICATION_TRANSFORM_CHANGED) {
  1162. if (tile_set.is_valid()) {
  1163. Transform2D tilemap_xform = get_global_transform();
  1164. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  1165. const CellData &cell_data = kv.value;
  1166. // Update navigation regions transform.
  1167. for (const RID &region : cell_data.navigation_regions) {
  1168. if (!region.is_valid()) {
  1169. continue;
  1170. }
  1171. Transform2D tile_transform;
  1172. tile_transform.set_origin(tile_set->map_to_local(kv.key));
  1173. NavigationServer2D::get_singleton()->region_set_transform(region, tilemap_xform * tile_transform);
  1174. }
  1175. }
  1176. }
  1177. }
  1178. }
  1179. void TileMapLayer::_navigation_clear_cell(CellData &r_cell_data) {
  1180. NavigationServer2D *ns = NavigationServer2D::get_singleton();
  1181. // Clear navigation shapes.
  1182. for (uint32_t i = 0; i < r_cell_data.navigation_regions.size(); i++) {
  1183. const RID &region = r_cell_data.navigation_regions[i];
  1184. if (region.is_valid()) {
  1185. ns->region_set_map(region, RID());
  1186. ns->free_rid(region);
  1187. }
  1188. }
  1189. r_cell_data.navigation_regions.clear();
  1190. }
  1191. void TileMapLayer::_navigation_update_cell(CellData &r_cell_data) {
  1192. NavigationServer2D *ns = NavigationServer2D::get_singleton();
  1193. Transform2D gl_xform = get_global_transform();
  1194. RID navigation_map = navigation_map_override.is_valid() ? navigation_map_override : get_world_2d()->get_navigation_map();
  1195. ERR_FAIL_COND(navigation_map.is_null());
  1196. // Get the navigation polygons and create regions.
  1197. TileMapCell &c = r_cell_data.cell;
  1198. TileSetSource *source;
  1199. if (tile_set->has_source(c.source_id)) {
  1200. source = *tile_set->get_source(c.source_id);
  1201. if (source->has_tile(c.get_atlas_coords()) && source->has_alternative_tile(c.get_atlas_coords(), c.alternative_tile)) {
  1202. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
  1203. if (atlas_source) {
  1204. const TileData *tile_data;
  1205. if (r_cell_data.runtime_tile_data_cache) {
  1206. tile_data = r_cell_data.runtime_tile_data_cache;
  1207. } else {
  1208. tile_data = atlas_source->get_tile_data(c.get_atlas_coords(), c.alternative_tile);
  1209. }
  1210. // Transform flags.
  1211. bool flip_h = (c.alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_H);
  1212. bool flip_v = (c.alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_V);
  1213. bool transpose = (c.alternative_tile & TileSetAtlasSource::TRANSFORM_TRANSPOSE);
  1214. // Free unused regions then resize the regions array.
  1215. for (uint32_t i = tile_set->get_navigation_layers_count(); i < r_cell_data.navigation_regions.size(); i++) {
  1216. RID &region = r_cell_data.navigation_regions[i];
  1217. if (region.is_valid()) {
  1218. ns->region_set_map(region, RID());
  1219. ns->free_rid(region);
  1220. region = RID();
  1221. }
  1222. }
  1223. r_cell_data.navigation_regions.resize(tile_set->get_navigation_layers_count());
  1224. // Create, update or clear regions.
  1225. for (uint32_t navigation_layer_index = 0; navigation_layer_index < r_cell_data.navigation_regions.size(); navigation_layer_index++) {
  1226. Ref<NavigationPolygon> navigation_polygon = tile_data->get_navigation_polygon(navigation_layer_index, flip_h, flip_v, transpose);
  1227. RID &region = r_cell_data.navigation_regions[navigation_layer_index];
  1228. if (navigation_polygon.is_valid() && (navigation_polygon->get_polygon_count() > 0 || navigation_polygon->get_outline_count() > 0)) {
  1229. // Create or update regions.
  1230. Transform2D tile_transform;
  1231. tile_transform.set_origin(tile_set->map_to_local(r_cell_data.coords));
  1232. if (!region.is_valid()) {
  1233. region = ns->region_create();
  1234. }
  1235. ns->region_set_owner_id(region, tile_map_node ? tile_map_node->get_instance_id() : get_instance_id());
  1236. ns->region_set_map(region, navigation_map);
  1237. ns->region_set_transform(region, gl_xform * tile_transform);
  1238. ns->region_set_navigation_layers(region, tile_set->get_navigation_layer_layers(navigation_layer_index));
  1239. ns->region_set_navigation_polygon(region, navigation_polygon);
  1240. } else {
  1241. // Clear region.
  1242. if (region.is_valid()) {
  1243. ns->region_set_map(region, RID());
  1244. ns->free_rid(region);
  1245. region = RID();
  1246. }
  1247. }
  1248. }
  1249. return;
  1250. }
  1251. }
  1252. }
  1253. // If we did not return earlier, clear the cell.
  1254. _navigation_clear_cell(r_cell_data);
  1255. }
  1256. #ifdef DEBUG_ENABLED
  1257. void TileMapLayer::_navigation_draw_cell_debug(const RID &p_canvas_item, const Vector2 &p_quadrant_pos, const CellData &r_cell_data) {
  1258. // Draw the debug collision shapes.
  1259. bool show_navigation = false;
  1260. switch (navigation_visibility_mode) {
  1261. case TileMapLayer::DEBUG_VISIBILITY_MODE_DEFAULT:
  1262. show_navigation = !Engine::get_singleton()->is_editor_hint() && get_tree()->is_debugging_navigation_hint();
  1263. break;
  1264. case TileMapLayer::DEBUG_VISIBILITY_MODE_FORCE_HIDE:
  1265. show_navigation = false;
  1266. break;
  1267. case TileMapLayer::DEBUG_VISIBILITY_MODE_FORCE_SHOW:
  1268. show_navigation = true;
  1269. break;
  1270. }
  1271. if (!show_navigation) {
  1272. return;
  1273. }
  1274. // Check if the navigation is used.
  1275. if (r_cell_data.navigation_regions.is_empty()) {
  1276. return;
  1277. }
  1278. RenderingServer *rs = RenderingServer::get_singleton();
  1279. const NavigationServer2D *ns2d = NavigationServer2D::get_singleton();
  1280. bool enabled_geometry_face_random_color = ns2d->get_debug_navigation_enable_geometry_face_random_color();
  1281. bool enabled_edge_lines = ns2d->get_debug_navigation_enable_edge_lines();
  1282. Color debug_face_color = ns2d->get_debug_navigation_geometry_face_color();
  1283. Color debug_edge_color = ns2d->get_debug_navigation_geometry_edge_color();
  1284. RandomPCG rand;
  1285. const TileMapCell &c = r_cell_data.cell;
  1286. TileSetSource *source;
  1287. if (tile_set->has_source(c.source_id)) {
  1288. source = *tile_set->get_source(c.source_id);
  1289. if (source->has_tile(c.get_atlas_coords()) && source->has_alternative_tile(c.get_atlas_coords(), c.alternative_tile)) {
  1290. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
  1291. if (atlas_source) {
  1292. const TileData *tile_data;
  1293. if (r_cell_data.runtime_tile_data_cache) {
  1294. tile_data = r_cell_data.runtime_tile_data_cache;
  1295. } else {
  1296. tile_data = atlas_source->get_tile_data(c.get_atlas_coords(), c.alternative_tile);
  1297. }
  1298. Transform2D cell_to_quadrant;
  1299. cell_to_quadrant.set_origin(tile_set->map_to_local(r_cell_data.coords) - p_quadrant_pos);
  1300. rs->canvas_item_add_set_transform(p_canvas_item, cell_to_quadrant);
  1301. for (int layer_index = 0; layer_index < tile_set->get_navigation_layers_count(); layer_index++) {
  1302. bool flip_h = (c.alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_H);
  1303. bool flip_v = (c.alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_V);
  1304. bool transpose = (c.alternative_tile & TileSetAtlasSource::TRANSFORM_TRANSPOSE);
  1305. Ref<NavigationPolygon> navigation_polygon = tile_data->get_navigation_polygon(layer_index, flip_h, flip_v, transpose);
  1306. if (navigation_polygon.is_valid()) {
  1307. Vector<Vector2> navigation_polygon_vertices = navigation_polygon->get_vertices();
  1308. if (navigation_polygon_vertices.size() < 3) {
  1309. continue;
  1310. }
  1311. for (int i = 0; i < navigation_polygon->get_polygon_count(); i++) {
  1312. // An array of vertices for this polygon.
  1313. Vector<int> polygon = navigation_polygon->get_polygon(i);
  1314. Vector<Vector2> debug_polygon_vertices;
  1315. debug_polygon_vertices.resize(polygon.size());
  1316. for (int j = 0; j < polygon.size(); j++) {
  1317. ERR_FAIL_INDEX(polygon[j], navigation_polygon_vertices.size());
  1318. debug_polygon_vertices.write[j] = navigation_polygon_vertices[polygon[j]];
  1319. }
  1320. // Generate the polygon color, slightly randomly modified from the settings one.
  1321. Color random_variation_color = debug_face_color;
  1322. if (enabled_geometry_face_random_color) {
  1323. random_variation_color.set_hsv(
  1324. debug_face_color.get_h() + rand.random(-1.0, 1.0) * 0.1,
  1325. debug_face_color.get_s(),
  1326. debug_face_color.get_v() + rand.random(-1.0, 1.0) * 0.2);
  1327. }
  1328. random_variation_color.a = debug_face_color.a;
  1329. Vector<Color> debug_face_colors;
  1330. debug_face_colors.push_back(random_variation_color);
  1331. rs->canvas_item_add_polygon(p_canvas_item, debug_polygon_vertices, debug_face_colors);
  1332. if (enabled_edge_lines) {
  1333. Vector<Color> debug_edge_colors;
  1334. debug_edge_colors.push_back(debug_edge_color);
  1335. debug_polygon_vertices.push_back(debug_polygon_vertices[0]); // Add first again for closing polyline.
  1336. rs->canvas_item_add_polyline(p_canvas_item, debug_polygon_vertices, debug_edge_colors);
  1337. }
  1338. }
  1339. }
  1340. }
  1341. }
  1342. }
  1343. }
  1344. }
  1345. #endif // DEBUG_ENABLED
  1346. #endif // NAVIGATION_2D_DISABLED
  1347. /////////////////////////////// Scenes //////////////////////////////////////
  1348. void TileMapLayer::_scenes_update(bool p_force_cleanup) {
  1349. // Check if we should cleanup everything.
  1350. bool forced_cleanup = p_force_cleanup || !enabled || !is_inside_tree() || tile_set.is_null();
  1351. if (forced_cleanup && _scenes_was_cleaned_up) {
  1352. return;
  1353. }
  1354. if (forced_cleanup) {
  1355. // Clean everything.
  1356. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  1357. _scenes_clear_cell(kv.value);
  1358. }
  1359. } else {
  1360. if (_scenes_was_cleaned_up || dirty.flags[DIRTY_FLAGS_TILE_SET] || dirty.flags[DIRTY_FLAGS_LAYER_IN_TREE] || dirty.flags[DIRTY_FLAGS_LAYER_HIGHLIGHT_MODE]) {
  1361. // Update all cells.
  1362. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  1363. _scenes_update_cell(kv.value);
  1364. }
  1365. } else {
  1366. // Update dirty cells.
  1367. for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  1368. CellData &cell_data = *cell_data_list_element->self();
  1369. _scenes_update_cell(cell_data);
  1370. }
  1371. }
  1372. }
  1373. // -----------
  1374. // Mark the scenes state as up to date.
  1375. _scenes_was_cleaned_up = forced_cleanup;
  1376. }
  1377. void TileMapLayer::_scenes_clear_cell(CellData &r_cell_data) {
  1378. // Cleanup existing scene.
  1379. Node *node = nullptr;
  1380. if (tile_map_node) {
  1381. // Compatibility with TileMap.
  1382. node = tile_map_node->get_node_or_null(r_cell_data.scene);
  1383. } else {
  1384. node = get_node_or_null(r_cell_data.scene);
  1385. }
  1386. if (node) {
  1387. node->queue_free();
  1388. }
  1389. r_cell_data.scene = "";
  1390. }
  1391. void TileMapLayer::_scenes_update_cell(CellData &r_cell_data) {
  1392. // Clear the scene in any case.
  1393. _scenes_clear_cell(r_cell_data);
  1394. // Create the scene.
  1395. const TileMapCell &c = r_cell_data.cell;
  1396. TileSetSource *source;
  1397. if (tile_set->has_source(c.source_id)) {
  1398. source = *tile_set->get_source(c.source_id);
  1399. if (source->has_tile(c.get_atlas_coords()) && source->has_alternative_tile(c.get_atlas_coords(), c.alternative_tile)) {
  1400. TileSetScenesCollectionSource *scenes_collection_source = Object::cast_to<TileSetScenesCollectionSource>(source);
  1401. if (scenes_collection_source) {
  1402. Ref<PackedScene> packed_scene = scenes_collection_source->get_scene_tile_scene(c.alternative_tile);
  1403. if (packed_scene.is_valid()) {
  1404. Node *scene = packed_scene->instantiate();
  1405. Control *scene_as_control = Object::cast_to<Control>(scene);
  1406. Node2D *scene_as_node2d = Object::cast_to<Node2D>(scene);
  1407. if (scene_as_control) {
  1408. scene_as_control->set_position(tile_set->map_to_local(r_cell_data.coords) + scene_as_control->get_position());
  1409. } else if (scene_as_node2d) {
  1410. _set_scene_transform_with_alternative(scene_as_node2d, tile_set->map_to_local(r_cell_data.coords), c.alternative_tile);
  1411. }
  1412. #ifdef TOOLS_ENABLED
  1413. RenderingServer *rs = RenderingServer::get_singleton();
  1414. CanvasItem *scene_as_ci = Object::cast_to<CanvasItem>(scene);
  1415. if (scene_as_ci) {
  1416. rs->canvas_item_set_modulate(scene_as_ci->get_canvas_item(), _highlight_color(scene_as_ci->get_modulate()));
  1417. }
  1418. #endif // TOOLS_ENABLED
  1419. if (tile_map_node) {
  1420. // Compatibility with TileMap.
  1421. tile_map_node->add_child(scene);
  1422. } else {
  1423. add_child(scene);
  1424. }
  1425. r_cell_data.scene = scene->get_name();
  1426. }
  1427. }
  1428. }
  1429. }
  1430. }
  1431. #ifdef DEBUG_ENABLED
  1432. void TileMapLayer::_scenes_draw_cell_debug(const RID &p_canvas_item, const Vector2 &p_quadrant_pos, const CellData &r_cell_data) {
  1433. ERR_FAIL_COND(tile_set.is_null());
  1434. if (!Engine::get_singleton()->is_editor_hint()) {
  1435. return;
  1436. }
  1437. // Draw a placeholder for scenes needing one.
  1438. RenderingServer *rs = RenderingServer::get_singleton();
  1439. const TileMapCell &c = r_cell_data.cell;
  1440. TileSetSource *source;
  1441. if (tile_set->has_source(c.source_id)) {
  1442. source = *tile_set->get_source(c.source_id);
  1443. if (!source->has_tile(c.get_atlas_coords()) || !source->has_alternative_tile(c.get_atlas_coords(), c.alternative_tile)) {
  1444. return;
  1445. }
  1446. TileSetScenesCollectionSource *scenes_collection_source = Object::cast_to<TileSetScenesCollectionSource>(source);
  1447. if (scenes_collection_source) {
  1448. if (scenes_collection_source->get_scene_tile_scene(c.alternative_tile).is_null() || scenes_collection_source->get_scene_tile_display_placeholder(c.alternative_tile)) {
  1449. // Generate a random color from the hashed values of the tiles.
  1450. Array to_hash = { c.source_id, c.alternative_tile };
  1451. uint32_t hash = RandomPCG(to_hash.hash()).rand();
  1452. Color color;
  1453. color = color.from_hsv(
  1454. (float)((hash >> 24) & 0xFF) / 256.0,
  1455. Math::lerp(0.5, 1.0, (float)((hash >> 16) & 0xFF) / 256.0),
  1456. Math::lerp(0.5, 1.0, (float)((hash >> 8) & 0xFF) / 256.0),
  1457. 0.8);
  1458. // Draw a placeholder tile.
  1459. Transform2D cell_to_quadrant;
  1460. cell_to_quadrant.set_origin(tile_set->map_to_local(r_cell_data.coords) - p_quadrant_pos);
  1461. rs->canvas_item_add_set_transform(p_canvas_item, cell_to_quadrant);
  1462. rs->canvas_item_add_circle(p_canvas_item, Vector2(), MIN(tile_set->get_tile_size().x, tile_set->get_tile_size().y) / 4.0, color);
  1463. }
  1464. }
  1465. }
  1466. }
  1467. #endif // DEBUG_ENABLED
  1468. void TileMapLayer::_set_scene_transform_with_alternative(Node2D *p_scene, const Vector2 &p_cell_position, const int p_alternative_id) {
  1469. // Determine the transformations based on the alternative ID.
  1470. bool transform_flip_h = p_alternative_id & TileSetAtlasSource::TRANSFORM_FLIP_H;
  1471. bool transform_flip_v = p_alternative_id & TileSetAtlasSource::TRANSFORM_FLIP_V;
  1472. bool transform_transpose = p_alternative_id & TileSetAtlasSource::TRANSFORM_TRANSPOSE;
  1473. int axis_h = transform_transpose ? 1 : 0;
  1474. int axis_v = 1 - axis_h;
  1475. Transform2D xform;
  1476. xform[axis_h].x = transform_flip_h ? -1.0f : 1.0f;
  1477. xform[axis_h].y = 0.0f;
  1478. xform[axis_v].x = 0.0f;
  1479. xform[axis_v].y = transform_flip_v ? -1.0f : 1.0f;
  1480. xform.set_origin(p_cell_position);
  1481. p_scene->set_transform(xform * p_scene->get_transform());
  1482. }
  1483. /////////////////////////////////////////////////////////////////////
  1484. void TileMapLayer::_build_runtime_update_tile_data(bool p_force_cleanup) {
  1485. // Check if we should cleanup everything.
  1486. bool forced_cleanup = p_force_cleanup || !enabled || tile_set.is_null() || !is_visible_in_tree();
  1487. if (!forced_cleanup) {
  1488. bool valid_runtime_update = GDVIRTUAL_IS_OVERRIDDEN(_use_tile_data_runtime_update) && GDVIRTUAL_IS_OVERRIDDEN(_tile_data_runtime_update);
  1489. bool valid_runtime_update_for_tilemap = tile_map_node && tile_map_node->GDVIRTUAL_IS_OVERRIDDEN(_use_tile_data_runtime_update) && tile_map_node->GDVIRTUAL_IS_OVERRIDDEN(_tile_data_runtime_update); // For keeping compatibility.
  1490. if (valid_runtime_update || valid_runtime_update_for_tilemap) {
  1491. bool use_tilemap_for_runtime = valid_runtime_update_for_tilemap && !valid_runtime_update;
  1492. if (_runtime_update_tile_data_was_cleaned_up || dirty.flags[DIRTY_FLAGS_TILE_SET]) {
  1493. _runtime_update_needs_all_cells_cleaned_up = true;
  1494. for (KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
  1495. _build_runtime_update_tile_data_for_cell(E.value, use_tilemap_for_runtime);
  1496. }
  1497. } else if (dirty.flags[DIRTY_FLAGS_LAYER_RUNTIME_UPDATE]) {
  1498. for (KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
  1499. _build_runtime_update_tile_data_for_cell(E.value, use_tilemap_for_runtime, true);
  1500. }
  1501. } else {
  1502. for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  1503. CellData &cell_data = *cell_data_list_element->self();
  1504. _build_runtime_update_tile_data_for_cell(cell_data, use_tilemap_for_runtime);
  1505. }
  1506. }
  1507. }
  1508. }
  1509. // -----------
  1510. // Mark the tile data state as up to date.
  1511. _runtime_update_tile_data_was_cleaned_up = forced_cleanup;
  1512. }
  1513. void TileMapLayer::_build_runtime_update_tile_data_for_cell(CellData &r_cell_data, bool p_use_tilemap_for_runtime, bool p_auto_add_to_dirty_list) {
  1514. TileMapCell &c = r_cell_data.cell;
  1515. TileSetSource *source;
  1516. if (tile_set->has_source(c.source_id)) {
  1517. source = *tile_set->get_source(c.source_id);
  1518. if (source->has_tile(c.get_atlas_coords()) && source->has_alternative_tile(c.get_atlas_coords(), c.alternative_tile)) {
  1519. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
  1520. if (atlas_source) {
  1521. bool ret = false;
  1522. if (p_use_tilemap_for_runtime) {
  1523. // Compatibility with TileMap.
  1524. if (tile_map_node->GDVIRTUAL_CALL(_use_tile_data_runtime_update, layer_index_in_tile_map_node, r_cell_data.coords, ret) && ret) {
  1525. TileData *tile_data = atlas_source->get_tile_data(c.get_atlas_coords(), c.alternative_tile);
  1526. // Create the runtime TileData.
  1527. TileData *tile_data_runtime_use = tile_data->duplicate();
  1528. tile_data_runtime_use->set_allow_transform(true);
  1529. r_cell_data.runtime_tile_data_cache = tile_data_runtime_use;
  1530. tile_map_node->GDVIRTUAL_CALL(_tile_data_runtime_update, layer_index_in_tile_map_node, r_cell_data.coords, tile_data_runtime_use);
  1531. if (p_auto_add_to_dirty_list && !r_cell_data.dirty_list_element.in_list()) {
  1532. dirty.cell_list.add(&r_cell_data.dirty_list_element);
  1533. }
  1534. }
  1535. } else {
  1536. if (GDVIRTUAL_CALL(_use_tile_data_runtime_update, r_cell_data.coords, ret) && ret) {
  1537. TileData *tile_data = atlas_source->get_tile_data(c.get_atlas_coords(), c.alternative_tile);
  1538. // Create the runtime TileData.
  1539. TileData *tile_data_runtime_use = tile_data->duplicate();
  1540. tile_data_runtime_use->set_allow_transform(true);
  1541. r_cell_data.runtime_tile_data_cache = tile_data_runtime_use;
  1542. GDVIRTUAL_CALL(_tile_data_runtime_update, r_cell_data.coords, tile_data_runtime_use);
  1543. if (p_auto_add_to_dirty_list && !r_cell_data.dirty_list_element.in_list()) {
  1544. dirty.cell_list.add(&r_cell_data.dirty_list_element);
  1545. }
  1546. }
  1547. }
  1548. }
  1549. }
  1550. }
  1551. }
  1552. void TileMapLayer::_clear_runtime_update_tile_data() {
  1553. if (_runtime_update_needs_all_cells_cleaned_up) {
  1554. for (KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
  1555. _clear_runtime_update_tile_data_for_cell(E.value);
  1556. }
  1557. _runtime_update_needs_all_cells_cleaned_up = false;
  1558. } else {
  1559. for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  1560. CellData &r_cell_data = *cell_data_list_element->self();
  1561. _clear_runtime_update_tile_data_for_cell(r_cell_data);
  1562. }
  1563. }
  1564. }
  1565. void TileMapLayer::_clear_runtime_update_tile_data_for_cell(CellData &r_cell_data) {
  1566. // Clear the runtime tile data.
  1567. if (r_cell_data.runtime_tile_data_cache) {
  1568. memdelete(r_cell_data.runtime_tile_data_cache);
  1569. r_cell_data.runtime_tile_data_cache = nullptr;
  1570. }
  1571. }
  1572. void TileMapLayer::_update_cells_callback(bool p_force_cleanup) {
  1573. if (!GDVIRTUAL_IS_OVERRIDDEN(_update_cells)) {
  1574. return;
  1575. }
  1576. // Check if we should cleanup everything.
  1577. bool forced_cleanup = p_force_cleanup || !enabled || tile_set.is_null() || !is_visible_in_tree();
  1578. // List all the dirty cell's positions to notify script of cell updates.
  1579. TypedArray<Vector2i> dirty_cell_positions;
  1580. for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  1581. CellData &cell_data = *cell_data_list_element->self();
  1582. dirty_cell_positions.push_back(cell_data.coords);
  1583. }
  1584. GDVIRTUAL_CALL(_update_cells, dirty_cell_positions, forced_cleanup);
  1585. }
  1586. TileSet::TerrainsPattern TileMapLayer::_get_best_terrain_pattern_for_constraints(int p_terrain_set, const Vector2i &p_position, const RBSet<TerrainConstraint> &p_constraints, TileSet::TerrainsPattern p_current_pattern) const {
  1587. if (tile_set.is_null()) {
  1588. return TileSet::TerrainsPattern();
  1589. }
  1590. // Returns all tiles compatible with the given constraints.
  1591. RBMap<TileSet::TerrainsPattern, int> terrain_pattern_score;
  1592. RBSet<TileSet::TerrainsPattern> pattern_set = tile_set->get_terrains_pattern_set(p_terrain_set);
  1593. ERR_FAIL_COND_V(pattern_set.is_empty(), TileSet::TerrainsPattern());
  1594. for (TileSet::TerrainsPattern &terrain_pattern : pattern_set) {
  1595. int score = 0;
  1596. // Check the center bit constraint.
  1597. TerrainConstraint terrain_constraint = TerrainConstraint(tile_set, p_position, terrain_pattern.get_terrain());
  1598. const RBSet<TerrainConstraint>::Element *in_set_constraint_element = p_constraints.find(terrain_constraint);
  1599. if (in_set_constraint_element) {
  1600. if (in_set_constraint_element->get().get_terrain() != terrain_constraint.get_terrain()) {
  1601. score += in_set_constraint_element->get().get_priority();
  1602. }
  1603. } else if (p_current_pattern.get_terrain() != terrain_pattern.get_terrain()) {
  1604. continue; // Ignore a pattern that cannot keep bits without constraints unmodified.
  1605. }
  1606. // Check the surrounding bits
  1607. bool invalid_pattern = false;
  1608. for (int i = 0; i < TileSet::CELL_NEIGHBOR_MAX; i++) {
  1609. TileSet::CellNeighbor bit = TileSet::CellNeighbor(i);
  1610. if (tile_set->is_valid_terrain_peering_bit(p_terrain_set, bit)) {
  1611. // Check if the bit is compatible with the constraints.
  1612. TerrainConstraint terrain_bit_constraint = TerrainConstraint(tile_set, p_position, bit, terrain_pattern.get_terrain_peering_bit(bit));
  1613. in_set_constraint_element = p_constraints.find(terrain_bit_constraint);
  1614. if (in_set_constraint_element) {
  1615. if (in_set_constraint_element->get().get_terrain() != terrain_bit_constraint.get_terrain()) {
  1616. score += in_set_constraint_element->get().get_priority();
  1617. }
  1618. } else if (p_current_pattern.get_terrain_peering_bit(bit) != terrain_pattern.get_terrain_peering_bit(bit)) {
  1619. invalid_pattern = true; // Ignore a pattern that cannot keep bits without constraints unmodified.
  1620. break;
  1621. }
  1622. }
  1623. }
  1624. if (invalid_pattern) {
  1625. continue;
  1626. }
  1627. terrain_pattern_score[terrain_pattern] = score;
  1628. }
  1629. // Compute the minimum score.
  1630. TileSet::TerrainsPattern min_score_pattern = p_current_pattern;
  1631. int min_score = INT32_MAX;
  1632. for (KeyValue<TileSet::TerrainsPattern, int> E : terrain_pattern_score) {
  1633. if (E.value < min_score) {
  1634. min_score_pattern = E.key;
  1635. min_score = E.value;
  1636. }
  1637. }
  1638. return min_score_pattern;
  1639. }
  1640. RBSet<TerrainConstraint> TileMapLayer::_get_terrain_constraints_from_added_pattern(const Vector2i &p_position, int p_terrain_set, TileSet::TerrainsPattern p_terrains_pattern) const {
  1641. if (tile_set.is_null()) {
  1642. return RBSet<TerrainConstraint>();
  1643. }
  1644. // Compute the constraints needed from the surrounding tiles.
  1645. RBSet<TerrainConstraint> output;
  1646. output.insert(TerrainConstraint(tile_set, p_position, p_terrains_pattern.get_terrain()));
  1647. for (uint32_t i = 0; i < TileSet::CELL_NEIGHBOR_MAX; i++) {
  1648. TileSet::CellNeighbor side = TileSet::CellNeighbor(i);
  1649. if (tile_set->is_valid_terrain_peering_bit(p_terrain_set, side)) {
  1650. TerrainConstraint c = TerrainConstraint(tile_set, p_position, side, p_terrains_pattern.get_terrain_peering_bit(side));
  1651. output.insert(c);
  1652. }
  1653. }
  1654. return output;
  1655. }
  1656. RBSet<TerrainConstraint> TileMapLayer::_get_terrain_constraints_from_painted_cells_list(const RBSet<Vector2i> &p_painted, int p_terrain_set, bool p_ignore_empty_terrains) const {
  1657. if (tile_set.is_null()) {
  1658. return RBSet<TerrainConstraint>();
  1659. }
  1660. ERR_FAIL_INDEX_V(p_terrain_set, tile_set->get_terrain_sets_count(), RBSet<TerrainConstraint>());
  1661. // Build a set of dummy constraints to get the constrained points.
  1662. RBSet<TerrainConstraint> dummy_constraints;
  1663. for (const Vector2i &E : p_painted) {
  1664. for (int i = 0; i < TileSet::CELL_NEIGHBOR_MAX; i++) { // Iterates over neighbor bits.
  1665. TileSet::CellNeighbor bit = TileSet::CellNeighbor(i);
  1666. if (tile_set->is_valid_terrain_peering_bit(p_terrain_set, bit)) {
  1667. dummy_constraints.insert(TerrainConstraint(tile_set, E, bit, -1));
  1668. }
  1669. }
  1670. }
  1671. // For each constrained point, we get all overlapping tiles, and select the most adequate terrain for it.
  1672. RBSet<TerrainConstraint> constraints;
  1673. for (const TerrainConstraint &E_constraint : dummy_constraints) {
  1674. HashMap<int, int> terrain_count;
  1675. // Count the number of occurrences per terrain.
  1676. HashMap<Vector2i, TileSet::CellNeighbor> overlapping_terrain_bits = E_constraint.get_overlapping_coords_and_peering_bits();
  1677. for (const KeyValue<Vector2i, TileSet::CellNeighbor> &E_overlapping : overlapping_terrain_bits) {
  1678. TileData *neighbor_tile_data = nullptr;
  1679. TileMapCell neighbor_cell = get_cell(E_overlapping.key);
  1680. if (neighbor_cell.source_id != TileSet::INVALID_SOURCE) {
  1681. Ref<TileSetSource> source = tile_set->get_source(neighbor_cell.source_id);
  1682. Ref<TileSetAtlasSource> atlas_source = source;
  1683. if (atlas_source.is_valid()) {
  1684. TileData *tile_data = atlas_source->get_tile_data(neighbor_cell.get_atlas_coords(), neighbor_cell.alternative_tile);
  1685. if (tile_data && tile_data->get_terrain_set() == p_terrain_set) {
  1686. neighbor_tile_data = tile_data;
  1687. }
  1688. }
  1689. }
  1690. int terrain = neighbor_tile_data ? neighbor_tile_data->get_terrain_peering_bit(TileSet::CellNeighbor(E_overlapping.value)) : -1;
  1691. if (!p_ignore_empty_terrains || terrain >= 0) {
  1692. if (!terrain_count.has(terrain)) {
  1693. terrain_count[terrain] = 0;
  1694. }
  1695. terrain_count[terrain] += 1;
  1696. }
  1697. }
  1698. // Get the terrain with the max number of occurrences.
  1699. int max = 0;
  1700. int max_terrain = -1;
  1701. for (const KeyValue<int, int> &E_terrain_count : terrain_count) {
  1702. if (E_terrain_count.value > max) {
  1703. max = E_terrain_count.value;
  1704. max_terrain = E_terrain_count.key;
  1705. }
  1706. }
  1707. // Set the adequate terrain.
  1708. if (max > 0) {
  1709. TerrainConstraint c = E_constraint;
  1710. c.set_terrain(max_terrain);
  1711. constraints.insert(c);
  1712. }
  1713. }
  1714. // Add the centers as constraints.
  1715. for (Vector2i E_coords : p_painted) {
  1716. TileData *tile_data = nullptr;
  1717. TileMapCell cell = get_cell(E_coords);
  1718. if (cell.source_id != TileSet::INVALID_SOURCE) {
  1719. Ref<TileSetSource> source = tile_set->get_source(cell.source_id);
  1720. Ref<TileSetAtlasSource> atlas_source = source;
  1721. if (atlas_source.is_valid()) {
  1722. tile_data = atlas_source->get_tile_data(cell.get_atlas_coords(), cell.alternative_tile);
  1723. }
  1724. }
  1725. int terrain = (tile_data && tile_data->get_terrain_set() == p_terrain_set) ? tile_data->get_terrain() : -1;
  1726. if (!p_ignore_empty_terrains || terrain >= 0) {
  1727. constraints.insert(TerrainConstraint(tile_set, E_coords, terrain));
  1728. }
  1729. }
  1730. return constraints;
  1731. }
  1732. void TileMapLayer::_tile_set_changed() {
  1733. dirty.flags[DIRTY_FLAGS_TILE_SET] = true;
  1734. _queue_internal_update();
  1735. emit_signal(CoreStringName(changed));
  1736. }
  1737. void TileMapLayer::_renamed() {
  1738. emit_signal(CoreStringName(changed));
  1739. }
  1740. void TileMapLayer::_update_notify_local_transform() {
  1741. bool notify = is_using_kinematic_bodies() || is_y_sort_enabled();
  1742. if (!notify) {
  1743. if (is_y_sort_enabled()) {
  1744. notify = true;
  1745. }
  1746. }
  1747. set_notify_local_transform(notify);
  1748. }
  1749. void TileMapLayer::_queue_internal_update() {
  1750. if (pending_update) {
  1751. return;
  1752. }
  1753. // Don't update when outside the tree, it doesn't do anything useful, and causes threading problems.
  1754. if (is_inside_tree()) {
  1755. pending_update = true;
  1756. callable_mp(this, &TileMapLayer::_deferred_internal_update).call_deferred();
  1757. }
  1758. }
  1759. void TileMapLayer::_deferred_internal_update() {
  1760. // Other updates.
  1761. if (!pending_update) {
  1762. return;
  1763. }
  1764. // Update dirty quadrants on layers.
  1765. _internal_update(false);
  1766. }
  1767. void TileMapLayer::_internal_update(bool p_force_cleanup) {
  1768. // Find TileData that need a runtime modification.
  1769. // This may add cells to the dirty list if a runtime modification has been notified.
  1770. _build_runtime_update_tile_data(p_force_cleanup);
  1771. // Callback for implementing custom subsystems.
  1772. // This may add to the dirty list if some cells are changed inside _update_cells.
  1773. _update_cells_callback(p_force_cleanup);
  1774. // Update all subsystems.
  1775. _rendering_update(p_force_cleanup);
  1776. #ifndef PHYSICS_2D_DISABLED
  1777. _physics_update(p_force_cleanup);
  1778. #endif // PHYSICS_2D_DISABLED
  1779. #ifndef NAVIGATION_2D_DISABLED
  1780. _navigation_update(p_force_cleanup);
  1781. #endif // NAVIGATION_2D_DISABLED
  1782. _scenes_update(p_force_cleanup);
  1783. #ifdef DEBUG_ENABLED
  1784. _debug_update(p_force_cleanup);
  1785. #endif // DEBUG_ENABLED
  1786. _clear_runtime_update_tile_data();
  1787. // Clear the "what is dirty" flags.
  1788. for (int i = 0; i < DIRTY_FLAGS_MAX; i++) {
  1789. dirty.flags[i] = false;
  1790. }
  1791. // List the cells to delete definitely.
  1792. Vector<Vector2i> to_delete;
  1793. for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  1794. CellData &cell_data = *cell_data_list_element->self();
  1795. // Select the cell from tile_map if it is invalid.
  1796. if (cell_data.cell.source_id == TileSet::INVALID_SOURCE) {
  1797. to_delete.push_back(cell_data.coords);
  1798. }
  1799. }
  1800. // Remove cells that are empty after the cleanup.
  1801. for (const Vector2i &coords : to_delete) {
  1802. tile_map_layer_data.erase(coords);
  1803. }
  1804. // Clear the dirty cells list.
  1805. dirty.cell_list.clear();
  1806. pending_update = false;
  1807. }
  1808. void TileMapLayer::_physics_interpolated_changed() {
  1809. RenderingServer *rs = RenderingServer::get_singleton();
  1810. bool interpolated = is_physics_interpolated();
  1811. bool needs_reset = interpolated && is_visible_in_tree();
  1812. for (const KeyValue<Vector2i, Ref<RenderingQuadrant>> &kv : rendering_quadrant_map) {
  1813. for (const RID &ci : kv.value->canvas_items) {
  1814. if (ci.is_valid()) {
  1815. rs->canvas_item_set_interpolated(ci, interpolated);
  1816. if (needs_reset) {
  1817. rs->canvas_item_reset_physics_interpolation(ci);
  1818. }
  1819. }
  1820. }
  1821. }
  1822. for (const KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
  1823. for (const LocalVector<RID> &polygons : E.value.occluders) {
  1824. for (const RID &occluder_id : polygons) {
  1825. if (occluder_id.is_valid()) {
  1826. rs->canvas_light_occluder_set_interpolated(occluder_id, interpolated);
  1827. if (needs_reset) {
  1828. rs->canvas_light_occluder_reset_physics_interpolation(occluder_id);
  1829. }
  1830. }
  1831. }
  1832. }
  1833. }
  1834. }
  1835. void TileMapLayer::_notification(int p_what) {
  1836. switch (p_what) {
  1837. case NOTIFICATION_POSTINITIALIZE: {
  1838. connect(SNAME("renamed"), callable_mp(this, &TileMapLayer::_renamed));
  1839. break;
  1840. }
  1841. case NOTIFICATION_ENTER_TREE: {
  1842. _update_notify_local_transform();
  1843. dirty.flags[DIRTY_FLAGS_LAYER_IN_TREE] = true;
  1844. _queue_internal_update();
  1845. } break;
  1846. case NOTIFICATION_EXIT_TREE: {
  1847. dirty.flags[DIRTY_FLAGS_LAYER_IN_TREE] = true;
  1848. // Update immediately on exiting, and force cleanup.
  1849. _internal_update(true);
  1850. } break;
  1851. case NOTIFICATION_ENTER_CANVAS: {
  1852. dirty.flags[DIRTY_FLAGS_LAYER_IN_CANVAS] = true;
  1853. _queue_internal_update();
  1854. } break;
  1855. case NOTIFICATION_EXIT_CANVAS: {
  1856. dirty.flags[DIRTY_FLAGS_LAYER_IN_CANVAS] = true;
  1857. // Update immediately on exiting, and force cleanup.
  1858. _internal_update(true);
  1859. } break;
  1860. case NOTIFICATION_VISIBILITY_CHANGED: {
  1861. dirty.flags[DIRTY_FLAGS_LAYER_VISIBILITY] = true;
  1862. _queue_internal_update();
  1863. } break;
  1864. }
  1865. _rendering_notification(p_what);
  1866. #ifndef PHYSICS_2D_DISABLED
  1867. _physics_notification(p_what);
  1868. #endif // PHYSICS_2D_DISABLED
  1869. #ifndef NAVIGATION_2D_DISABLED
  1870. _navigation_notification(p_what);
  1871. #endif // NAVIGATION_2D_DISABLED
  1872. }
  1873. void TileMapLayer::_bind_methods() {
  1874. // --- Cells manipulation ---
  1875. // Generic cells manipulations and access.
  1876. ClassDB::bind_method(D_METHOD("set_cell", "coords", "source_id", "atlas_coords", "alternative_tile"), &TileMapLayer::set_cell, DEFVAL(TileSet::INVALID_SOURCE), DEFVAL(TileSetSource::INVALID_ATLAS_COORDS), DEFVAL(0));
  1877. ClassDB::bind_method(D_METHOD("erase_cell", "coords"), &TileMapLayer::erase_cell);
  1878. ClassDB::bind_method(D_METHOD("fix_invalid_tiles"), &TileMapLayer::fix_invalid_tiles);
  1879. ClassDB::bind_method(D_METHOD("clear"), &TileMapLayer::clear);
  1880. ClassDB::bind_method(D_METHOD("get_cell_source_id", "coords"), &TileMapLayer::get_cell_source_id);
  1881. ClassDB::bind_method(D_METHOD("get_cell_atlas_coords", "coords"), &TileMapLayer::get_cell_atlas_coords);
  1882. ClassDB::bind_method(D_METHOD("get_cell_alternative_tile", "coords"), &TileMapLayer::get_cell_alternative_tile);
  1883. ClassDB::bind_method(D_METHOD("get_cell_tile_data", "coords"), &TileMapLayer::get_cell_tile_data);
  1884. ClassDB::bind_method(D_METHOD("is_cell_flipped_h", "coords"), &TileMapLayer::is_cell_flipped_h);
  1885. ClassDB::bind_method(D_METHOD("is_cell_flipped_v", "coords"), &TileMapLayer::is_cell_flipped_v);
  1886. ClassDB::bind_method(D_METHOD("is_cell_transposed", "coords"), &TileMapLayer::is_cell_transposed);
  1887. ClassDB::bind_method(D_METHOD("get_used_cells"), &TileMapLayer::get_used_cells);
  1888. ClassDB::bind_method(D_METHOD("get_used_cells_by_id", "source_id", "atlas_coords", "alternative_tile"), &TileMapLayer::get_used_cells_by_id, DEFVAL(TileSet::INVALID_SOURCE), DEFVAL(TileSetSource::INVALID_ATLAS_COORDS), DEFVAL(TileSetSource::INVALID_TILE_ALTERNATIVE));
  1889. ClassDB::bind_method(D_METHOD("get_used_rect"), &TileMapLayer::get_used_rect);
  1890. // Patterns.
  1891. ClassDB::bind_method(D_METHOD("get_pattern", "coords_array"), &TileMapLayer::get_pattern);
  1892. ClassDB::bind_method(D_METHOD("set_pattern", "position", "pattern"), &TileMapLayer::set_pattern);
  1893. // Terrains.
  1894. ClassDB::bind_method(D_METHOD("set_cells_terrain_connect", "cells", "terrain_set", "terrain", "ignore_empty_terrains"), &TileMapLayer::set_cells_terrain_connect, DEFVAL(true));
  1895. ClassDB::bind_method(D_METHOD("set_cells_terrain_path", "path", "terrain_set", "terrain", "ignore_empty_terrains"), &TileMapLayer::set_cells_terrain_path, DEFVAL(true));
  1896. #ifndef PHYSICS_2D_DISABLED
  1897. // --- Physics helpers ---
  1898. ClassDB::bind_method(D_METHOD("has_body_rid", "body"), &TileMapLayer::has_body_rid);
  1899. ClassDB::bind_method(D_METHOD("get_coords_for_body_rid", "body"), &TileMapLayer::get_coords_for_body_rid);
  1900. #endif // PHYSICS_2D_DISABLED
  1901. // --- Runtime ---
  1902. ClassDB::bind_method(D_METHOD("update_internals"), &TileMapLayer::update_internals);
  1903. ClassDB::bind_method(D_METHOD("notify_runtime_tile_data_update"), &TileMapLayer::notify_runtime_tile_data_update);
  1904. // --- Shortcuts to methods defined in TileSet ---
  1905. ClassDB::bind_method(D_METHOD("map_pattern", "position_in_tilemap", "coords_in_pattern", "pattern"), &TileMapLayer::map_pattern);
  1906. ClassDB::bind_method(D_METHOD("get_surrounding_cells", "coords"), &TileMapLayer::get_surrounding_cells);
  1907. ClassDB::bind_method(D_METHOD("get_neighbor_cell", "coords", "neighbor"), &TileMapLayer::get_neighbor_cell);
  1908. ClassDB::bind_method(D_METHOD("map_to_local", "map_position"), &TileMapLayer::map_to_local);
  1909. ClassDB::bind_method(D_METHOD("local_to_map", "local_position"), &TileMapLayer::local_to_map);
  1910. // --- Accessors ---
  1911. ClassDB::bind_method(D_METHOD("set_tile_map_data_from_array", "tile_map_layer_data"), &TileMapLayer::set_tile_map_data_from_array);
  1912. ClassDB::bind_method(D_METHOD("get_tile_map_data_as_array"), &TileMapLayer::get_tile_map_data_as_array);
  1913. ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &TileMapLayer::set_enabled);
  1914. ClassDB::bind_method(D_METHOD("is_enabled"), &TileMapLayer::is_enabled);
  1915. ClassDB::bind_method(D_METHOD("set_tile_set", "tile_set"), &TileMapLayer::set_tile_set);
  1916. ClassDB::bind_method(D_METHOD("get_tile_set"), &TileMapLayer::get_tile_set);
  1917. ClassDB::bind_method(D_METHOD("set_y_sort_origin", "y_sort_origin"), &TileMapLayer::set_y_sort_origin);
  1918. ClassDB::bind_method(D_METHOD("get_y_sort_origin"), &TileMapLayer::get_y_sort_origin);
  1919. ClassDB::bind_method(D_METHOD("set_x_draw_order_reversed", "x_draw_order_reversed"), &TileMapLayer::set_x_draw_order_reversed);
  1920. ClassDB::bind_method(D_METHOD("is_x_draw_order_reversed"), &TileMapLayer::is_x_draw_order_reversed);
  1921. ClassDB::bind_method(D_METHOD("set_rendering_quadrant_size", "size"), &TileMapLayer::set_rendering_quadrant_size);
  1922. ClassDB::bind_method(D_METHOD("get_rendering_quadrant_size"), &TileMapLayer::get_rendering_quadrant_size);
  1923. ClassDB::bind_method(D_METHOD("set_collision_enabled", "enabled"), &TileMapLayer::set_collision_enabled);
  1924. ClassDB::bind_method(D_METHOD("is_collision_enabled"), &TileMapLayer::is_collision_enabled);
  1925. ClassDB::bind_method(D_METHOD("set_use_kinematic_bodies", "use_kinematic_bodies"), &TileMapLayer::set_use_kinematic_bodies);
  1926. ClassDB::bind_method(D_METHOD("is_using_kinematic_bodies"), &TileMapLayer::is_using_kinematic_bodies);
  1927. ClassDB::bind_method(D_METHOD("set_collision_visibility_mode", "visibility_mode"), &TileMapLayer::set_collision_visibility_mode);
  1928. ClassDB::bind_method(D_METHOD("get_collision_visibility_mode"), &TileMapLayer::get_collision_visibility_mode);
  1929. ClassDB::bind_method(D_METHOD("set_physics_quadrant_size", "size"), &TileMapLayer::set_physics_quadrant_size);
  1930. ClassDB::bind_method(D_METHOD("get_physics_quadrant_size"), &TileMapLayer::get_physics_quadrant_size);
  1931. ClassDB::bind_method(D_METHOD("set_occlusion_enabled", "enabled"), &TileMapLayer::set_occlusion_enabled);
  1932. ClassDB::bind_method(D_METHOD("is_occlusion_enabled"), &TileMapLayer::is_occlusion_enabled);
  1933. #ifndef NAVIGATION_2D_DISABLED
  1934. ClassDB::bind_method(D_METHOD("set_navigation_enabled", "enabled"), &TileMapLayer::set_navigation_enabled);
  1935. ClassDB::bind_method(D_METHOD("is_navigation_enabled"), &TileMapLayer::is_navigation_enabled);
  1936. ClassDB::bind_method(D_METHOD("set_navigation_map", "map"), &TileMapLayer::set_navigation_map);
  1937. ClassDB::bind_method(D_METHOD("get_navigation_map"), &TileMapLayer::get_navigation_map);
  1938. ClassDB::bind_method(D_METHOD("set_navigation_visibility_mode", "show_navigation"), &TileMapLayer::set_navigation_visibility_mode);
  1939. ClassDB::bind_method(D_METHOD("get_navigation_visibility_mode"), &TileMapLayer::get_navigation_visibility_mode);
  1940. #endif // NAVIGATION_2D_DISABLED
  1941. GDVIRTUAL_BIND(_use_tile_data_runtime_update, "coords");
  1942. GDVIRTUAL_BIND(_tile_data_runtime_update, "coords", "tile_data");
  1943. GDVIRTUAL_BIND(_update_cells, "coords", "forced_cleanup");
  1944. ADD_PROPERTY(PropertyInfo(Variant::PACKED_BYTE_ARRAY, "tile_map_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_tile_map_data_from_array", "get_tile_map_data_as_array");
  1945. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled");
  1946. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "tile_set", PROPERTY_HINT_RESOURCE_TYPE, "TileSet"), "set_tile_set", "get_tile_set");
  1947. ADD_GROUP("Rendering", "");
  1948. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "occlusion_enabled"), "set_occlusion_enabled", "is_occlusion_enabled");
  1949. ADD_PROPERTY(PropertyInfo(Variant::INT, "y_sort_origin"), "set_y_sort_origin", "get_y_sort_origin");
  1950. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "x_draw_order_reversed"), "set_x_draw_order_reversed", "is_x_draw_order_reversed");
  1951. ADD_PROPERTY(PropertyInfo(Variant::INT, "rendering_quadrant_size"), "set_rendering_quadrant_size", "get_rendering_quadrant_size");
  1952. ADD_GROUP("Physics", "");
  1953. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collision_enabled"), "set_collision_enabled", "is_collision_enabled");
  1954. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_kinematic_bodies"), "set_use_kinematic_bodies", "is_using_kinematic_bodies");
  1955. ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_visibility_mode", PROPERTY_HINT_ENUM, "Default,Force Show,Force Hide"), "set_collision_visibility_mode", "get_collision_visibility_mode");
  1956. ADD_PROPERTY(PropertyInfo(Variant::INT, "physics_quadrant_size"), "set_physics_quadrant_size", "get_physics_quadrant_size");
  1957. #ifndef NAVIGATION_2D_DISABLED
  1958. ADD_GROUP("Navigation", "navigation_");
  1959. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "navigation_enabled", PROPERTY_HINT_GROUP_ENABLE), "set_navigation_enabled", "is_navigation_enabled");
  1960. ADD_PROPERTY(PropertyInfo(Variant::INT, "navigation_visibility_mode", PROPERTY_HINT_ENUM, "Default,Force Show,Force Hide"), "set_navigation_visibility_mode", "get_navigation_visibility_mode");
  1961. #endif // NAVIGATION_2D_DISABLED
  1962. ADD_SIGNAL(MethodInfo(CoreStringName(changed)));
  1963. ADD_PROPERTY_DEFAULT("tile_map_data_format", TileMapDataFormat::TILE_MAP_DATA_FORMAT_1);
  1964. BIND_ENUM_CONSTANT(DEBUG_VISIBILITY_MODE_DEFAULT);
  1965. BIND_ENUM_CONSTANT(DEBUG_VISIBILITY_MODE_FORCE_HIDE);
  1966. BIND_ENUM_CONSTANT(DEBUG_VISIBILITY_MODE_FORCE_SHOW);
  1967. }
  1968. void TileMapLayer::_validate_property(PropertyInfo &p_property) const {
  1969. if (!Engine::get_singleton()->is_editor_hint()) {
  1970. return;
  1971. }
  1972. if (is_y_sort_enabled()) {
  1973. if (p_property.name == "rendering_quadrant_size") {
  1974. p_property.usage |= PROPERTY_USAGE_READ_ONLY;
  1975. }
  1976. } else {
  1977. if (p_property.name == "x_draw_order_reversed") {
  1978. p_property.usage |= PROPERTY_USAGE_READ_ONLY;
  1979. }
  1980. }
  1981. }
  1982. void TileMapLayer::_update_self_texture_filter(RS::CanvasItemTextureFilter p_texture_filter) {
  1983. // Set a default texture filter for the whole tilemap.
  1984. CanvasItem::_update_self_texture_filter(p_texture_filter);
  1985. dirty.flags[DIRTY_FLAGS_LAYER_TEXTURE_FILTER] = true;
  1986. _queue_internal_update();
  1987. emit_signal(CoreStringName(changed));
  1988. }
  1989. void TileMapLayer::_update_self_texture_repeat(RS::CanvasItemTextureRepeat p_texture_repeat) {
  1990. // Set a default texture repeat for the whole tilemap.
  1991. CanvasItem::_update_self_texture_repeat(p_texture_repeat);
  1992. dirty.flags[DIRTY_FLAGS_LAYER_TEXTURE_REPEAT] = true;
  1993. _queue_internal_update();
  1994. emit_signal(CoreStringName(changed));
  1995. }
  1996. #ifdef TOOLS_ENABLED
  1997. bool TileMapLayer::_edit_is_selected_on_click(const Point2 &p_point, double p_tolerance) const {
  1998. return tile_set.is_valid() && get_cell_source_id(local_to_map(p_point)) != TileSet::INVALID_SOURCE;
  1999. }
  2000. #endif
  2001. void TileMapLayer::set_as_tile_map_internal_node(int p_index) {
  2002. // Compatibility with TileMap.
  2003. ERR_FAIL_NULL(get_parent());
  2004. tile_map_node = Object::cast_to<TileMap>(get_parent());
  2005. set_use_parent_material(true);
  2006. if (layer_index_in_tile_map_node != p_index) {
  2007. layer_index_in_tile_map_node = p_index;
  2008. dirty.flags[DIRTY_FLAGS_LAYER_INDEX_IN_TILE_MAP_NODE] = true;
  2009. _queue_internal_update();
  2010. }
  2011. }
  2012. Rect2 TileMapLayer::get_rect(bool &r_changed) const {
  2013. if (tile_set.is_null()) {
  2014. r_changed = rect_cache != Rect2();
  2015. return Rect2();
  2016. }
  2017. // Compute the displayed area of the tilemap.
  2018. r_changed = false;
  2019. #ifdef DEBUG_ENABLED
  2020. if (rect_cache_dirty) {
  2021. Rect2 r_total;
  2022. bool first = true;
  2023. for (const KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
  2024. Rect2 r;
  2025. r.position = tile_set->map_to_local(E.key);
  2026. r.size = Size2();
  2027. if (first) {
  2028. r_total = r;
  2029. first = false;
  2030. } else {
  2031. r_total = r_total.merge(r);
  2032. }
  2033. }
  2034. r_changed = rect_cache != r_total;
  2035. rect_cache = r_total;
  2036. rect_cache_dirty = false;
  2037. }
  2038. #endif
  2039. return rect_cache;
  2040. }
  2041. HashMap<Vector2i, TileSet::TerrainsPattern> TileMapLayer::terrain_fill_constraints(const Vector<Vector2i> &p_to_replace, int p_terrain_set, const RBSet<TerrainConstraint> &p_constraints) const {
  2042. if (tile_set.is_null()) {
  2043. return HashMap<Vector2i, TileSet::TerrainsPattern>();
  2044. }
  2045. // Copy the constraints set.
  2046. RBSet<TerrainConstraint> constraints = p_constraints;
  2047. // Output map.
  2048. HashMap<Vector2i, TileSet::TerrainsPattern> output;
  2049. // Add all positions to a set.
  2050. for (int i = 0; i < p_to_replace.size(); i++) {
  2051. const Vector2i &coords = p_to_replace[i];
  2052. // Select the best pattern for the given constraints.
  2053. TileSet::TerrainsPattern current_pattern = TileSet::TerrainsPattern(*tile_set, p_terrain_set);
  2054. TileMapCell cell = get_cell(coords);
  2055. if (cell.source_id != TileSet::INVALID_SOURCE) {
  2056. TileSetSource *source = *tile_set->get_source(cell.source_id);
  2057. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
  2058. if (atlas_source) {
  2059. // Get tile data.
  2060. TileData *tile_data = atlas_source->get_tile_data(cell.get_atlas_coords(), cell.alternative_tile);
  2061. if (tile_data && tile_data->get_terrain_set() == p_terrain_set) {
  2062. current_pattern = tile_data->get_terrains_pattern();
  2063. }
  2064. }
  2065. }
  2066. TileSet::TerrainsPattern pattern = _get_best_terrain_pattern_for_constraints(p_terrain_set, coords, constraints, current_pattern);
  2067. // Update the constraint set with the new ones.
  2068. RBSet<TerrainConstraint> new_constraints = _get_terrain_constraints_from_added_pattern(coords, p_terrain_set, pattern);
  2069. for (const TerrainConstraint &E_constraint : new_constraints) {
  2070. if (constraints.has(E_constraint)) {
  2071. constraints.erase(E_constraint);
  2072. }
  2073. TerrainConstraint c = E_constraint;
  2074. c.set_priority(5);
  2075. constraints.insert(c);
  2076. }
  2077. output[coords] = pattern;
  2078. }
  2079. return output;
  2080. }
  2081. HashMap<Vector2i, TileSet::TerrainsPattern> TileMapLayer::terrain_fill_connect(const Vector<Vector2i> &p_coords_array, int p_terrain_set, int p_terrain, bool p_ignore_empty_terrains) const {
  2082. ERR_FAIL_COND_V(tile_set.is_null(), (HashMap<Vector2i, TileSet::TerrainsPattern>()));
  2083. ERR_FAIL_INDEX_V(p_terrain_set, tile_set->get_terrain_sets_count(), (HashMap<Vector2i, TileSet::TerrainsPattern>()));
  2084. HashMap<Vector2i, TileSet::TerrainsPattern> output;
  2085. // Build list and set of tiles that can be modified (painted and their surroundings).
  2086. Vector<Vector2i> can_modify_list;
  2087. RBSet<Vector2i> can_modify_set;
  2088. RBSet<Vector2i> painted_set;
  2089. for (int i = p_coords_array.size() - 1; i >= 0; i--) {
  2090. const Vector2i &coords = p_coords_array[i];
  2091. can_modify_list.push_back(coords);
  2092. can_modify_set.insert(coords);
  2093. painted_set.insert(coords);
  2094. }
  2095. for (Vector2i coords : p_coords_array) {
  2096. // Find the adequate neighbor.
  2097. for (int j = 0; j < TileSet::CELL_NEIGHBOR_MAX; j++) {
  2098. TileSet::CellNeighbor bit = TileSet::CellNeighbor(j);
  2099. if (tile_set->is_existing_neighbor(bit)) {
  2100. Vector2i neighbor = tile_set->get_neighbor_cell(coords, bit);
  2101. if (!can_modify_set.has(neighbor)) {
  2102. can_modify_list.push_back(neighbor);
  2103. can_modify_set.insert(neighbor);
  2104. }
  2105. }
  2106. }
  2107. }
  2108. // Build a set, out of the possibly modified tiles, of the one with a center bit that is set (or will be) to the painted terrain.
  2109. RBSet<Vector2i> cells_with_terrain_center_bit;
  2110. for (Vector2i coords : can_modify_set) {
  2111. bool connect = false;
  2112. if (painted_set.has(coords)) {
  2113. connect = true;
  2114. } else {
  2115. // Get the center bit of the cell.
  2116. TileData *tile_data = nullptr;
  2117. TileMapCell cell = get_cell(coords);
  2118. if (cell.source_id != TileSet::INVALID_SOURCE) {
  2119. Ref<TileSetSource> source = tile_set->get_source(cell.source_id);
  2120. Ref<TileSetAtlasSource> atlas_source = source;
  2121. if (atlas_source.is_valid()) {
  2122. tile_data = atlas_source->get_tile_data(cell.get_atlas_coords(), cell.alternative_tile);
  2123. }
  2124. }
  2125. if (tile_data && tile_data->get_terrain_set() == p_terrain_set && tile_data->get_terrain() == p_terrain) {
  2126. connect = true;
  2127. }
  2128. }
  2129. if (connect) {
  2130. cells_with_terrain_center_bit.insert(coords);
  2131. }
  2132. }
  2133. RBSet<TerrainConstraint> constraints;
  2134. // Add new constraints from the path drawn.
  2135. for (Vector2i coords : p_coords_array) {
  2136. // Constraints on the center bit.
  2137. TerrainConstraint c = TerrainConstraint(tile_set, coords, p_terrain);
  2138. c.set_priority(10);
  2139. constraints.insert(c);
  2140. // Constraints on the connecting bits.
  2141. for (int j = 0; j < TileSet::CELL_NEIGHBOR_MAX; j++) {
  2142. TileSet::CellNeighbor bit = TileSet::CellNeighbor(j);
  2143. if (tile_set->is_valid_terrain_peering_bit(p_terrain_set, bit)) {
  2144. c = TerrainConstraint(tile_set, coords, bit, p_terrain);
  2145. c.set_priority(10);
  2146. if ((int(bit) % 2) == 0) {
  2147. // Side peering bits: add the constraint if the center is of the same terrain.
  2148. Vector2i neighbor = tile_set->get_neighbor_cell(coords, bit);
  2149. if (cells_with_terrain_center_bit.has(neighbor)) {
  2150. constraints.insert(c);
  2151. }
  2152. } else {
  2153. // Corner peering bits: add the constraint if all tiles on the constraint has the same center bit.
  2154. HashMap<Vector2i, TileSet::CellNeighbor> overlapping_terrain_bits = c.get_overlapping_coords_and_peering_bits();
  2155. bool valid = true;
  2156. for (KeyValue<Vector2i, TileSet::CellNeighbor> kv : overlapping_terrain_bits) {
  2157. if (!cells_with_terrain_center_bit.has(kv.key)) {
  2158. valid = false;
  2159. break;
  2160. }
  2161. }
  2162. if (valid) {
  2163. constraints.insert(c);
  2164. }
  2165. }
  2166. }
  2167. }
  2168. }
  2169. // Fills in the constraint list from existing tiles.
  2170. for (TerrainConstraint c : _get_terrain_constraints_from_painted_cells_list(painted_set, p_terrain_set, p_ignore_empty_terrains)) {
  2171. constraints.insert(c);
  2172. }
  2173. // Fill the terrains.
  2174. return terrain_fill_constraints(can_modify_list, p_terrain_set, constraints);
  2175. }
  2176. HashMap<Vector2i, TileSet::TerrainsPattern> TileMapLayer::terrain_fill_path(const Vector<Vector2i> &p_coords_array, int p_terrain_set, int p_terrain, bool p_ignore_empty_terrains) const {
  2177. ERR_FAIL_COND_V(tile_set.is_null(), (HashMap<Vector2i, TileSet::TerrainsPattern>()));
  2178. ERR_FAIL_INDEX_V(p_terrain_set, tile_set->get_terrain_sets_count(), (HashMap<Vector2i, TileSet::TerrainsPattern>()));
  2179. HashMap<Vector2i, TileSet::TerrainsPattern> output;
  2180. // Make sure the path is correct and build the peering bit list while doing it.
  2181. Vector<TileSet::CellNeighbor> neighbor_list;
  2182. for (int i = 0; i < p_coords_array.size() - 1; i++) {
  2183. // Find the adequate neighbor.
  2184. TileSet::CellNeighbor found_bit = TileSet::CELL_NEIGHBOR_MAX;
  2185. for (int j = 0; j < TileSet::CELL_NEIGHBOR_MAX; j++) {
  2186. TileSet::CellNeighbor bit = TileSet::CellNeighbor(j);
  2187. if (tile_set->is_existing_neighbor(bit)) {
  2188. if (tile_set->get_neighbor_cell(p_coords_array[i], bit) == p_coords_array[i + 1]) {
  2189. found_bit = bit;
  2190. break;
  2191. }
  2192. }
  2193. }
  2194. ERR_FAIL_COND_V_MSG(found_bit == TileSet::CELL_NEIGHBOR_MAX, output, vformat("Invalid terrain path, %s is not a neighboring tile of %s", p_coords_array[i + 1], p_coords_array[i]));
  2195. neighbor_list.push_back(found_bit);
  2196. }
  2197. // Build list and set of tiles that can be modified (painted and their surroundings).
  2198. Vector<Vector2i> can_modify_list;
  2199. RBSet<Vector2i> can_modify_set;
  2200. RBSet<Vector2i> painted_set;
  2201. for (int i = p_coords_array.size() - 1; i >= 0; i--) {
  2202. const Vector2i &coords = p_coords_array[i];
  2203. can_modify_list.push_back(coords);
  2204. can_modify_set.insert(coords);
  2205. painted_set.insert(coords);
  2206. }
  2207. for (Vector2i coords : p_coords_array) {
  2208. // Find the adequate neighbor.
  2209. for (int j = 0; j < TileSet::CELL_NEIGHBOR_MAX; j++) {
  2210. TileSet::CellNeighbor bit = TileSet::CellNeighbor(j);
  2211. if (tile_set->is_valid_terrain_peering_bit(p_terrain_set, bit)) {
  2212. Vector2i neighbor = tile_set->get_neighbor_cell(coords, bit);
  2213. if (!can_modify_set.has(neighbor)) {
  2214. can_modify_list.push_back(neighbor);
  2215. can_modify_set.insert(neighbor);
  2216. }
  2217. }
  2218. }
  2219. }
  2220. RBSet<TerrainConstraint> constraints;
  2221. // Add new constraints from the path drawn.
  2222. for (Vector2i coords : p_coords_array) {
  2223. // Constraints on the center bit.
  2224. TerrainConstraint c = TerrainConstraint(tile_set, coords, p_terrain);
  2225. c.set_priority(10);
  2226. constraints.insert(c);
  2227. }
  2228. for (int i = 0; i < p_coords_array.size() - 1; i++) {
  2229. // Constraints on the peering bits.
  2230. TerrainConstraint c = TerrainConstraint(tile_set, p_coords_array[i], neighbor_list[i], p_terrain);
  2231. c.set_priority(10);
  2232. constraints.insert(c);
  2233. }
  2234. // Fills in the constraint list from existing tiles.
  2235. for (TerrainConstraint c : _get_terrain_constraints_from_painted_cells_list(painted_set, p_terrain_set, p_ignore_empty_terrains)) {
  2236. constraints.insert(c);
  2237. }
  2238. // Fill the terrains.
  2239. return terrain_fill_constraints(can_modify_list, p_terrain_set, constraints);
  2240. }
  2241. HashMap<Vector2i, TileSet::TerrainsPattern> TileMapLayer::terrain_fill_pattern(const Vector<Vector2i> &p_coords_array, int p_terrain_set, TileSet::TerrainsPattern p_terrains_pattern, bool p_ignore_empty_terrains) const {
  2242. ERR_FAIL_COND_V(tile_set.is_null(), (HashMap<Vector2i, TileSet::TerrainsPattern>()));
  2243. ERR_FAIL_INDEX_V(p_terrain_set, tile_set->get_terrain_sets_count(), (HashMap<Vector2i, TileSet::TerrainsPattern>()));
  2244. HashMap<Vector2i, TileSet::TerrainsPattern> output;
  2245. // Build list and set of tiles that can be modified (painted and their surroundings).
  2246. Vector<Vector2i> can_modify_list;
  2247. RBSet<Vector2i> can_modify_set;
  2248. RBSet<Vector2i> painted_set;
  2249. for (int i = p_coords_array.size() - 1; i >= 0; i--) {
  2250. const Vector2i &coords = p_coords_array[i];
  2251. can_modify_list.push_back(coords);
  2252. can_modify_set.insert(coords);
  2253. painted_set.insert(coords);
  2254. }
  2255. for (Vector2i coords : p_coords_array) {
  2256. // Find the adequate neighbor.
  2257. for (int j = 0; j < TileSet::CELL_NEIGHBOR_MAX; j++) {
  2258. TileSet::CellNeighbor bit = TileSet::CellNeighbor(j);
  2259. if (tile_set->is_existing_neighbor(bit)) {
  2260. Vector2i neighbor = tile_set->get_neighbor_cell(coords, bit);
  2261. if (!can_modify_set.has(neighbor)) {
  2262. can_modify_list.push_back(neighbor);
  2263. can_modify_set.insert(neighbor);
  2264. }
  2265. }
  2266. }
  2267. }
  2268. // Add constraint by the new ones.
  2269. RBSet<TerrainConstraint> constraints;
  2270. // Add new constraints from the path drawn.
  2271. for (Vector2i coords : p_coords_array) {
  2272. // Constraints on the center bit.
  2273. RBSet<TerrainConstraint> added_constraints = _get_terrain_constraints_from_added_pattern(coords, p_terrain_set, p_terrains_pattern);
  2274. for (TerrainConstraint c : added_constraints) {
  2275. c.set_priority(10);
  2276. constraints.insert(c);
  2277. }
  2278. }
  2279. // Fills in the constraint list from modified tiles border.
  2280. for (TerrainConstraint c : _get_terrain_constraints_from_painted_cells_list(painted_set, p_terrain_set, p_ignore_empty_terrains)) {
  2281. constraints.insert(c);
  2282. }
  2283. // Fill the terrains.
  2284. return terrain_fill_constraints(can_modify_list, p_terrain_set, constraints);
  2285. }
  2286. TileMapCell TileMapLayer::get_cell(const Vector2i &p_coords) const {
  2287. if (!tile_map_layer_data.has(p_coords)) {
  2288. return TileMapCell();
  2289. } else {
  2290. return tile_map_layer_data.find(p_coords)->value.cell;
  2291. }
  2292. }
  2293. void TileMapLayer::draw_tile(RID p_canvas_item, const Vector2 &p_position, const Ref<TileSet> p_tile_set, int p_atlas_source_id, const Vector2i &p_atlas_coords, int p_alternative_tile, int p_frame, const TileData *p_tile_data_override, real_t p_normalized_animation_offset) {
  2294. ERR_FAIL_COND(p_tile_set.is_null());
  2295. ERR_FAIL_COND(!p_tile_set->has_source(p_atlas_source_id));
  2296. ERR_FAIL_COND(!p_tile_set->get_source(p_atlas_source_id)->has_tile(p_atlas_coords));
  2297. ERR_FAIL_COND(!p_tile_set->get_source(p_atlas_source_id)->has_alternative_tile(p_atlas_coords, p_alternative_tile));
  2298. TileSetSource *source = *p_tile_set->get_source(p_atlas_source_id);
  2299. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
  2300. if (atlas_source) {
  2301. // Check for the frame.
  2302. if (p_frame >= 0) {
  2303. ERR_FAIL_INDEX(p_frame, atlas_source->get_tile_animation_frames_count(p_atlas_coords));
  2304. }
  2305. // Get the texture.
  2306. Ref<Texture2D> tex = atlas_source->get_runtime_texture();
  2307. if (tex.is_null()) {
  2308. return;
  2309. }
  2310. // Check if we are in the texture, return otherwise.
  2311. Vector2i grid_size = atlas_source->get_atlas_grid_size();
  2312. if (p_atlas_coords.x >= grid_size.x || p_atlas_coords.y >= grid_size.y) {
  2313. return;
  2314. }
  2315. // Get tile data.
  2316. const TileData *tile_data = p_tile_data_override ? p_tile_data_override : atlas_source->get_tile_data(p_atlas_coords, p_alternative_tile);
  2317. // Get the tile modulation.
  2318. Color modulate = tile_data->get_modulate();
  2319. // Compute the dest rect.
  2320. Rect2 dest_rect;
  2321. bool transpose;
  2322. compute_transformed_tile_dest_rect(dest_rect, transpose, p_position, atlas_source->get_runtime_tile_texture_region(p_atlas_coords).size, tile_data, p_alternative_tile);
  2323. // Draw the tile.
  2324. if (p_frame >= 0) {
  2325. Rect2i source_rect = atlas_source->get_runtime_tile_texture_region(p_atlas_coords, p_frame);
  2326. tex->draw_rect_region(p_canvas_item, dest_rect, source_rect, modulate, transpose, p_tile_set->is_uv_clipping());
  2327. } else if (atlas_source->get_tile_animation_frames_count(p_atlas_coords) == 1) {
  2328. Rect2i source_rect = atlas_source->get_runtime_tile_texture_region(p_atlas_coords, 0);
  2329. tex->draw_rect_region(p_canvas_item, dest_rect, source_rect, modulate, transpose, p_tile_set->is_uv_clipping());
  2330. } else {
  2331. real_t speed = atlas_source->get_tile_animation_speed(p_atlas_coords);
  2332. real_t animation_duration = atlas_source->get_tile_animation_total_duration(p_atlas_coords) / speed;
  2333. real_t animation_offset = p_normalized_animation_offset * animation_duration;
  2334. // Accumulate durations unaffected by the speed to avoid accumulating floating point division errors.
  2335. // Aka do `sum(duration[i]) / speed` instead of `sum(duration[i] / speed)`.
  2336. real_t time_unscaled = 0.0;
  2337. for (int frame = 0; frame < atlas_source->get_tile_animation_frames_count(p_atlas_coords); frame++) {
  2338. real_t frame_duration_unscaled = atlas_source->get_tile_animation_frame_duration(p_atlas_coords, frame);
  2339. real_t slice_start = time_unscaled / speed;
  2340. real_t slice_end = (time_unscaled + frame_duration_unscaled) / speed;
  2341. RenderingServer::get_singleton()->canvas_item_add_animation_slice(p_canvas_item, animation_duration, slice_start, slice_end, animation_offset);
  2342. Rect2i source_rect = atlas_source->get_runtime_tile_texture_region(p_atlas_coords, frame);
  2343. tex->draw_rect_region(p_canvas_item, dest_rect, source_rect, modulate, transpose, p_tile_set->is_uv_clipping());
  2344. time_unscaled += frame_duration_unscaled;
  2345. }
  2346. RenderingServer::get_singleton()->canvas_item_add_animation_slice(p_canvas_item, 1.0, 0.0, 1.0, 0.0);
  2347. }
  2348. }
  2349. }
  2350. void TileMapLayer::compute_transformed_tile_dest_rect(Rect2 &r_dest_rect, bool &r_transpose, const Vector2 &p_position, const Vector2 &p_dest_rect_size, const TileData *p_tile_data, int p_alternative_tile) {
  2351. DEV_ASSERT(p_tile_data);
  2352. // Conceptually the order of transformations is (starting from the tile centered at the origin):
  2353. // - Per TileSet-tile transforms (transpose then flips).
  2354. // - Translation so texture origin is at the origin.
  2355. // - Per TileMapLayer-cell transforms (transpose then flips).
  2356. // - Translation to target position.
  2357. const bool tile_transpose = p_tile_data->get_transpose();
  2358. const bool tile_flip_h = p_tile_data->get_flip_h();
  2359. const bool tile_flip_v = p_tile_data->get_flip_v();
  2360. const Vector2 texture_origin = p_tile_data->get_texture_origin();
  2361. const bool cell_transpose = bool(p_alternative_tile & TileSetAtlasSource::TRANSFORM_TRANSPOSE);
  2362. const bool cell_flip_h = bool(p_alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_H);
  2363. const bool cell_flip_v = bool(p_alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_V);
  2364. const bool final_transpose = tile_transpose != cell_transpose;
  2365. const bool final_flip_h = cell_flip_h != (cell_transpose ? tile_flip_v : tile_flip_h);
  2366. const bool final_flip_v = cell_flip_v != (cell_transpose ? tile_flip_h : tile_flip_v);
  2367. // Rect draw commands swap the size based on the passed transpose, so the size is left non-tranposed here.
  2368. // Position calculations need to use transposed size though.
  2369. Rect2 dest_rect;
  2370. dest_rect.size = p_dest_rect_size;
  2371. dest_rect.size.x += FP_ADJUST;
  2372. dest_rect.size.y += FP_ADJUST;
  2373. Vector2 transposed_size = final_transpose ? Vector2(dest_rect.size.y, dest_rect.size.x) : dest_rect.size;
  2374. if (final_flip_h) {
  2375. dest_rect.size.x = -dest_rect.size.x;
  2376. }
  2377. if (final_flip_v) {
  2378. dest_rect.size.y = -dest_rect.size.y;
  2379. }
  2380. dest_rect.position = -0.5f * transposed_size;
  2381. dest_rect.position -= cell_transpose ? Vector2(texture_origin.y, texture_origin.x) : texture_origin;
  2382. if (cell_flip_h) {
  2383. dest_rect.position.x = -(dest_rect.position.x + transposed_size.x);
  2384. }
  2385. if (cell_flip_v) {
  2386. dest_rect.position.y = -(dest_rect.position.y + transposed_size.y);
  2387. }
  2388. dest_rect.position += p_position;
  2389. r_dest_rect = dest_rect;
  2390. r_transpose = final_transpose;
  2391. }
  2392. void TileMapLayer::set_cell(const Vector2i &p_coords, int p_source_id, const Vector2i &p_atlas_coords, int p_alternative_tile) {
  2393. // Set the current cell tile (using integer position).
  2394. Vector2i pk(p_coords);
  2395. HashMap<Vector2i, CellData>::Iterator E = tile_map_layer_data.find(pk);
  2396. int source_id = p_source_id;
  2397. Vector2i atlas_coords = p_atlas_coords;
  2398. int alternative_tile = p_alternative_tile;
  2399. if ((source_id == TileSet::INVALID_SOURCE || atlas_coords == TileSetSource::INVALID_ATLAS_COORDS || alternative_tile == TileSetSource::INVALID_TILE_ALTERNATIVE) &&
  2400. (source_id != TileSet::INVALID_SOURCE || atlas_coords != TileSetSource::INVALID_ATLAS_COORDS || alternative_tile != TileSetSource::INVALID_TILE_ALTERNATIVE)) {
  2401. source_id = TileSet::INVALID_SOURCE;
  2402. atlas_coords = TileSetSource::INVALID_ATLAS_COORDS;
  2403. alternative_tile = TileSetSource::INVALID_TILE_ALTERNATIVE;
  2404. }
  2405. if (!E) {
  2406. if (source_id == TileSet::INVALID_SOURCE) {
  2407. return; // Nothing to do, the tile is already empty.
  2408. }
  2409. // Insert a new cell in the tile map.
  2410. CellData new_cell_data;
  2411. new_cell_data.coords = pk;
  2412. E = tile_map_layer_data.insert(pk, new_cell_data);
  2413. } else {
  2414. if (E->value.cell.source_id == source_id && E->value.cell.get_atlas_coords() == atlas_coords && E->value.cell.alternative_tile == alternative_tile) {
  2415. return; // Nothing changed.
  2416. }
  2417. }
  2418. TileMapCell &c = E->value.cell;
  2419. c.source_id = source_id;
  2420. c.set_atlas_coords(atlas_coords);
  2421. c.alternative_tile = alternative_tile;
  2422. // Make the given cell dirty.
  2423. if (!E->value.dirty_list_element.in_list()) {
  2424. dirty.cell_list.add(&(E->value.dirty_list_element));
  2425. }
  2426. _queue_internal_update();
  2427. used_rect_cache_dirty = true;
  2428. }
  2429. void TileMapLayer::erase_cell(const Vector2i &p_coords) {
  2430. set_cell(p_coords, TileSet::INVALID_SOURCE, TileSetSource::INVALID_ATLAS_COORDS, TileSetSource::INVALID_TILE_ALTERNATIVE);
  2431. }
  2432. void TileMapLayer::fix_invalid_tiles() {
  2433. ERR_FAIL_COND_MSG(tile_set.is_null(), "Cannot call fix_invalid_tiles() on a TileMapLayer without a valid TileSet.");
  2434. RBSet<Vector2i> coords;
  2435. for (const KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
  2436. TileSetSource *source = *tile_set->get_source(E.value.cell.source_id);
  2437. if (!source || !source->has_tile(E.value.cell.get_atlas_coords()) || !source->has_alternative_tile(E.value.cell.get_atlas_coords(), E.value.cell.alternative_tile)) {
  2438. coords.insert(E.key);
  2439. }
  2440. }
  2441. for (const Vector2i &E : coords) {
  2442. set_cell(E, TileSet::INVALID_SOURCE, TileSetSource::INVALID_ATLAS_COORDS, TileSetSource::INVALID_TILE_ALTERNATIVE);
  2443. }
  2444. }
  2445. void TileMapLayer::clear() {
  2446. // Remove all tiles.
  2447. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  2448. erase_cell(kv.key);
  2449. }
  2450. used_rect_cache_dirty = true;
  2451. }
  2452. int TileMapLayer::get_cell_source_id(const Vector2i &p_coords) const {
  2453. // Get a cell source id from position.
  2454. HashMap<Vector2i, CellData>::ConstIterator E = tile_map_layer_data.find(p_coords);
  2455. if (!E) {
  2456. return TileSet::INVALID_SOURCE;
  2457. }
  2458. return E->value.cell.source_id;
  2459. }
  2460. Vector2i TileMapLayer::get_cell_atlas_coords(const Vector2i &p_coords) const {
  2461. // Get a cell source id from position.
  2462. HashMap<Vector2i, CellData>::ConstIterator E = tile_map_layer_data.find(p_coords);
  2463. if (!E) {
  2464. return TileSetSource::INVALID_ATLAS_COORDS;
  2465. }
  2466. return E->value.cell.get_atlas_coords();
  2467. }
  2468. int TileMapLayer::get_cell_alternative_tile(const Vector2i &p_coords) const {
  2469. // Get a cell source id from position.
  2470. HashMap<Vector2i, CellData>::ConstIterator E = tile_map_layer_data.find(p_coords);
  2471. if (!E) {
  2472. return TileSetSource::INVALID_TILE_ALTERNATIVE;
  2473. }
  2474. return E->value.cell.alternative_tile;
  2475. }
  2476. TileData *TileMapLayer::get_cell_tile_data(const Vector2i &p_coords) const {
  2477. int source_id = get_cell_source_id(p_coords);
  2478. if (source_id == TileSet::INVALID_SOURCE) {
  2479. return nullptr;
  2480. }
  2481. Ref<TileSetAtlasSource> source = tile_set->get_source(source_id);
  2482. if (source.is_valid()) {
  2483. return source->get_tile_data(get_cell_atlas_coords(p_coords), get_cell_alternative_tile(p_coords));
  2484. }
  2485. return nullptr;
  2486. }
  2487. TypedArray<Vector2i> TileMapLayer::get_used_cells() const {
  2488. // Returns the cells used in the tilemap.
  2489. TypedArray<Vector2i> a;
  2490. for (const KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
  2491. const TileMapCell &c = E.value.cell;
  2492. if (c.source_id == TileSet::INVALID_SOURCE) {
  2493. continue;
  2494. }
  2495. a.push_back(E.key);
  2496. }
  2497. return a;
  2498. }
  2499. TypedArray<Vector2i> TileMapLayer::get_used_cells_by_id(int p_source_id, const Vector2i &p_atlas_coords, int p_alternative_tile) const {
  2500. // Returns the cells used in the tilemap.
  2501. TypedArray<Vector2i> a;
  2502. for (const KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
  2503. const TileMapCell &c = E.value.cell;
  2504. if (c.source_id == TileSet::INVALID_SOURCE) {
  2505. continue;
  2506. }
  2507. if ((p_source_id == TileSet::INVALID_SOURCE || p_source_id == c.source_id) &&
  2508. (p_atlas_coords == TileSetSource::INVALID_ATLAS_COORDS || p_atlas_coords == c.get_atlas_coords()) &&
  2509. (p_alternative_tile == TileSetSource::INVALID_TILE_ALTERNATIVE || p_alternative_tile == c.alternative_tile)) {
  2510. a.push_back(E.key);
  2511. }
  2512. }
  2513. return a;
  2514. }
  2515. Rect2i TileMapLayer::get_used_rect() const {
  2516. // Return the rect of the currently used area.
  2517. if (used_rect_cache_dirty) {
  2518. used_rect_cache = Rect2i();
  2519. bool first = true;
  2520. for (const KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
  2521. const TileMapCell &c = E.value.cell;
  2522. if (c.source_id == TileSet::INVALID_SOURCE) {
  2523. continue;
  2524. }
  2525. if (first) {
  2526. used_rect_cache = Rect2i(E.key, Size2i());
  2527. first = false;
  2528. } else {
  2529. used_rect_cache.expand_to(E.key);
  2530. }
  2531. }
  2532. if (!first) {
  2533. // Only if we have at least one cell.
  2534. // The cache expands to top-left coordinate, so we add one full tile.
  2535. used_rect_cache.size += Vector2i(1, 1);
  2536. }
  2537. used_rect_cache_dirty = false;
  2538. }
  2539. return used_rect_cache;
  2540. }
  2541. bool TileMapLayer::is_cell_flipped_h(const Vector2i &p_coords) const {
  2542. return get_cell_alternative_tile(p_coords) & TileSetAtlasSource::TRANSFORM_FLIP_H;
  2543. }
  2544. bool TileMapLayer::is_cell_flipped_v(const Vector2i &p_coords) const {
  2545. return get_cell_alternative_tile(p_coords) & TileSetAtlasSource::TRANSFORM_FLIP_V;
  2546. }
  2547. bool TileMapLayer::is_cell_transposed(const Vector2i &p_coords) const {
  2548. return get_cell_alternative_tile(p_coords) & TileSetAtlasSource::TRANSFORM_TRANSPOSE;
  2549. }
  2550. Ref<TileMapPattern> TileMapLayer::get_pattern(TypedArray<Vector2i> p_coords_array) {
  2551. ERR_FAIL_COND_V(tile_set.is_null(), nullptr);
  2552. Ref<TileMapPattern> output;
  2553. output.instantiate();
  2554. if (p_coords_array.is_empty()) {
  2555. return output;
  2556. }
  2557. Vector2i min = Vector2i(p_coords_array[0]);
  2558. for (int i = 1; i < p_coords_array.size(); i++) {
  2559. min = min.min(p_coords_array[i]);
  2560. }
  2561. Vector<Vector2i> coords_in_pattern_array;
  2562. coords_in_pattern_array.resize(p_coords_array.size());
  2563. Vector2i ensure_positive_offset;
  2564. for (int i = 0; i < p_coords_array.size(); i++) {
  2565. Vector2i coords = p_coords_array[i];
  2566. Vector2i coords_in_pattern = coords - min;
  2567. if (tile_set->get_tile_shape() != TileSet::TILE_SHAPE_SQUARE) {
  2568. if (tile_set->get_tile_layout() == TileSet::TILE_LAYOUT_STACKED) {
  2569. if (tile_set->get_tile_offset_axis() == TileSet::TILE_OFFSET_AXIS_HORIZONTAL && bool(min.y % 2) && bool(coords_in_pattern.y % 2)) {
  2570. coords_in_pattern.x -= 1;
  2571. if (coords_in_pattern.x < 0) {
  2572. ensure_positive_offset.x = 1;
  2573. }
  2574. } else if (tile_set->get_tile_offset_axis() == TileSet::TILE_OFFSET_AXIS_VERTICAL && bool(min.x % 2) && bool(coords_in_pattern.x % 2)) {
  2575. coords_in_pattern.y -= 1;
  2576. if (coords_in_pattern.y < 0) {
  2577. ensure_positive_offset.y = 1;
  2578. }
  2579. }
  2580. } else if (tile_set->get_tile_layout() == TileSet::TILE_LAYOUT_STACKED_OFFSET) {
  2581. if (tile_set->get_tile_offset_axis() == TileSet::TILE_OFFSET_AXIS_HORIZONTAL && bool(min.y % 2) && bool(coords_in_pattern.y % 2)) {
  2582. coords_in_pattern.x += 1;
  2583. } else if (tile_set->get_tile_offset_axis() == TileSet::TILE_OFFSET_AXIS_VERTICAL && bool(min.x % 2) && bool(coords_in_pattern.x % 2)) {
  2584. coords_in_pattern.y += 1;
  2585. }
  2586. }
  2587. }
  2588. coords_in_pattern_array.write[i] = coords_in_pattern;
  2589. }
  2590. for (int i = 0; i < coords_in_pattern_array.size(); i++) {
  2591. Vector2i coords = p_coords_array[i];
  2592. Vector2i coords_in_pattern = coords_in_pattern_array[i];
  2593. output->set_cell(coords_in_pattern + ensure_positive_offset, get_cell_source_id(coords), get_cell_atlas_coords(coords), get_cell_alternative_tile(coords));
  2594. }
  2595. return output;
  2596. }
  2597. void TileMapLayer::set_pattern(const Vector2i &p_position, const Ref<TileMapPattern> p_pattern) {
  2598. ERR_FAIL_COND(tile_set.is_null());
  2599. ERR_FAIL_COND(p_pattern.is_null());
  2600. TypedArray<Vector2i> used_cells = p_pattern->get_used_cells();
  2601. for (int i = 0; i < used_cells.size(); i++) {
  2602. Vector2i coords = tile_set->map_pattern(p_position, used_cells[i], p_pattern);
  2603. set_cell(coords, p_pattern->get_cell_source_id(used_cells[i]), p_pattern->get_cell_atlas_coords(used_cells[i]), p_pattern->get_cell_alternative_tile(used_cells[i]));
  2604. }
  2605. }
  2606. void TileMapLayer::set_cells_terrain_connect(TypedArray<Vector2i> p_cells, int p_terrain_set, int p_terrain, bool p_ignore_empty_terrains) {
  2607. ERR_FAIL_COND(tile_set.is_null());
  2608. ERR_FAIL_INDEX(p_terrain_set, tile_set->get_terrain_sets_count());
  2609. Vector<Vector2i> cells_vector;
  2610. HashSet<Vector2i> painted_set;
  2611. for (int i = 0; i < p_cells.size(); i++) {
  2612. cells_vector.push_back(p_cells[i]);
  2613. painted_set.insert(p_cells[i]);
  2614. }
  2615. HashMap<Vector2i, TileSet::TerrainsPattern> terrain_fill_output = terrain_fill_connect(cells_vector, p_terrain_set, p_terrain, p_ignore_empty_terrains);
  2616. for (const KeyValue<Vector2i, TileSet::TerrainsPattern> &kv : terrain_fill_output) {
  2617. if (painted_set.has(kv.key)) {
  2618. // Paint a random tile with the correct terrain for the painted path.
  2619. TileMapCell c = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, kv.value);
  2620. set_cell(kv.key, c.source_id, c.get_atlas_coords(), c.alternative_tile);
  2621. } else {
  2622. // Avoids updating the painted path from the output if the new pattern is the same as before.
  2623. TileSet::TerrainsPattern in_map_terrain_pattern = TileSet::TerrainsPattern(*tile_set, p_terrain_set);
  2624. TileMapCell cell = get_cell(kv.key);
  2625. if (cell.source_id != TileSet::INVALID_SOURCE) {
  2626. TileSetSource *source = *tile_set->get_source(cell.source_id);
  2627. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
  2628. if (atlas_source) {
  2629. // Get tile data.
  2630. TileData *tile_data = atlas_source->get_tile_data(cell.get_atlas_coords(), cell.alternative_tile);
  2631. if (tile_data && tile_data->get_terrain_set() == p_terrain_set) {
  2632. in_map_terrain_pattern = tile_data->get_terrains_pattern();
  2633. }
  2634. }
  2635. }
  2636. if (in_map_terrain_pattern != kv.value) {
  2637. TileMapCell c = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, kv.value);
  2638. set_cell(kv.key, c.source_id, c.get_atlas_coords(), c.alternative_tile);
  2639. }
  2640. }
  2641. }
  2642. }
  2643. void TileMapLayer::set_cells_terrain_path(TypedArray<Vector2i> p_path, int p_terrain_set, int p_terrain, bool p_ignore_empty_terrains) {
  2644. ERR_FAIL_COND(tile_set.is_null());
  2645. ERR_FAIL_INDEX(p_terrain_set, tile_set->get_terrain_sets_count());
  2646. Vector<Vector2i> vector_path;
  2647. HashSet<Vector2i> painted_set;
  2648. for (int i = 0; i < p_path.size(); i++) {
  2649. vector_path.push_back(p_path[i]);
  2650. painted_set.insert(p_path[i]);
  2651. }
  2652. HashMap<Vector2i, TileSet::TerrainsPattern> terrain_fill_output = terrain_fill_path(vector_path, p_terrain_set, p_terrain, p_ignore_empty_terrains);
  2653. for (const KeyValue<Vector2i, TileSet::TerrainsPattern> &kv : terrain_fill_output) {
  2654. if (painted_set.has(kv.key)) {
  2655. // Paint a random tile with the correct terrain for the painted path.
  2656. TileMapCell c = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, kv.value);
  2657. set_cell(kv.key, c.source_id, c.get_atlas_coords(), c.alternative_tile);
  2658. } else {
  2659. // Avoids updating the painted path from the output if the new pattern is the same as before.
  2660. TileSet::TerrainsPattern in_map_terrain_pattern = TileSet::TerrainsPattern(*tile_set, p_terrain_set);
  2661. TileMapCell cell = get_cell(kv.key);
  2662. if (cell.source_id != TileSet::INVALID_SOURCE) {
  2663. TileSetSource *source = *tile_set->get_source(cell.source_id);
  2664. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
  2665. if (atlas_source) {
  2666. // Get tile data.
  2667. TileData *tile_data = atlas_source->get_tile_data(cell.get_atlas_coords(), cell.alternative_tile);
  2668. if (tile_data && tile_data->get_terrain_set() == p_terrain_set) {
  2669. in_map_terrain_pattern = tile_data->get_terrains_pattern();
  2670. }
  2671. }
  2672. }
  2673. if (in_map_terrain_pattern != kv.value) {
  2674. TileMapCell c = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, kv.value);
  2675. set_cell(kv.key, c.source_id, c.get_atlas_coords(), c.alternative_tile);
  2676. }
  2677. }
  2678. }
  2679. }
  2680. #ifndef PHYSICS_2D_DISABLED
  2681. bool TileMapLayer::has_body_rid(RID p_physics_body) const {
  2682. return bodies_coords.has(p_physics_body);
  2683. }
  2684. Vector2i TileMapLayer::get_coords_for_body_rid(RID p_physics_body) const {
  2685. const Vector2i *found = bodies_coords.getptr(p_physics_body);
  2686. ERR_FAIL_NULL_V(found, Vector2i());
  2687. return *found;
  2688. }
  2689. #endif // PHYSICS_2D_DISABLED
  2690. void TileMapLayer::update_internals() {
  2691. _internal_update(false);
  2692. }
  2693. void TileMapLayer::notify_runtime_tile_data_update() {
  2694. dirty.flags[TileMapLayer::DIRTY_FLAGS_LAYER_RUNTIME_UPDATE] = true;
  2695. _queue_internal_update();
  2696. emit_signal(CoreStringName(changed));
  2697. }
  2698. Vector2i TileMapLayer::map_pattern(const Vector2i &p_position_in_tilemap, const Vector2i &p_coords_in_pattern, Ref<TileMapPattern> p_pattern) {
  2699. ERR_FAIL_COND_V(tile_set.is_null(), Vector2i());
  2700. return tile_set->map_pattern(p_position_in_tilemap, p_coords_in_pattern, p_pattern);
  2701. }
  2702. TypedArray<Vector2i> TileMapLayer::get_surrounding_cells(const Vector2i &p_coords) {
  2703. ERR_FAIL_COND_V(tile_set.is_null(), TypedArray<Vector2i>());
  2704. return tile_set->get_surrounding_cells(p_coords);
  2705. }
  2706. Vector2i TileMapLayer::get_neighbor_cell(const Vector2i &p_coords, TileSet::CellNeighbor p_cell_neighbor) const {
  2707. ERR_FAIL_COND_V(tile_set.is_null(), Vector2i());
  2708. return tile_set->get_neighbor_cell(p_coords, p_cell_neighbor);
  2709. }
  2710. Vector2 TileMapLayer::map_to_local(const Vector2i &p_pos) const {
  2711. ERR_FAIL_COND_V(tile_set.is_null(), Vector2());
  2712. return tile_set->map_to_local(p_pos);
  2713. }
  2714. Vector2i TileMapLayer::local_to_map(const Vector2 &p_pos) const {
  2715. ERR_FAIL_COND_V(tile_set.is_null(), Vector2i());
  2716. return tile_set->local_to_map(p_pos);
  2717. }
  2718. void TileMapLayer::set_enabled(bool p_enabled) {
  2719. if (enabled == p_enabled) {
  2720. return;
  2721. }
  2722. enabled = p_enabled;
  2723. dirty.flags[DIRTY_FLAGS_LAYER_ENABLED] = true;
  2724. _queue_internal_update();
  2725. emit_signal(CoreStringName(changed));
  2726. }
  2727. bool TileMapLayer::is_enabled() const {
  2728. return enabled;
  2729. }
  2730. void TileMapLayer::set_tile_set(const Ref<TileSet> &p_tile_set) {
  2731. if (p_tile_set == tile_set) {
  2732. return;
  2733. }
  2734. dirty.flags[DIRTY_FLAGS_TILE_SET] = true;
  2735. _queue_internal_update();
  2736. // Set the TileSet, registering to its changes.
  2737. if (tile_set.is_valid()) {
  2738. tile_set->disconnect_changed(callable_mp(this, &TileMapLayer::_tile_set_changed));
  2739. }
  2740. tile_set = p_tile_set;
  2741. if (tile_set.is_valid()) {
  2742. tile_set->connect_changed(callable_mp(this, &TileMapLayer::_tile_set_changed));
  2743. }
  2744. emit_signal(CoreStringName(changed));
  2745. // Trigger updates for TileSet's read-only status.
  2746. notify_property_list_changed();
  2747. }
  2748. Ref<TileSet> TileMapLayer::get_tile_set() const {
  2749. return tile_set;
  2750. }
  2751. void TileMapLayer::set_highlight_mode(HighlightMode p_highlight_mode) {
  2752. if (p_highlight_mode == highlight_mode) {
  2753. return;
  2754. }
  2755. highlight_mode = p_highlight_mode;
  2756. dirty.flags[DIRTY_FLAGS_LAYER_HIGHLIGHT_MODE] = true;
  2757. _queue_internal_update();
  2758. }
  2759. TileMapLayer::HighlightMode TileMapLayer::get_highlight_mode() const {
  2760. return highlight_mode;
  2761. }
  2762. void TileMapLayer::set_tile_map_data_from_array(const Vector<uint8_t> &p_data) {
  2763. if (p_data.is_empty()) {
  2764. clear();
  2765. return;
  2766. }
  2767. const int cell_data_struct_size = 12;
  2768. int size = p_data.size();
  2769. const uint8_t *ptr = p_data.ptr();
  2770. // Index in the array.
  2771. int index = 0;
  2772. // First extract the data version.
  2773. ERR_FAIL_COND_MSG(size < 2, "Corrupted tile map data: not enough bytes.");
  2774. uint16_t format = decode_uint16(&ptr[index]);
  2775. index += 2;
  2776. ERR_FAIL_COND_MSG(format >= TileMapLayerDataFormat::TILE_MAP_LAYER_DATA_FORMAT_MAX, vformat("Unsupported tile map data format: %s. Expected format ID lower or equal to: %s", format, TileMapLayerDataFormat::TILE_MAP_LAYER_DATA_FORMAT_MAX - 1));
  2777. // Clear the TileMap.
  2778. clear();
  2779. while (index < size) {
  2780. ERR_FAIL_COND_MSG(index + cell_data_struct_size > size, vformat("Corrupted tile map data: tiles might be missing."));
  2781. // Get a pointer at the start of the cell data.
  2782. const uint8_t *cell_data_ptr = &ptr[index];
  2783. // Extracts position in TileMap.
  2784. int16_t x = decode_uint16(&cell_data_ptr[0]);
  2785. int16_t y = decode_uint16(&cell_data_ptr[2]);
  2786. // Extracts the tile identifiers.
  2787. uint16_t source_id = decode_uint16(&cell_data_ptr[4]);
  2788. uint16_t atlas_coords_x = decode_uint16(&cell_data_ptr[6]);
  2789. uint16_t atlas_coords_y = decode_uint16(&cell_data_ptr[8]);
  2790. uint16_t alternative_tile = decode_uint16(&cell_data_ptr[10]);
  2791. set_cell(Vector2i(x, y), source_id, Vector2i(atlas_coords_x, atlas_coords_y), alternative_tile);
  2792. index += cell_data_struct_size;
  2793. }
  2794. }
  2795. Vector<uint8_t> TileMapLayer::get_tile_map_data_as_array() const {
  2796. const int cell_data_struct_size = 12;
  2797. Vector<uint8_t> tile_map_data_array;
  2798. if (tile_map_layer_data.is_empty()) {
  2799. return tile_map_data_array;
  2800. }
  2801. tile_map_data_array.resize(2 + tile_map_layer_data.size() * cell_data_struct_size);
  2802. uint8_t *ptr = tile_map_data_array.ptrw();
  2803. // Index in the array.
  2804. int index = 0;
  2805. // Save the version.
  2806. encode_uint16(TileMapLayerDataFormat::TILE_MAP_LAYER_DATA_FORMAT_MAX - 1, &ptr[index]);
  2807. index += 2;
  2808. // Save in highest format.
  2809. for (const KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
  2810. // Get a pointer at the start of the cell data.
  2811. uint8_t *cell_data_ptr = (uint8_t *)&ptr[index];
  2812. // Store position in TileMap.
  2813. encode_uint16((int16_t)(E.key.x), &cell_data_ptr[0]);
  2814. encode_uint16((int16_t)(E.key.y), &cell_data_ptr[2]);
  2815. // Store the tile identifiers.
  2816. encode_uint16(E.value.cell.source_id, &cell_data_ptr[4]);
  2817. encode_uint16(E.value.cell.coord_x, &cell_data_ptr[6]);
  2818. encode_uint16(E.value.cell.coord_y, &cell_data_ptr[8]);
  2819. encode_uint16(E.value.cell.alternative_tile, &cell_data_ptr[10]);
  2820. index += cell_data_struct_size;
  2821. }
  2822. return tile_map_data_array;
  2823. }
  2824. void TileMapLayer::set_self_modulate(const Color &p_self_modulate) {
  2825. if (get_self_modulate() == p_self_modulate) {
  2826. return;
  2827. }
  2828. CanvasItem::set_self_modulate(p_self_modulate);
  2829. dirty.flags[DIRTY_FLAGS_LAYER_SELF_MODULATE] = true;
  2830. _queue_internal_update();
  2831. emit_signal(CoreStringName(changed));
  2832. }
  2833. void TileMapLayer::set_y_sort_enabled(bool p_y_sort_enabled) {
  2834. if (is_y_sort_enabled() == p_y_sort_enabled) {
  2835. return;
  2836. }
  2837. CanvasItem::set_y_sort_enabled(p_y_sort_enabled);
  2838. dirty.flags[DIRTY_FLAGS_LAYER_Y_SORT_ENABLED] = true;
  2839. _queue_internal_update();
  2840. emit_signal(CoreStringName(changed));
  2841. notify_property_list_changed();
  2842. _update_notify_local_transform();
  2843. }
  2844. void TileMapLayer::set_y_sort_origin(int p_y_sort_origin) {
  2845. if (y_sort_origin == p_y_sort_origin) {
  2846. return;
  2847. }
  2848. y_sort_origin = p_y_sort_origin;
  2849. dirty.flags[DIRTY_FLAGS_LAYER_Y_SORT_ORIGIN] = true;
  2850. _queue_internal_update();
  2851. emit_signal(CoreStringName(changed));
  2852. }
  2853. int TileMapLayer::get_y_sort_origin() const {
  2854. return y_sort_origin;
  2855. }
  2856. void TileMapLayer::set_x_draw_order_reversed(bool p_x_draw_order_reversed) {
  2857. if (x_draw_order_reversed == p_x_draw_order_reversed) {
  2858. return;
  2859. }
  2860. x_draw_order_reversed = p_x_draw_order_reversed;
  2861. dirty.flags[DIRTY_FLAGS_LAYER_X_DRAW_ORDER_REVERSED] = true;
  2862. _queue_internal_update();
  2863. emit_signal(CoreStringName(changed));
  2864. }
  2865. bool TileMapLayer::is_x_draw_order_reversed() const {
  2866. return x_draw_order_reversed;
  2867. }
  2868. void TileMapLayer::set_z_index(int p_z_index) {
  2869. if (get_z_index() == p_z_index) {
  2870. return;
  2871. }
  2872. CanvasItem::set_z_index(p_z_index);
  2873. dirty.flags[DIRTY_FLAGS_LAYER_Z_INDEX] = true;
  2874. _queue_internal_update();
  2875. emit_signal(CoreStringName(changed));
  2876. }
  2877. void TileMapLayer::set_light_mask(int p_light_mask) {
  2878. if (get_light_mask() == p_light_mask) {
  2879. return;
  2880. }
  2881. CanvasItem::set_light_mask(p_light_mask);
  2882. dirty.flags[DIRTY_FLAGS_LAYER_LIGHT_MASK] = true;
  2883. _queue_internal_update();
  2884. emit_signal(CoreStringName(changed));
  2885. }
  2886. void TileMapLayer::set_rendering_quadrant_size(int p_size) {
  2887. if (rendering_quadrant_size == p_size) {
  2888. return;
  2889. }
  2890. ERR_FAIL_COND_MSG(p_size < 1, "TileMapQuadrant size cannot be smaller than 1.");
  2891. rendering_quadrant_size = p_size;
  2892. dirty.flags[DIRTY_FLAGS_LAYER_RENDERING_QUADRANT_SIZE] = true;
  2893. _queue_internal_update();
  2894. emit_signal(CoreStringName(changed));
  2895. }
  2896. int TileMapLayer::get_rendering_quadrant_size() const {
  2897. return rendering_quadrant_size;
  2898. }
  2899. void TileMapLayer::set_collision_enabled(bool p_enabled) {
  2900. if (collision_enabled == p_enabled) {
  2901. return;
  2902. }
  2903. collision_enabled = p_enabled;
  2904. dirty.flags[DIRTY_FLAGS_LAYER_COLLISION_ENABLED] = true;
  2905. _queue_internal_update();
  2906. emit_signal(CoreStringName(changed));
  2907. }
  2908. bool TileMapLayer::is_collision_enabled() const {
  2909. return collision_enabled;
  2910. }
  2911. void TileMapLayer::set_use_kinematic_bodies(bool p_use_kinematic_bodies) {
  2912. if (use_kinematic_bodies == p_use_kinematic_bodies) {
  2913. return;
  2914. }
  2915. use_kinematic_bodies = p_use_kinematic_bodies;
  2916. dirty.flags[DIRTY_FLAGS_LAYER_USE_KINEMATIC_BODIES] = p_use_kinematic_bodies;
  2917. _queue_internal_update();
  2918. emit_signal(CoreStringName(changed));
  2919. }
  2920. bool TileMapLayer::is_using_kinematic_bodies() const {
  2921. return use_kinematic_bodies;
  2922. }
  2923. void TileMapLayer::set_collision_visibility_mode(TileMapLayer::DebugVisibilityMode p_show_collision) {
  2924. if (collision_visibility_mode == p_show_collision) {
  2925. return;
  2926. }
  2927. collision_visibility_mode = p_show_collision;
  2928. dirty.flags[DIRTY_FLAGS_LAYER_COLLISION_VISIBILITY_MODE] = true;
  2929. _queue_internal_update();
  2930. emit_signal(CoreStringName(changed));
  2931. }
  2932. TileMapLayer::DebugVisibilityMode TileMapLayer::get_collision_visibility_mode() const {
  2933. return collision_visibility_mode;
  2934. }
  2935. void TileMapLayer::set_physics_quadrant_size(int p_size) {
  2936. if (physics_quadrant_size == p_size) {
  2937. return;
  2938. }
  2939. ERR_FAIL_COND_MSG(p_size < 1, "Physics quandrant size cannot be smaller than 1.");
  2940. physics_quadrant_size = p_size;
  2941. dirty.flags[DIRTY_FLAGS_LAYER_PHYSICS_QUADRANT_SIZE] = true;
  2942. _queue_internal_update();
  2943. emit_signal(CoreStringName(changed));
  2944. }
  2945. int TileMapLayer::get_physics_quadrant_size() const {
  2946. return physics_quadrant_size;
  2947. }
  2948. void TileMapLayer::set_occlusion_enabled(bool p_enabled) {
  2949. if (occlusion_enabled == p_enabled) {
  2950. return;
  2951. }
  2952. occlusion_enabled = p_enabled;
  2953. dirty.flags[DIRTY_FLAGS_LAYER_OCCLUSION_ENABLED] = true;
  2954. _queue_internal_update();
  2955. emit_signal(CoreStringName(changed));
  2956. }
  2957. bool TileMapLayer::is_occlusion_enabled() const {
  2958. return occlusion_enabled;
  2959. }
  2960. #ifndef NAVIGATION_2D_DISABLED
  2961. void TileMapLayer::set_navigation_enabled(bool p_enabled) {
  2962. if (navigation_enabled == p_enabled) {
  2963. return;
  2964. }
  2965. navigation_enabled = p_enabled;
  2966. dirty.flags[DIRTY_FLAGS_LAYER_NAVIGATION_ENABLED] = true;
  2967. _queue_internal_update();
  2968. emit_signal(CoreStringName(changed));
  2969. }
  2970. bool TileMapLayer::is_navigation_enabled() const {
  2971. return navigation_enabled;
  2972. }
  2973. void TileMapLayer::set_navigation_map(RID p_map) {
  2974. if (navigation_map_override == p_map) {
  2975. return;
  2976. }
  2977. navigation_map_override = p_map;
  2978. dirty.flags[DIRTY_FLAGS_LAYER_NAVIGATION_MAP] = true;
  2979. _queue_internal_update();
  2980. emit_signal(CoreStringName(changed));
  2981. }
  2982. RID TileMapLayer::get_navigation_map() const {
  2983. if (navigation_map_override.is_valid()) {
  2984. return navigation_map_override;
  2985. } else if (is_inside_tree()) {
  2986. return get_world_2d()->get_navigation_map();
  2987. }
  2988. return RID();
  2989. }
  2990. void TileMapLayer::set_navigation_visibility_mode(TileMapLayer::DebugVisibilityMode p_show_navigation) {
  2991. if (navigation_visibility_mode == p_show_navigation) {
  2992. return;
  2993. }
  2994. navigation_visibility_mode = p_show_navigation;
  2995. dirty.flags[DIRTY_FLAGS_LAYER_NAVIGATION_VISIBILITY_MODE] = true;
  2996. _queue_internal_update();
  2997. emit_signal(CoreStringName(changed));
  2998. }
  2999. TileMapLayer::DebugVisibilityMode TileMapLayer::get_navigation_visibility_mode() const {
  3000. return navigation_visibility_mode;
  3001. }
  3002. void TileMapLayer::navmesh_parse_init() {
  3003. ERR_FAIL_NULL(NavigationServer2D::get_singleton());
  3004. if (!_navmesh_source_geometry_parser.is_valid()) {
  3005. _navmesh_source_geometry_parsing_callback = callable_mp_static(&TileMapLayer::navmesh_parse_source_geometry);
  3006. _navmesh_source_geometry_parser = NavigationServer2D::get_singleton()->source_geometry_parser_create();
  3007. NavigationServer2D::get_singleton()->source_geometry_parser_set_callback(_navmesh_source_geometry_parser, _navmesh_source_geometry_parsing_callback);
  3008. }
  3009. }
  3010. void TileMapLayer::navmesh_parse_source_geometry(const Ref<NavigationPolygon> &p_navigation_mesh, Ref<NavigationMeshSourceGeometryData2D> p_source_geometry_data, Node *p_node) {
  3011. TileMapLayer *tile_map_layer = Object::cast_to<TileMapLayer>(p_node);
  3012. if (tile_map_layer == nullptr) {
  3013. return;
  3014. }
  3015. Ref<TileSet> tile_set = tile_map_layer->get_tile_set();
  3016. if (tile_set.is_null()) {
  3017. return;
  3018. }
  3019. int navigation_layers_count = tile_set->get_navigation_layers_count();
  3020. #ifndef PHYSICS_2D_DISABLED
  3021. int physics_layers_count = tile_set->get_physics_layers_count();
  3022. if (physics_layers_count <= 0 && navigation_layers_count <= 0) {
  3023. return;
  3024. }
  3025. #else
  3026. if (navigation_layers_count <= 0) {
  3027. return;
  3028. }
  3029. #endif // PHYSICS_2D_DISABLED
  3030. const Transform2D tilemap_xform = p_source_geometry_data->root_node_transform * tile_map_layer->get_global_transform();
  3031. for (KeyValue<Vector2i, CellData> kv : tile_map_layer->get_tile_map_layer_data()) {
  3032. const Vector2i &cell = kv.key;
  3033. const TileData *tile_data = tile_map_layer->get_cell_tile_data(cell);
  3034. if (tile_data == nullptr) {
  3035. continue;
  3036. }
  3037. // Transform flags.
  3038. const int alternative_id = tile_map_layer->get_cell_alternative_tile(cell);
  3039. bool flip_h = (alternative_id & TileSetAtlasSource::TRANSFORM_FLIP_H);
  3040. bool flip_v = (alternative_id & TileSetAtlasSource::TRANSFORM_FLIP_V);
  3041. bool transpose = (alternative_id & TileSetAtlasSource::TRANSFORM_TRANSPOSE);
  3042. Transform2D tile_transform;
  3043. tile_transform.set_origin(tile_map_layer->map_to_local(cell));
  3044. const Transform2D tile_transform_offset = tilemap_xform * tile_transform;
  3045. // Parse traversable polygons.
  3046. for (int navigation_layer = 0; navigation_layer < navigation_layers_count; navigation_layer++) {
  3047. Ref<NavigationPolygon> navigation_polygon = tile_data->get_navigation_polygon(navigation_layer, flip_h, flip_v, transpose);
  3048. if (navigation_polygon.is_valid()) {
  3049. for (int outline_index = 0; outline_index < navigation_polygon->get_outline_count(); outline_index++) {
  3050. const Vector<Vector2> &navigation_polygon_outline = navigation_polygon->get_outline(outline_index);
  3051. if (navigation_polygon_outline.is_empty()) {
  3052. continue;
  3053. }
  3054. Vector<Vector2> traversable_outline = tile_transform_offset.xform(navigation_polygon_outline);
  3055. p_source_geometry_data->_add_traversable_outline(traversable_outline);
  3056. }
  3057. }
  3058. }
  3059. #ifndef PHYSICS_2D_DISABLED
  3060. NavigationPolygon::ParsedGeometryType parsed_geometry_type = p_navigation_mesh->get_parsed_geometry_type();
  3061. uint32_t parsed_collision_mask = p_navigation_mesh->get_parsed_collision_mask();
  3062. // Parse obstacles.
  3063. for (int physics_layer = 0; physics_layer < physics_layers_count; physics_layer++) {
  3064. if ((parsed_geometry_type == NavigationPolygon::PARSED_GEOMETRY_STATIC_COLLIDERS || parsed_geometry_type == NavigationPolygon::PARSED_GEOMETRY_BOTH) &&
  3065. (tile_set->get_physics_layer_collision_layer(physics_layer) & parsed_collision_mask)) {
  3066. for (int collision_polygon_index = 0; collision_polygon_index < tile_data->get_collision_polygons_count(physics_layer); collision_polygon_index++) {
  3067. PackedVector2Array collision_polygon_points = tile_data->get_collision_polygon_points(physics_layer, collision_polygon_index);
  3068. if (collision_polygon_points.is_empty()) {
  3069. continue;
  3070. }
  3071. if (flip_h || flip_v || transpose) {
  3072. collision_polygon_points = TileData::get_transformed_vertices(collision_polygon_points, flip_h, flip_v, transpose);
  3073. }
  3074. Vector<Vector2> obstruction_outline = tile_transform_offset.xform(collision_polygon_points);
  3075. p_source_geometry_data->_add_obstruction_outline(obstruction_outline);
  3076. }
  3077. }
  3078. }
  3079. #endif // PHYSICS_2D_DISABLED
  3080. }
  3081. }
  3082. #endif // NAVIGATION_2D_DISABLED
  3083. TileMapLayer::TileMapLayer() {
  3084. set_notify_transform(true);
  3085. }
  3086. TileMapLayer::~TileMapLayer() {
  3087. clear();
  3088. _internal_update(true);
  3089. }
  3090. HashMap<Vector2i, TileSet::CellNeighbor> TerrainConstraint::get_overlapping_coords_and_peering_bits() const {
  3091. ERR_FAIL_COND_V(is_center_bit(), (HashMap<Vector2i, TileSet::CellNeighbor>()));
  3092. ERR_FAIL_COND_V(tile_set.is_null(), (HashMap<Vector2i, TileSet::CellNeighbor>()));
  3093. HashMap<Vector2i, TileSet::CellNeighbor> output;
  3094. TileSet::TileShape shape = tile_set->get_tile_shape();
  3095. if (shape == TileSet::TILE_SHAPE_SQUARE) {
  3096. switch (bit) {
  3097. case 1:
  3098. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_RIGHT_SIDE;
  3099. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_LEFT_SIDE;
  3100. break;
  3101. case 2:
  3102. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_CORNER;
  3103. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_CORNER;
  3104. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_CORNER)] = TileSet::CELL_NEIGHBOR_TOP_LEFT_CORNER;
  3105. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_RIGHT_CORNER;
  3106. break;
  3107. case 3:
  3108. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_SIDE;
  3109. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_SIDE;
  3110. break;
  3111. default:
  3112. ERR_FAIL_V(output);
  3113. }
  3114. } else if (shape == TileSet::TILE_SHAPE_ISOMETRIC) {
  3115. switch (bit) {
  3116. case 1:
  3117. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE;
  3118. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE;
  3119. break;
  3120. case 2:
  3121. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_CORNER;
  3122. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_LEFT_CORNER;
  3123. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_CORNER)] = TileSet::CELL_NEIGHBOR_TOP_CORNER;
  3124. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE)] = TileSet::CELL_NEIGHBOR_RIGHT_CORNER;
  3125. break;
  3126. case 3:
  3127. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE;
  3128. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE;
  3129. break;
  3130. default:
  3131. ERR_FAIL_V(output);
  3132. }
  3133. } else {
  3134. // Half offset shapes.
  3135. TileSet::TileOffsetAxis offset_axis = tile_set->get_tile_offset_axis();
  3136. if (offset_axis == TileSet::TILE_OFFSET_AXIS_HORIZONTAL) {
  3137. switch (bit) {
  3138. case 1:
  3139. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_RIGHT_SIDE;
  3140. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_LEFT_SIDE;
  3141. break;
  3142. case 2:
  3143. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_CORNER;
  3144. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_CORNER;
  3145. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_CORNER;
  3146. break;
  3147. case 3:
  3148. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE;
  3149. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE;
  3150. break;
  3151. case 4:
  3152. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_CORNER;
  3153. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_LEFT_CORNER;
  3154. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_RIGHT_CORNER;
  3155. break;
  3156. case 5:
  3157. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE;
  3158. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE;
  3159. break;
  3160. default:
  3161. ERR_FAIL_V(output);
  3162. }
  3163. } else {
  3164. switch (bit) {
  3165. case 1:
  3166. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_RIGHT_CORNER;
  3167. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_CORNER;
  3168. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_LEFT_CORNER;
  3169. break;
  3170. case 2:
  3171. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE;
  3172. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE;
  3173. break;
  3174. case 3:
  3175. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_CORNER;
  3176. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_LEFT_CORNER;
  3177. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_LEFT_CORNER;
  3178. break;
  3179. case 4:
  3180. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_SIDE;
  3181. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_SIDE;
  3182. break;
  3183. case 5:
  3184. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE;
  3185. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE;
  3186. break;
  3187. default:
  3188. ERR_FAIL_V(output);
  3189. }
  3190. }
  3191. }
  3192. return output;
  3193. }
  3194. TerrainConstraint::TerrainConstraint(Ref<TileSet> p_tile_set, const Vector2i &p_position, int p_terrain) {
  3195. ERR_FAIL_COND(p_tile_set.is_null());
  3196. tile_set = p_tile_set;
  3197. bit = 0;
  3198. base_cell_coords = p_position;
  3199. terrain = p_terrain;
  3200. }
  3201. TerrainConstraint::TerrainConstraint(Ref<TileSet> p_tile_set, const Vector2i &p_position, const TileSet::CellNeighbor &p_bit, int p_terrain) {
  3202. // The way we build the constraint make it easy to detect conflicting constraints.
  3203. ERR_FAIL_COND(p_tile_set.is_null());
  3204. tile_set = p_tile_set;
  3205. TileSet::TileShape shape = tile_set->get_tile_shape();
  3206. if (shape == TileSet::TILE_SHAPE_SQUARE) {
  3207. switch (p_bit) {
  3208. case TileSet::CELL_NEIGHBOR_RIGHT_SIDE:
  3209. bit = 1;
  3210. base_cell_coords = p_position;
  3211. break;
  3212. case TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_CORNER:
  3213. bit = 2;
  3214. base_cell_coords = p_position;
  3215. break;
  3216. case TileSet::CELL_NEIGHBOR_BOTTOM_SIDE:
  3217. bit = 3;
  3218. base_cell_coords = p_position;
  3219. break;
  3220. case TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_CORNER:
  3221. bit = 2;
  3222. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_LEFT_SIDE);
  3223. break;
  3224. case TileSet::CELL_NEIGHBOR_LEFT_SIDE:
  3225. bit = 1;
  3226. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_LEFT_SIDE);
  3227. break;
  3228. case TileSet::CELL_NEIGHBOR_TOP_LEFT_CORNER:
  3229. bit = 2;
  3230. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_CORNER);
  3231. break;
  3232. case TileSet::CELL_NEIGHBOR_TOP_SIDE:
  3233. bit = 3;
  3234. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_SIDE);
  3235. break;
  3236. case TileSet::CELL_NEIGHBOR_TOP_RIGHT_CORNER:
  3237. bit = 2;
  3238. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_SIDE);
  3239. break;
  3240. default:
  3241. ERR_FAIL();
  3242. break;
  3243. }
  3244. } else if (shape == TileSet::TILE_SHAPE_ISOMETRIC) {
  3245. switch (p_bit) {
  3246. case TileSet::CELL_NEIGHBOR_RIGHT_CORNER:
  3247. bit = 2;
  3248. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE);
  3249. break;
  3250. case TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE:
  3251. bit = 1;
  3252. base_cell_coords = p_position;
  3253. break;
  3254. case TileSet::CELL_NEIGHBOR_BOTTOM_CORNER:
  3255. bit = 2;
  3256. base_cell_coords = p_position;
  3257. break;
  3258. case TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE:
  3259. bit = 3;
  3260. base_cell_coords = p_position;
  3261. break;
  3262. case TileSet::CELL_NEIGHBOR_LEFT_CORNER:
  3263. bit = 2;
  3264. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE);
  3265. break;
  3266. case TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE:
  3267. bit = 1;
  3268. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE);
  3269. break;
  3270. case TileSet::CELL_NEIGHBOR_TOP_CORNER:
  3271. bit = 2;
  3272. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_CORNER);
  3273. break;
  3274. case TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE:
  3275. bit = 3;
  3276. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE);
  3277. break;
  3278. default:
  3279. ERR_FAIL();
  3280. break;
  3281. }
  3282. } else {
  3283. // Half-offset shapes.
  3284. TileSet::TileOffsetAxis offset_axis = tile_set->get_tile_offset_axis();
  3285. if (offset_axis == TileSet::TILE_OFFSET_AXIS_HORIZONTAL) {
  3286. switch (p_bit) {
  3287. case TileSet::CELL_NEIGHBOR_RIGHT_SIDE:
  3288. bit = 1;
  3289. base_cell_coords = p_position;
  3290. break;
  3291. case TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_CORNER:
  3292. bit = 2;
  3293. base_cell_coords = p_position;
  3294. break;
  3295. case TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE:
  3296. bit = 3;
  3297. base_cell_coords = p_position;
  3298. break;
  3299. case TileSet::CELL_NEIGHBOR_BOTTOM_CORNER:
  3300. bit = 4;
  3301. base_cell_coords = p_position;
  3302. break;
  3303. case TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE:
  3304. bit = 5;
  3305. base_cell_coords = p_position;
  3306. break;
  3307. case TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_CORNER:
  3308. bit = 2;
  3309. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_LEFT_SIDE);
  3310. break;
  3311. case TileSet::CELL_NEIGHBOR_LEFT_SIDE:
  3312. bit = 1;
  3313. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_LEFT_SIDE);
  3314. break;
  3315. case TileSet::CELL_NEIGHBOR_TOP_LEFT_CORNER:
  3316. bit = 4;
  3317. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE);
  3318. break;
  3319. case TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE:
  3320. bit = 3;
  3321. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE);
  3322. break;
  3323. case TileSet::CELL_NEIGHBOR_TOP_CORNER:
  3324. bit = 2;
  3325. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE);
  3326. break;
  3327. case TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE:
  3328. bit = 5;
  3329. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE);
  3330. break;
  3331. case TileSet::CELL_NEIGHBOR_TOP_RIGHT_CORNER:
  3332. bit = 4;
  3333. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE);
  3334. break;
  3335. default:
  3336. ERR_FAIL();
  3337. break;
  3338. }
  3339. } else {
  3340. switch (p_bit) {
  3341. case TileSet::CELL_NEIGHBOR_RIGHT_CORNER:
  3342. bit = 1;
  3343. base_cell_coords = p_position;
  3344. break;
  3345. case TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE:
  3346. bit = 2;
  3347. base_cell_coords = p_position;
  3348. break;
  3349. case TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_CORNER:
  3350. bit = 3;
  3351. base_cell_coords = p_position;
  3352. break;
  3353. case TileSet::CELL_NEIGHBOR_BOTTOM_SIDE:
  3354. bit = 4;
  3355. base_cell_coords = p_position;
  3356. break;
  3357. case TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_CORNER:
  3358. bit = 1;
  3359. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE);
  3360. break;
  3361. case TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE:
  3362. bit = 5;
  3363. base_cell_coords = p_position;
  3364. break;
  3365. case TileSet::CELL_NEIGHBOR_LEFT_CORNER:
  3366. bit = 3;
  3367. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE);
  3368. break;
  3369. case TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE:
  3370. bit = 2;
  3371. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE);
  3372. break;
  3373. case TileSet::CELL_NEIGHBOR_TOP_LEFT_CORNER:
  3374. bit = 1;
  3375. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE);
  3376. break;
  3377. case TileSet::CELL_NEIGHBOR_TOP_SIDE:
  3378. bit = 4;
  3379. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_SIDE);
  3380. break;
  3381. case TileSet::CELL_NEIGHBOR_TOP_RIGHT_CORNER:
  3382. bit = 3;
  3383. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_SIDE);
  3384. break;
  3385. case TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE:
  3386. bit = 5;
  3387. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE);
  3388. break;
  3389. default:
  3390. ERR_FAIL();
  3391. break;
  3392. }
  3393. }
  3394. }
  3395. terrain = p_terrain;
  3396. }