tile_map_layer.cpp 152 KB

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