map.c 123 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459
  1. // Copyright (c) Athena Dev Teams - Licensed under GNU GPL
  2. // For more information, see LICENCE in the main folder
  3. #include "../common/cbasetypes.h"
  4. #include "../common/core.h"
  5. #include "../common/timer.h"
  6. #include "../common/grfio.h"
  7. #include "../common/malloc.h"
  8. #include "../common/socket.h" // WFIFO*()
  9. #include "../common/showmsg.h"
  10. #include "../common/nullpo.h"
  11. #include "../common/random.h"
  12. #include "../common/strlib.h"
  13. #include "../common/utils.h"
  14. #include "../common/cli.h"
  15. #include "../common/ers.h"
  16. #include "map.h"
  17. #include "path.h"
  18. #include "chrif.h"
  19. #include "clif.h"
  20. #include "duel.h"
  21. #include "intif.h"
  22. #include "npc.h"
  23. #include "pc.h"
  24. #include "chat.h"
  25. #include "storage.h"
  26. #include "trade.h"
  27. #include "party.h"
  28. #include "battleground.h"
  29. #include "quest.h"
  30. #include "mapreg.h"
  31. #include "pet.h"
  32. #include "homunculus.h"
  33. #include "instance.h"
  34. #include "mercenary.h"
  35. #include "elemental.h"
  36. #include "cashshop.h"
  37. #include "channel.h"
  38. #include <stdlib.h>
  39. #include <math.h>
  40. #ifndef _WIN32
  41. #endif
  42. char default_codepage[32] = "";
  43. int map_server_port = 3306;
  44. char map_server_ip[32] = "127.0.0.1";
  45. char map_server_id[32] = "ragnarok";
  46. char map_server_pw[32] = "";
  47. char map_server_db[32] = "ragnarok";
  48. Sql* mmysql_handle;
  49. Sql* qsmysql_handle; /// For query_sql
  50. int db_use_sqldbs = 0;
  51. char buyingstores_db[32] = "buyingstores";
  52. char buyingstore_items_db[32] = "buyingstore_items";
  53. char item_db_db[32] = "item_db";
  54. char item_db2_db[32] = "item_db2";
  55. char item_db_re_db[32] = "item_db_re";
  56. char item_cash_db_db[32] = "item_cash_db";
  57. char item_cash_db2_db[32] = "item_cash_db2";
  58. char mob_db_db[32] = "mob_db";
  59. char mob_db_re_db[32] = "mob_db_re";
  60. char mob_db2_db[32] = "mob_db2";
  61. char mob_skill_db_db[32] = "mob_skill_db";
  62. char mob_skill_db_re_db[32] = "mob_skill_db_re";
  63. char mob_skill_db2_db[32] = "mob_skill_db2";
  64. char vendings_db[32] = "vendings";
  65. char vending_items_db[32] = "vending_items";
  66. // log database
  67. char log_db_ip[32] = "127.0.0.1";
  68. int log_db_port = 3306;
  69. char log_db_id[32] = "ragnarok";
  70. char log_db_pw[32] = "ragnarok";
  71. char log_db_db[32] = "log";
  72. Sql* logmysql_handle;
  73. // DBMap declaration
  74. static DBMap* id_db=NULL; /// int id -> struct block_list*
  75. static DBMap* pc_db=NULL; /// int id -> struct map_session_data*
  76. static DBMap* mobid_db=NULL; /// int id -> struct mob_data*
  77. static DBMap* bossid_db=NULL; /// int id -> struct mob_data* (MVP db)
  78. static DBMap* map_db=NULL; /// unsigned int mapindex -> struct map_data*
  79. static DBMap* nick_db=NULL; /// uint32 char_id -> struct charid2nick* (requested names of offline characters)
  80. static DBMap* charid_db=NULL; /// uint32 char_id -> struct map_session_data*
  81. static DBMap* regen_db=NULL; /// int id -> struct block_list* (status_natural_heal processing)
  82. static DBMap* map_msg_db=NULL;
  83. static int map_users=0;
  84. #define BLOCK_SIZE 8
  85. #define block_free_max 1048576
  86. struct block_list *block_free[block_free_max];
  87. static int block_free_count = 0, block_free_lock = 0;
  88. #define BL_LIST_MAX 1048576
  89. static struct block_list *bl_list[BL_LIST_MAX];
  90. static int bl_list_count = 0;
  91. #define MAP_MAX_MSG 1500
  92. struct map_data map[MAX_MAP_PER_SERVER];
  93. int map_num = 0;
  94. int map_port=0;
  95. int autosave_interval = DEFAULT_AUTOSAVE_INTERVAL;
  96. int minsave_interval = 100;
  97. unsigned char save_settings = CHARSAVE_ALL;
  98. int agit_flag = 0;
  99. int agit2_flag = 0;
  100. int night_flag = 0; // 0=day, 1=night [Yor]
  101. #ifdef ADJUST_SKILL_DAMAGE
  102. struct eri *map_skill_damage_ers = NULL;
  103. #endif
  104. struct charid_request {
  105. struct charid_request* next;
  106. int charid;// who want to be notified of the nick
  107. };
  108. struct charid2nick {
  109. char nick[NAME_LENGTH];
  110. struct charid_request* requests;// requests of notification on this nick
  111. };
  112. // This is the main header found at the very beginning of the map cache
  113. struct map_cache_main_header {
  114. uint32 file_size;
  115. uint16 map_count;
  116. };
  117. // This is the header appended before every compressed map cells info in the map cache
  118. struct map_cache_map_info {
  119. char name[MAP_NAME_LENGTH];
  120. int16 xs;
  121. int16 ys;
  122. int32 len;
  123. };
  124. char motd_txt[256] = "conf/motd.txt";
  125. char help_txt[256] = "conf/help.txt";
  126. char help2_txt[256] = "conf/help2.txt";
  127. char charhelp_txt[256] = "conf/charhelp.txt";
  128. char wisp_server_name[NAME_LENGTH] = "Server"; // can be modified in char-server configuration file
  129. struct s_map_default map_default;
  130. int console = 0;
  131. int enable_spy = 0; //To enable/disable @spy commands, which consume too much cpu time when sending packets. [Skotlex]
  132. int enable_grf = 0; //To enable/disable reading maps from GRF files, bypassing mapcache [blackhole89]
  133. /*==========================================
  134. * server player count (of all mapservers)
  135. *------------------------------------------*/
  136. void map_setusers(int users)
  137. {
  138. map_users = users;
  139. }
  140. int map_getusers(void)
  141. {
  142. return map_users;
  143. }
  144. /*==========================================
  145. * server player count (this mapserver only)
  146. *------------------------------------------*/
  147. int map_usercount(void)
  148. {
  149. return pc_db->size(pc_db);
  150. }
  151. /*==========================================
  152. * Attempt to free a map blocklist
  153. *------------------------------------------*/
  154. int map_freeblock (struct block_list *bl)
  155. {
  156. nullpo_retr(block_free_lock, bl);
  157. if (block_free_lock == 0 || block_free_count >= block_free_max)
  158. {
  159. aFree(bl);
  160. bl = NULL;
  161. if (block_free_count >= block_free_max)
  162. ShowWarning("map_freeblock: too many free block! %d %d\n", block_free_count, block_free_lock);
  163. } else
  164. block_free[block_free_count++] = bl;
  165. return block_free_lock;
  166. }
  167. /*==========================================
  168. * Lock blocklist, (prevent map_freeblock usage)
  169. *------------------------------------------*/
  170. int map_freeblock_lock (void)
  171. {
  172. return ++block_free_lock;
  173. }
  174. /*==========================================
  175. * Remove the lock on map_bl
  176. *------------------------------------------*/
  177. int map_freeblock_unlock (void)
  178. {
  179. if ((--block_free_lock) == 0) {
  180. int i;
  181. for (i = 0; i < block_free_count; i++)
  182. {
  183. aFree(block_free[i]);
  184. block_free[i] = NULL;
  185. }
  186. block_free_count = 0;
  187. } else if (block_free_lock < 0) {
  188. ShowError("map_freeblock_unlock: lock count < 0 !\n");
  189. block_free_lock = 0;
  190. }
  191. return block_free_lock;
  192. }
  193. // Timer function to check if there some remaining lock and remove them if so.
  194. // Called each 1s
  195. int map_freeblock_timer(int tid, unsigned int tick, int id, intptr_t data)
  196. {
  197. if (block_free_lock > 0) {
  198. ShowError("map_freeblock_timer: block_free_lock(%d) is invalid.\n", block_free_lock);
  199. block_free_lock = 1;
  200. map_freeblock_unlock();
  201. }
  202. return 0;
  203. }
  204. //
  205. // blocklist
  206. //
  207. /*==========================================
  208. * Handling of map_bl[]
  209. * The address of bl_heal is set in bl->prev
  210. *------------------------------------------*/
  211. static struct block_list bl_head;
  212. #ifdef CELL_NOSTACK
  213. /*==========================================
  214. * These pair of functions update the counter of how many objects
  215. * lie on a tile.
  216. *------------------------------------------*/
  217. static void map_addblcell(struct block_list *bl)
  218. {
  219. if( bl->m<0 || bl->x<0 || bl->x>=map[bl->m].xs || bl->y<0 || bl->y>=map[bl->m].ys || !(bl->type&BL_CHAR) )
  220. return;
  221. map[bl->m].cell[bl->x+bl->y*map[bl->m].xs].cell_bl++;
  222. return;
  223. }
  224. static void map_delblcell(struct block_list *bl)
  225. {
  226. if( bl->m <0 || bl->x<0 || bl->x>=map[bl->m].xs || bl->y<0 || bl->y>=map[bl->m].ys || !(bl->type&BL_CHAR) )
  227. return;
  228. map[bl->m].cell[bl->x+bl->y*map[bl->m].xs].cell_bl--;
  229. }
  230. #endif
  231. /*==========================================
  232. * Adds a block to the map.
  233. * Returns 0 on success, 1 on failure (illegal coordinates).
  234. *------------------------------------------*/
  235. int map_addblock(struct block_list* bl)
  236. {
  237. int16 m, x, y;
  238. int pos;
  239. nullpo_ret(bl);
  240. if (bl->prev != NULL) {
  241. ShowError("map_addblock: bl->prev != NULL\n");
  242. return 1;
  243. }
  244. m = bl->m;
  245. x = bl->x;
  246. y = bl->y;
  247. if( m < 0 || m >= map_num )
  248. {
  249. ShowError("map_addblock: invalid map id (%d), only %d are loaded.\n", m, map_num);
  250. return 1;
  251. }
  252. if( x < 0 || x >= map[m].xs || y < 0 || y >= map[m].ys )
  253. {
  254. ShowError("map_addblock: out-of-bounds coordinates (\"%s\",%d,%d), map is %dx%d\n", map[m].name, x, y, map[m].xs, map[m].ys);
  255. return 1;
  256. }
  257. pos = x/BLOCK_SIZE+(y/BLOCK_SIZE)*map[m].bxs;
  258. if (bl->type == BL_MOB) {
  259. bl->next = map[m].block_mob[pos];
  260. bl->prev = &bl_head;
  261. if (bl->next) bl->next->prev = bl;
  262. map[m].block_mob[pos] = bl;
  263. } else {
  264. bl->next = map[m].block[pos];
  265. bl->prev = &bl_head;
  266. if (bl->next) bl->next->prev = bl;
  267. map[m].block[pos] = bl;
  268. }
  269. #ifdef CELL_NOSTACK
  270. map_addblcell(bl);
  271. #endif
  272. return 0;
  273. }
  274. /*==========================================
  275. * Removes a block from the map.
  276. *------------------------------------------*/
  277. int map_delblock(struct block_list* bl)
  278. {
  279. int pos;
  280. nullpo_ret(bl);
  281. // blocklist (2ways chainlist)
  282. if (bl->prev == NULL) {
  283. if (bl->next != NULL) {
  284. // can't delete block (already at the beginning of the chain)
  285. ShowError("map_delblock error : bl->next!=NULL\n");
  286. }
  287. return 0;
  288. }
  289. #ifdef CELL_NOSTACK
  290. map_delblcell(bl);
  291. #endif
  292. pos = bl->x/BLOCK_SIZE+(bl->y/BLOCK_SIZE)*map[bl->m].bxs;
  293. if (bl->next)
  294. bl->next->prev = bl->prev;
  295. if (bl->prev == &bl_head) {
  296. //Since the head of the list, update the block_list map of []
  297. if (bl->type == BL_MOB) {
  298. map[bl->m].block_mob[pos] = bl->next;
  299. } else {
  300. map[bl->m].block[pos] = bl->next;
  301. }
  302. } else {
  303. bl->prev->next = bl->next;
  304. }
  305. bl->next = NULL;
  306. bl->prev = NULL;
  307. return 0;
  308. }
  309. /**
  310. * Moves a block a x/y target position. [Skotlex]
  311. * Pass flag as 1 to prevent doing skill_unit_move checks
  312. * (which are executed by default on BL_CHAR types)
  313. * @param bl : block(object) to move
  314. * @param x1 : new x position
  315. * @param y1 : new y position
  316. * @param tick : when this was scheduled
  317. * @return 0:success, 1:fail
  318. */
  319. int map_moveblock(struct block_list *bl, int x1, int y1, unsigned int tick)
  320. {
  321. int x0 = bl->x, y0 = bl->y;
  322. struct status_change *sc = NULL;
  323. int moveblock = ( x0/BLOCK_SIZE != x1/BLOCK_SIZE || y0/BLOCK_SIZE != y1/BLOCK_SIZE);
  324. if (!bl->prev) {
  325. //Block not in map, just update coordinates, but do naught else.
  326. bl->x = x1;
  327. bl->y = y1;
  328. return 0;
  329. }
  330. //TODO: Perhaps some outs of bounds checking should be placed here?
  331. if (bl->type&BL_CHAR) {
  332. sc = status_get_sc(bl);
  333. skill_unit_move(bl,tick,2);
  334. status_change_end(bl, SC_CLOSECONFINE, INVALID_TIMER);
  335. status_change_end(bl, SC_CLOSECONFINE2, INVALID_TIMER);
  336. status_change_end(bl, SC_TINDER_BREAKER, INVALID_TIMER);
  337. status_change_end(bl, SC_TINDER_BREAKER2, INVALID_TIMER);
  338. // status_change_end(bl, SC_BLADESTOP, INVALID_TIMER); //Won't stop when you are knocked away, go figure...
  339. status_change_end(bl, SC_TATAMIGAESHI, INVALID_TIMER);
  340. status_change_end(bl, SC_MAGICROD, INVALID_TIMER);
  341. if (sc->data[SC_PROPERTYWALK] &&
  342. sc->data[SC_PROPERTYWALK]->val3 >= skill_get_maxcount(sc->data[SC_PROPERTYWALK]->val1,sc->data[SC_PROPERTYWALK]->val2) )
  343. status_change_end(bl,SC_PROPERTYWALK,INVALID_TIMER);
  344. } else
  345. if (bl->type == BL_NPC)
  346. npc_unsetcells((TBL_NPC*)bl);
  347. if (moveblock) map_delblock(bl);
  348. #ifdef CELL_NOSTACK
  349. else map_delblcell(bl);
  350. #endif
  351. bl->x = x1;
  352. bl->y = y1;
  353. if (moveblock) {
  354. if(map_addblock(bl))
  355. return 1;
  356. }
  357. #ifdef CELL_NOSTACK
  358. else map_addblcell(bl);
  359. #endif
  360. if (bl->type&BL_CHAR) {
  361. skill_unit_move(bl,tick,3);
  362. if( bl->type == BL_PC && ((TBL_PC*)bl)->shadowform_id ) {//Shadow Form Target Moving
  363. struct block_list *d_bl;
  364. if( (d_bl = map_id2bl(((TBL_PC*)bl)->shadowform_id)) == NULL || !check_distance_bl(bl,d_bl,10) ) {
  365. if( d_bl )
  366. status_change_end(d_bl,SC__SHADOWFORM,INVALID_TIMER);
  367. ((TBL_PC*)bl)->shadowform_id = 0;
  368. }
  369. }
  370. if (sc && sc->count) {
  371. if (sc->data[SC_DANCING])
  372. skill_unit_move_unit_group(skill_id2group(sc->data[SC_DANCING]->val2), bl->m, x1-x0, y1-y0);
  373. else {
  374. if (sc->data[SC_CLOAKING] && sc->data[SC_CLOAKING]->val1 < 3 && !skill_check_cloaking(bl, NULL))
  375. status_change_end(bl, SC_CLOAKING, INVALID_TIMER);
  376. if (sc->data[SC_WARM])
  377. skill_unit_move_unit_group(skill_id2group(sc->data[SC_WARM]->val4), bl->m, x1-x0, y1-y0);
  378. if (sc->data[SC_BANDING])
  379. skill_unit_move_unit_group(skill_id2group(sc->data[SC_BANDING]->val4), bl->m, x1-x0, y1-y0);
  380. if (sc->data[SC_NEUTRALBARRIER_MASTER])
  381. skill_unit_move_unit_group(skill_id2group(sc->data[SC_NEUTRALBARRIER_MASTER]->val2), bl->m, x1-x0, y1-y0);
  382. else if (sc->data[SC_STEALTHFIELD_MASTER])
  383. skill_unit_move_unit_group(skill_id2group(sc->data[SC_STEALTHFIELD_MASTER]->val2), bl->m, x1-x0, y1-y0);
  384. if( sc->data[SC__SHADOWFORM] ) {//Shadow Form Caster Moving
  385. struct block_list *d_bl;
  386. if( (d_bl = map_id2bl(sc->data[SC__SHADOWFORM]->val2)) == NULL || !check_distance_bl(bl,d_bl,10) )
  387. status_change_end(bl,SC__SHADOWFORM,INVALID_TIMER);
  388. }
  389. if (sc->data[SC_PROPERTYWALK]
  390. && sc->data[SC_PROPERTYWALK]->val3 < skill_get_maxcount(sc->data[SC_PROPERTYWALK]->val1,sc->data[SC_PROPERTYWALK]->val2)
  391. && map_find_skill_unit_oncell(bl,bl->x,bl->y,SO_ELECTRICWALK,NULL,0) == NULL
  392. && map_find_skill_unit_oncell(bl,bl->x,bl->y,SO_FIREWALK,NULL,0) == NULL
  393. && skill_unitsetting(bl,sc->data[SC_PROPERTYWALK]->val1,sc->data[SC_PROPERTYWALK]->val2,x0, y0,0)) {
  394. sc->data[SC_PROPERTYWALK]->val3++;
  395. }
  396. }
  397. /* Guild Aura Moving */
  398. if( bl->type == BL_PC && ((TBL_PC*)bl)->state.gmaster_flag ) {
  399. if (sc->data[SC_LEADERSHIP])
  400. skill_unit_move_unit_group(skill_id2group(sc->data[SC_LEADERSHIP]->val4), bl->m, x1-x0, y1-y0);
  401. if (sc->data[SC_GLORYWOUNDS])
  402. skill_unit_move_unit_group(skill_id2group(sc->data[SC_GLORYWOUNDS]->val4), bl->m, x1-x0, y1-y0);
  403. if (sc->data[SC_SOULCOLD])
  404. skill_unit_move_unit_group(skill_id2group(sc->data[SC_SOULCOLD]->val4), bl->m, x1-x0, y1-y0);
  405. if (sc->data[SC_HAWKEYES])
  406. skill_unit_move_unit_group(skill_id2group(sc->data[SC_HAWKEYES]->val4), bl->m, x1-x0, y1-y0);
  407. }
  408. }
  409. } else
  410. if (bl->type == BL_NPC)
  411. npc_setcells((TBL_NPC*)bl);
  412. return 0;
  413. }
  414. /*==========================================
  415. * Counts specified number of objects on given cell.
  416. * flag:
  417. * 0x1 - only count standing units
  418. *------------------------------------------*/
  419. int map_count_oncell(int16 m, int16 x, int16 y, int type, int flag)
  420. {
  421. int bx,by;
  422. struct block_list *bl;
  423. int count = 0;
  424. if (x < 0 || y < 0 || (x >= map[m].xs) || (y >= map[m].ys))
  425. return 0;
  426. bx = x/BLOCK_SIZE;
  427. by = y/BLOCK_SIZE;
  428. if (type&~BL_MOB)
  429. for( bl = map[m].block[bx+by*map[m].bxs] ; bl != NULL ; bl = bl->next )
  430. if(bl->x == x && bl->y == y && bl->type&type) {
  431. if(flag&1) {
  432. struct unit_data *ud = unit_bl2ud(bl);
  433. if(!ud || ud->walktimer == INVALID_TIMER)
  434. count++;
  435. } else {
  436. count++;
  437. }
  438. }
  439. if (type&BL_MOB)
  440. for( bl = map[m].block_mob[bx+by*map[m].bxs] ; bl != NULL ; bl = bl->next )
  441. if(bl->x == x && bl->y == y) {
  442. if(flag&1) {
  443. struct unit_data *ud = unit_bl2ud(bl);
  444. if(!ud || ud->walktimer == INVALID_TIMER)
  445. count++;
  446. } else {
  447. count++;
  448. }
  449. }
  450. return count;
  451. }
  452. /*
  453. * Looks for a skill unit on a given cell
  454. * flag&1: runs battle_check_target check based on unit->group->target_flag
  455. */
  456. struct skill_unit* map_find_skill_unit_oncell(struct block_list* target,int16 x,int16 y,uint16 skill_id,struct skill_unit* out_unit, int flag) {
  457. int16 m,bx,by;
  458. struct block_list *bl;
  459. struct skill_unit *unit;
  460. m = target->m;
  461. if (x < 0 || y < 0 || (x >= map[m].xs) || (y >= map[m].ys))
  462. return NULL;
  463. bx = x/BLOCK_SIZE;
  464. by = y/BLOCK_SIZE;
  465. for( bl = map[m].block[bx+by*map[m].bxs] ; bl != NULL ; bl = bl->next )
  466. {
  467. if (bl->x != x || bl->y != y || bl->type != BL_SKILL)
  468. continue;
  469. unit = (struct skill_unit *) bl;
  470. if( unit == out_unit || !unit->alive || !unit->group || unit->group->skill_id != skill_id )
  471. continue;
  472. if( !(flag&1) || battle_check_target(&unit->bl,target,unit->group->target_flag) > 0 )
  473. return unit;
  474. }
  475. return NULL;
  476. }
  477. /*==========================================
  478. * Adapted from foreachinarea for an easier invocation. [Skotlex]
  479. *------------------------------------------*/
  480. int map_foreachinrange(int (*func)(struct block_list*,va_list), struct block_list* center, int16 range, int type, ...)
  481. {
  482. int bx, by, m;
  483. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  484. struct block_list *bl;
  485. int blockcount = bl_list_count, i;
  486. int x0, x1, y0, y1;
  487. va_list ap;
  488. m = center->m;
  489. x0 = max(center->x - range, 0);
  490. y0 = max(center->y - range, 0);
  491. x1 = min(center->x + range, map[ m ].xs - 1);
  492. y1 = min(center->y + range, map[ m ].ys - 1);
  493. if ( type&~BL_MOB )
  494. for ( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ ) {
  495. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ ) {
  496. for( bl = map[m].block[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  497. if( bl->type&type
  498. && bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1
  499. #ifdef CIRCULAR_AREA
  500. && check_distance_bl(center, bl, range)
  501. #endif
  502. && bl_list_count < BL_LIST_MAX )
  503. bl_list[ bl_list_count++ ] = bl;
  504. }
  505. }
  506. }
  507. if( type&BL_MOB )
  508. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ ) {
  509. for(bx=x0/BLOCK_SIZE;bx<=x1/BLOCK_SIZE;bx++) {
  510. for( bl = map[ m ].block_mob[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  511. if( bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1
  512. #ifdef CIRCULAR_AREA
  513. && check_distance_bl(center, bl, range)
  514. #endif
  515. && bl_list_count < BL_LIST_MAX )
  516. bl_list[ bl_list_count++ ] = bl;
  517. }
  518. }
  519. }
  520. if( bl_list_count >= BL_LIST_MAX )
  521. ShowWarning("map_foreachinrange: block count too many!\n");
  522. map_freeblock_lock();
  523. for( i = blockcount; i < bl_list_count; i++ )
  524. if( bl_list[ i ]->prev ) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  525. va_start(ap, type);
  526. returnCount += func(bl_list[ i ], ap);
  527. va_end(ap);
  528. }
  529. map_freeblock_unlock();
  530. bl_list_count = blockcount;
  531. return returnCount; //[Skotlex]
  532. }
  533. /*==========================================
  534. * Same as foreachinrange, but there must be a shoot-able range between center and target to be counted in. [Skotlex]
  535. *------------------------------------------*/
  536. int map_foreachinshootrange(int (*func)(struct block_list*,va_list),struct block_list* center, int16 range, int type,...)
  537. {
  538. int bx, by, m;
  539. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  540. struct block_list *bl;
  541. int blockcount = bl_list_count, i;
  542. int x0, x1, y0, y1;
  543. va_list ap;
  544. m = center->m;
  545. if ( m < 0 )
  546. return 0;
  547. x0 = max(center->x-range, 0);
  548. y0 = max(center->y-range, 0);
  549. x1 = min(center->x+range, map[m].xs-1);
  550. y1 = min(center->y+range, map[m].ys-1);
  551. if ( type&~BL_MOB )
  552. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ ) {
  553. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ ) {
  554. for( bl = map[ m ].block[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  555. if( bl->type&type
  556. && bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1
  557. #ifdef CIRCULAR_AREA
  558. && check_distance_bl(center, bl, range)
  559. #endif
  560. && path_search_long(NULL, center->m, center->x, center->y, bl->x, bl->y, CELL_CHKWALL)
  561. && bl_list_count < BL_LIST_MAX )
  562. bl_list[ bl_list_count++ ] = bl;
  563. }
  564. }
  565. }
  566. if( type&BL_MOB )
  567. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ ) {
  568. for( bx=x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ ) {
  569. for( bl = map[ m ].block_mob[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  570. if( bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1
  571. #ifdef CIRCULAR_AREA
  572. && check_distance_bl(center, bl, range)
  573. #endif
  574. && path_search_long(NULL, center->m, center->x, center->y, bl->x, bl->y, CELL_CHKWALL)
  575. && bl_list_count < BL_LIST_MAX )
  576. bl_list[ bl_list_count++ ] = bl;
  577. }
  578. }
  579. }
  580. if( bl_list_count >= BL_LIST_MAX )
  581. ShowWarning("map_foreachinrange: block count too many!\n");
  582. map_freeblock_lock();
  583. for( i = blockcount; i < bl_list_count; i++ )
  584. if( bl_list[ i ]->prev ) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  585. va_start(ap, type);
  586. returnCount += func(bl_list[ i ], ap);
  587. va_end(ap);
  588. }
  589. map_freeblock_unlock();
  590. bl_list_count = blockcount;
  591. return returnCount; //[Skotlex]
  592. }
  593. /*==========================================
  594. * range = map m (x0,y0)-(x1,y1)
  595. * Apply *func with ... arguments for the range.
  596. * @type = BL_PC/BL_MOB etc..
  597. *------------------------------------------*/
  598. int map_foreachinarea(int (*func)(struct block_list*,va_list), int16 m, int16 x0, int16 y0, int16 x1, int16 y1, int type, ...)
  599. {
  600. int bx, by;
  601. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  602. struct block_list *bl;
  603. int blockcount = bl_list_count, i;
  604. va_list ap;
  605. if ( m < 0 || m >= map_num)
  606. return 0;
  607. if ( x1 < x0 )
  608. swap(x0, x1);
  609. if ( y1 < y0 )
  610. swap(y0, y1);
  611. x0 = max(x0, 0);
  612. y0 = max(y0, 0);
  613. x1 = min(x1, map[ m ].xs - 1);
  614. y1 = min(y1, map[ m ].ys - 1);
  615. if ( type&~BL_MOB )
  616. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ )
  617. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ )
  618. for( bl = map[ m ].block[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next )
  619. if( bl->type&type && bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1 && bl_list_count < BL_LIST_MAX )
  620. bl_list[ bl_list_count++ ] = bl;
  621. if( type&BL_MOB )
  622. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ )
  623. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ )
  624. for( bl = map[ m ].block_mob[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next )
  625. if( bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1 && bl_list_count < BL_LIST_MAX )
  626. bl_list[ bl_list_count++ ] = bl;
  627. if( bl_list_count >= BL_LIST_MAX )
  628. ShowWarning("map_foreachinarea: block count too many!\n");
  629. map_freeblock_lock();
  630. for( i = blockcount; i < bl_list_count; i++ )
  631. if( bl_list[ i ]->prev ) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  632. va_start(ap, type);
  633. returnCount += func(bl_list[ i ], ap);
  634. va_end(ap);
  635. }
  636. map_freeblock_unlock();
  637. bl_list_count = blockcount;
  638. return returnCount; //[Skotlex]
  639. }
  640. /*==========================================
  641. * Adapted from forcountinarea for an easier invocation. [pakpil]
  642. *------------------------------------------*/
  643. int map_forcountinrange(int (*func)(struct block_list*,va_list), struct block_list* center, int16 range, int count, int type, ...)
  644. {
  645. int bx, by, m;
  646. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  647. struct block_list *bl;
  648. int blockcount = bl_list_count, i;
  649. int x0, x1, y0, y1;
  650. va_list ap;
  651. m = center->m;
  652. x0 = max(center->x - range, 0);
  653. y0 = max(center->y - range, 0);
  654. x1 = min(center->x + range, map[ m ].xs - 1);
  655. y1 = min(center->y + range, map[ m ].ys - 1);
  656. if ( type&~BL_MOB )
  657. for ( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ ) {
  658. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ ) {
  659. for( bl = map[ m ].block[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  660. if( bl->type&type
  661. && bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1
  662. #ifdef CIRCULAR_AREA
  663. && check_distance_bl(center, bl, range)
  664. #endif
  665. && bl_list_count < BL_LIST_MAX )
  666. bl_list[ bl_list_count++ ] = bl;
  667. }
  668. }
  669. }
  670. if( type&BL_MOB )
  671. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ ) {
  672. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ ){
  673. for( bl = map[ m ].block_mob[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  674. if( bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1
  675. #ifdef CIRCULAR_AREA
  676. && check_distance_bl(center, bl, range)
  677. #endif
  678. && bl_list_count < BL_LIST_MAX )
  679. bl_list[ bl_list_count++ ] = bl;
  680. }
  681. }
  682. }
  683. if( bl_list_count >= BL_LIST_MAX )
  684. ShowWarning("map_forcountinrange: block count too many!\n");
  685. map_freeblock_lock();
  686. for( i = blockcount; i < bl_list_count; i++ )
  687. if( bl_list[ i ]->prev ) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  688. va_start(ap, type);
  689. returnCount += func(bl_list[ i ], ap);
  690. va_end(ap);
  691. if( count && returnCount >= count )
  692. break;
  693. }
  694. map_freeblock_unlock();
  695. bl_list_count = blockcount;
  696. return returnCount; //[Skotlex]
  697. }
  698. int map_forcountinarea(int (*func)(struct block_list*,va_list), int16 m, int16 x0, int16 y0, int16 x1, int16 y1, int count, int type, ...)
  699. {
  700. int bx, by;
  701. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  702. struct block_list *bl;
  703. int blockcount = bl_list_count, i;
  704. va_list ap;
  705. if ( m < 0 )
  706. return 0;
  707. if ( x1 < x0 )
  708. swap(x0, x1);
  709. if ( y1 < y0 )
  710. swap(y0, y1);
  711. x0 = max(x0, 0);
  712. y0 = max(y0, 0);
  713. x1 = min(x1, map[ m ].xs - 1);
  714. y1 = min(y1, map[ m ].ys - 1);
  715. if ( type&~BL_MOB )
  716. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ )
  717. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ )
  718. for( bl = map[ m ].block[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next )
  719. if( bl->type&type && bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1 && bl_list_count < BL_LIST_MAX )
  720. bl_list[ bl_list_count++ ] = bl;
  721. if( type&BL_MOB )
  722. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ )
  723. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ )
  724. for( bl = map[ m ].block_mob[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next )
  725. if( bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1 && bl_list_count < BL_LIST_MAX )
  726. bl_list[ bl_list_count++ ] = bl;
  727. if( bl_list_count >= BL_LIST_MAX )
  728. ShowWarning("map_foreachinarea: block count too many!\n");
  729. map_freeblock_lock();
  730. for( i = blockcount; i < bl_list_count; i++ )
  731. if(bl_list[ i ]->prev) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  732. va_start(ap, type);
  733. returnCount += func(bl_list[ i ], ap);
  734. va_end(ap);
  735. if( count && returnCount >= count )
  736. break;
  737. }
  738. map_freeblock_unlock();
  739. bl_list_count = blockcount;
  740. return returnCount; //[Skotlex]
  741. }
  742. /*==========================================
  743. * Move bl and do func* with va_list while moving.
  744. * Movement is set by dx dy which are distance in x and y
  745. *------------------------------------------*/
  746. int map_foreachinmovearea(int (*func)(struct block_list*,va_list), struct block_list* center, int16 range, int16 dx, int16 dy, int type, ...)
  747. {
  748. int bx, by, m;
  749. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  750. struct block_list *bl;
  751. int blockcount = bl_list_count, i;
  752. int x0, x1, y0, y1;
  753. va_list ap;
  754. if ( !range ) return 0;
  755. if ( !dx && !dy ) return 0; //No movement.
  756. m = center->m;
  757. x0 = center->x - range;
  758. x1 = center->x + range;
  759. y0 = center->y - range;
  760. y1 = center->y + range;
  761. if ( x1 < x0 )
  762. swap(x0, x1);
  763. if ( y1 < y0 )
  764. swap(y0, y1);
  765. if( dx == 0 || dy == 0 ) {
  766. //Movement along one axis only.
  767. if( dx == 0 ){
  768. if( dy < 0 ) //Moving south
  769. y0 = y1 + dy + 1;
  770. else //North
  771. y1 = y0 + dy - 1;
  772. } else { //dy == 0
  773. if( dx < 0 ) //West
  774. x0 = x1 + dx + 1;
  775. else //East
  776. x1 = x0 + dx - 1;
  777. }
  778. x0 = max(x0, 0);
  779. y0 = max(y0, 0);
  780. x1 = min(x1, map[ m ].xs - 1);
  781. y1 = min(y1, map[ m ].ys - 1);
  782. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ ) {
  783. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ ) {
  784. if ( type&~BL_MOB ) {
  785. for( bl = map[m].block[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  786. if( bl->type&type &&
  787. bl->x >= x0 && bl->x <= x1 &&
  788. bl->y >= y0 && bl->y <= y1 &&
  789. bl_list_count < BL_LIST_MAX )
  790. bl_list[ bl_list_count++ ] = bl;
  791. }
  792. }
  793. if ( type&BL_MOB ) {
  794. for( bl = map[ m ].block_mob[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  795. if( bl->x >= x0 && bl->x <= x1 &&
  796. bl->y >= y0 && bl->y <= y1 &&
  797. bl_list_count < BL_LIST_MAX )
  798. bl_list[ bl_list_count++ ] = bl;
  799. }
  800. }
  801. }
  802. }
  803. } else { // Diagonal movement
  804. x0 = max(x0, 0);
  805. y0 = max(y0, 0);
  806. x1 = min(x1, map[ m ].xs - 1);
  807. y1 = min(y1, map[ m ].ys - 1);
  808. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ ) {
  809. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ ) {
  810. if ( type & ~BL_MOB ) {
  811. for( bl = map[ m ].block[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  812. if( bl->type&type &&
  813. bl->x >= x0 && bl->x <= x1 &&
  814. bl->y >= y0 && bl->y <= y1 &&
  815. bl_list_count < BL_LIST_MAX )
  816. if( ( dx > 0 && bl->x < x0 + dx) ||
  817. ( dx < 0 && bl->x > x1 + dx) ||
  818. ( dy > 0 && bl->y < y0 + dy) ||
  819. ( dy < 0 && bl->y > y1 + dy) )
  820. bl_list[ bl_list_count++ ] = bl;
  821. }
  822. }
  823. if ( type&BL_MOB ) {
  824. for( bl = map[ m ].block_mob[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  825. if( bl->x >= x0 && bl->x <= x1 &&
  826. bl->y >= y0 && bl->y <= y1 &&
  827. bl_list_count < BL_LIST_MAX)
  828. if( ( dx > 0 && bl->x < x0 + dx) ||
  829. ( dx < 0 && bl->x > x1 + dx) ||
  830. ( dy > 0 && bl->y < y0 + dy) ||
  831. ( dy < 0 && bl->y > y1 + dy) )
  832. bl_list[ bl_list_count++ ] = bl;
  833. }
  834. }
  835. }
  836. }
  837. }
  838. if( bl_list_count >= BL_LIST_MAX )
  839. ShowWarning("map_foreachinmovearea: block count too many!\n");
  840. map_freeblock_lock(); // Prohibit the release from memory
  841. for( i = blockcount; i < bl_list_count; i++ )
  842. if( bl_list[ i ]->prev ) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  843. va_start(ap, type);
  844. returnCount += func(bl_list[ i ], ap);
  845. va_end(ap);
  846. }
  847. map_freeblock_unlock(); // Allow Free
  848. bl_list_count = blockcount;
  849. return returnCount;
  850. }
  851. // -- moonsoul (added map_foreachincell which is a rework of map_foreachinarea but
  852. // which only checks the exact single x/y passed to it rather than an
  853. // area radius - may be more useful in some instances)
  854. //
  855. int map_foreachincell(int (*func)(struct block_list*,va_list), int16 m, int16 x, int16 y, int type, ...)
  856. {
  857. int bx, by;
  858. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  859. struct block_list *bl;
  860. int blockcount = bl_list_count, i;
  861. va_list ap;
  862. if ( x < 0 || y < 0 || x >= map[ m ].xs || y >= map[ m ].ys ) return 0;
  863. by = y / BLOCK_SIZE;
  864. bx = x / BLOCK_SIZE;
  865. if( type&~BL_MOB )
  866. for( bl = map[ m ].block[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next )
  867. if( bl->type&type && bl->x == x && bl->y == y && bl_list_count < BL_LIST_MAX )
  868. bl_list[ bl_list_count++ ] = bl;
  869. if( type&BL_MOB )
  870. for( bl = map[ m ].block_mob[ bx + by * map[ m ].bxs]; bl != NULL; bl = bl->next )
  871. if( bl->x == x && bl->y == y && bl_list_count < BL_LIST_MAX)
  872. bl_list[ bl_list_count++ ] = bl;
  873. if( bl_list_count >= BL_LIST_MAX )
  874. ShowWarning("map_foreachincell: block count too many!\n");
  875. map_freeblock_lock();
  876. for( i = blockcount; i < bl_list_count; i++ )
  877. if( bl_list[ i ]->prev ) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  878. va_start(ap, type);
  879. returnCount += func(bl_list[ i ], ap);
  880. va_end(ap);
  881. }
  882. map_freeblock_unlock();
  883. bl_list_count = blockcount;
  884. return returnCount;
  885. }
  886. /*============================================================
  887. * For checking a path between two points (x0, y0) and (x1, y1)
  888. *------------------------------------------------------------*/
  889. int map_foreachinpath(int (*func)(struct block_list*,va_list),int16 m,int16 x0,int16 y0,int16 x1,int16 y1,int16 range,int length, int type,...)
  890. {
  891. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  892. //////////////////////////////////////////////////////////////
  893. //
  894. // sharp shooting 3 [Skotlex]
  895. //
  896. //////////////////////////////////////////////////////////////
  897. // problem:
  898. // Same as Sharp Shooting 1. Hits all targets within range of
  899. // the line.
  900. // (t1,t2 t3 and t4 get hit)
  901. //
  902. // target 1
  903. // x t4
  904. // t2
  905. // t3 x
  906. // x
  907. // S
  908. //////////////////////////////////////////////////////////////
  909. // Methodology:
  910. // My trigonometrics and math are a little rusty... so the approach I am writing
  911. // here is basically do a double for to check for all targets in the square that
  912. // contains the initial and final positions (area range increased to match the
  913. // radius given), then for each object to test, calculate the distance to the
  914. // path and include it if the range fits and the target is in the line (0<k<1,
  915. // as they call it).
  916. // The implementation I took as reference is found at
  917. // http://astronomy.swin.edu.au/~pbourke/geometry/pointline/
  918. // (they have a link to a C implementation, too)
  919. // This approach is a lot like #2 commented on this function, which I have no
  920. // idea why it was commented. I won't use doubles/floats, but pure int math for
  921. // speed purposes. The range considered is always the same no matter how
  922. // close/far the target is because that's how SharpShooting works currently in
  923. // kRO.
  924. //Generic map_foreach* variables.
  925. int i, blockcount = bl_list_count;
  926. struct block_list *bl;
  927. int bx, by;
  928. //method specific variables
  929. int magnitude2, len_limit; //The square of the magnitude
  930. int k, xi, yi, xu, yu;
  931. int mx0 = x0, mx1 = x1, my0 = y0, my1 = y1;
  932. va_list ap;
  933. //Avoid needless calculations by not getting the sqrt right away.
  934. #define MAGNITUDE2(x0, y0, x1, y1) ( ( ( x1 ) - ( x0 ) ) * ( ( x1 ) - ( x0 ) ) + ( ( y1 ) - ( y0 ) ) * ( ( y1 ) - ( y0 ) ) )
  935. if ( m < 0 )
  936. return 0;
  937. len_limit = magnitude2 = MAGNITUDE2(x0, y0, x1, y1);
  938. if ( magnitude2 < 1 ) //Same begin and ending point, can't trace path.
  939. return 0;
  940. if ( length ) { //Adjust final position to fit in the given area.
  941. //TODO: Find an alternate method which does not requires a square root calculation.
  942. k = (int)sqrt((float)magnitude2);
  943. mx1 = x0 + (x1 - x0) * length / k;
  944. my1 = y0 + (y1 - y0) * length / k;
  945. len_limit = MAGNITUDE2(x0, y0, mx1, my1);
  946. }
  947. //Expand target area to cover range.
  948. if ( mx0 > mx1 ) {
  949. mx0 += range;
  950. mx1 -= range;
  951. } else {
  952. mx0 -= range;
  953. mx1 += range;
  954. }
  955. if (my0 > my1) {
  956. my0 += range;
  957. my1 -= range;
  958. } else {
  959. my0 -= range;
  960. my1 += range;
  961. }
  962. //The two fors assume mx0 < mx1 && my0 < my1
  963. if ( mx0 > mx1 )
  964. swap(mx0, mx1);
  965. if ( my0 > my1 )
  966. swap(my0, my1);
  967. mx0 = max(mx0, 0);
  968. my0 = max(my0, 0);
  969. mx1 = min(mx1, map[ m ].xs - 1);
  970. my1 = min(my1, map[ m ].ys - 1);
  971. range *= range << 8; //Values are shifted later on for higher precision using int math.
  972. if ( type&~BL_MOB )
  973. for ( by = my0 / BLOCK_SIZE; by <= my1 / BLOCK_SIZE; by++ ) {
  974. for( bx = mx0 / BLOCK_SIZE; bx <= mx1 / BLOCK_SIZE; bx++ ) {
  975. for( bl = map[ m ].block[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  976. if( bl->prev && bl->type&type && bl_list_count < BL_LIST_MAX ) {
  977. xi = bl->x;
  978. yi = bl->y;
  979. k = ( xi - x0 ) * ( x1 - x0 ) + ( yi - y0 ) * ( y1 - y0 );
  980. if ( k < 0 || k > len_limit ) //Since more skills use this, check for ending point as well.
  981. continue;
  982. if ( k > magnitude2 && !path_search_long(NULL, m, x0, y0, xi, yi, CELL_CHKWALL) )
  983. continue; //Targets beyond the initial ending point need the wall check.
  984. //All these shifts are to increase the precision of the intersection point and distance considering how it's
  985. //int math.
  986. k = ( k << 4 ) / magnitude2; //k will be between 1~16 instead of 0~1
  987. xi <<= 4;
  988. yi <<= 4;
  989. xu = ( x0 << 4 ) + k * ( x1 - x0 );
  990. yu = ( y0 << 4 ) + k * ( y1 - y0 );
  991. k = MAGNITUDE2(xi, yi, xu, yu);
  992. //If all dot coordinates were <<4 the square of the magnitude is <<8
  993. if ( k > range )
  994. continue;
  995. bl_list[ bl_list_count++ ] = bl;
  996. }
  997. }
  998. }
  999. }
  1000. if( type&BL_MOB )
  1001. for( by = my0 / BLOCK_SIZE; by <= my1 / BLOCK_SIZE; by++ ) {
  1002. for( bx = mx0 / BLOCK_SIZE; bx <= mx1 / BLOCK_SIZE; bx++ ) {
  1003. for( bl = map[ m ].block_mob[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  1004. if( bl->prev && bl_list_count < BL_LIST_MAX ) {
  1005. xi = bl->x;
  1006. yi = bl->y;
  1007. k = ( xi - x0 ) * ( x1 - x0 ) + ( yi - y0 ) * ( y1 - y0 );
  1008. if ( k < 0 || k > len_limit )
  1009. continue;
  1010. if ( k > magnitude2 && !path_search_long(NULL, m, x0, y0, xi, yi, CELL_CHKWALL) )
  1011. continue; //Targets beyond the initial ending point need the wall check.
  1012. k = ( k << 4 ) / magnitude2; //k will be between 1~16 instead of 0~1
  1013. xi <<= 4;
  1014. yi <<= 4;
  1015. xu = ( x0 << 4 ) + k * ( x1 - x0 );
  1016. yu = ( y0 << 4 ) + k * ( y1 - y0 );
  1017. k = MAGNITUDE2(xi, yi, xu, yu);
  1018. //If all dot coordinates were <<4 the square of the magnitude is <<8
  1019. if ( k > range )
  1020. continue;
  1021. bl_list[ bl_list_count++ ] = bl;
  1022. }
  1023. }
  1024. }
  1025. }
  1026. if( bl_list_count >= BL_LIST_MAX )
  1027. ShowWarning("map_foreachinpath: block count too many!\n");
  1028. map_freeblock_lock();
  1029. for( i = blockcount; i < bl_list_count; i++ )
  1030. if( bl_list[ i ]->prev ) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  1031. va_start(ap, type);
  1032. returnCount += func(bl_list[ i ], ap);
  1033. va_end(ap);
  1034. }
  1035. map_freeblock_unlock();
  1036. bl_list_count = blockcount;
  1037. return returnCount; //[Skotlex]
  1038. }
  1039. // Copy of map_foreachincell, but applied to the whole map. [Skotlex]
  1040. int map_foreachinmap(int (*func)(struct block_list*,va_list), int16 m, int type,...)
  1041. {
  1042. int b, bsize;
  1043. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  1044. struct block_list *bl;
  1045. int blockcount = bl_list_count, i;
  1046. va_list ap;
  1047. bsize = map[ m ].bxs * map[ m ].bys;
  1048. if( type&~BL_MOB )
  1049. for( b = 0; b < bsize; b++ )
  1050. for( bl = map[ m ].block[ b ]; bl != NULL; bl = bl->next )
  1051. if( bl->type&type && bl_list_count < BL_LIST_MAX )
  1052. bl_list[ bl_list_count++ ] = bl;
  1053. if( type&BL_MOB )
  1054. for( b = 0; b < bsize; b++ )
  1055. for( bl = map[ m ].block_mob[ b ]; bl != NULL; bl = bl->next )
  1056. if( bl_list_count < BL_LIST_MAX )
  1057. bl_list[ bl_list_count++ ] = bl;
  1058. if( bl_list_count >= BL_LIST_MAX )
  1059. ShowWarning("map_foreachinmap: block count too many!\n");
  1060. map_freeblock_lock();
  1061. for( i = blockcount; i < bl_list_count ; i++ )
  1062. if( bl_list[ i ]->prev ) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  1063. va_start(ap, type);
  1064. returnCount += func(bl_list[ i ], ap);
  1065. va_end(ap);
  1066. }
  1067. map_freeblock_unlock();
  1068. bl_list_count = blockcount;
  1069. return returnCount;
  1070. }
  1071. /// Generates a new flooritem object id from the interval [MIN_FLOORITEM, MAX_FLOORITEM).
  1072. /// Used for floor items, skill units and chatroom objects.
  1073. /// @return The new object id
  1074. int map_get_new_object_id(void)
  1075. {
  1076. static int last_object_id = MIN_FLOORITEM - 1;
  1077. int i;
  1078. // find a free id
  1079. i = last_object_id + 1;
  1080. while( i != last_object_id ) {
  1081. if( i == MAX_FLOORITEM )
  1082. i = MIN_FLOORITEM;
  1083. if( !idb_exists(id_db, i) )
  1084. break;
  1085. ++i;
  1086. }
  1087. if( i == last_object_id ) {
  1088. ShowError("map_addobject: no free object id!\n");
  1089. return 0;
  1090. }
  1091. // update cursor
  1092. last_object_id = i;
  1093. return i;
  1094. }
  1095. /*==========================================
  1096. * Timered function to clear the floor (remove remaining item)
  1097. * Called each flooritem_lifetime ms
  1098. *------------------------------------------*/
  1099. int map_clearflooritem_timer(int tid, unsigned int tick, int id, intptr_t data)
  1100. {
  1101. struct flooritem_data* fitem = (struct flooritem_data*)idb_get(id_db, id);
  1102. if (fitem == NULL || fitem->bl.type != BL_ITEM || (fitem->cleartimer != tid)) {
  1103. ShowError("map_clearflooritem_timer : error\n");
  1104. return 1;
  1105. }
  1106. if (search_petDB_index(fitem->item.nameid, PET_EGG) >= 0)
  1107. intif_delete_petdata(MakeDWord(fitem->item.card[1], fitem->item.card[2]));
  1108. clif_clearflooritem(fitem, 0);
  1109. map_deliddb(&fitem->bl);
  1110. map_delblock(&fitem->bl);
  1111. map_freeblock(&fitem->bl);
  1112. return 0;
  1113. }
  1114. /*
  1115. * clears a single bl item out of the map.
  1116. */
  1117. void map_clearflooritem(struct block_list *bl) {
  1118. struct flooritem_data* fitem = (struct flooritem_data*)bl;
  1119. if( fitem->cleartimer )
  1120. delete_timer(fitem->cleartimer,map_clearflooritem_timer);
  1121. clif_clearflooritem(fitem, 0);
  1122. map_deliddb(&fitem->bl);
  1123. map_delblock(&fitem->bl);
  1124. map_freeblock(&fitem->bl);
  1125. }
  1126. /*==========================================
  1127. * (m,x,y) locates a random available free cell around the given coordinates
  1128. * to place an BL_ITEM object. Scan area is 9x9, returns 1 on success.
  1129. * x and y are modified with the target cell when successful.
  1130. *------------------------------------------*/
  1131. int map_searchrandfreecell(int16 m,int16 *x,int16 *y,int stack) {
  1132. int free_cell,i,j;
  1133. int free_cells[9][2];
  1134. for(free_cell=0,i=-1;i<=1;i++){
  1135. if(i+*y<0 || i+*y>=map[m].ys)
  1136. continue;
  1137. for(j=-1;j<=1;j++){
  1138. if(j+*x<0 || j+*x>=map[m].xs)
  1139. continue;
  1140. if(map_getcell(m,j+*x,i+*y,CELL_CHKNOPASS) && !map_getcell(m,j+*x,i+*y,CELL_CHKICEWALL))
  1141. continue;
  1142. //Avoid item stacking to prevent against exploits. [Skotlex]
  1143. if(stack && map_count_oncell(m,j+*x,i+*y, BL_ITEM, 0) > stack)
  1144. continue;
  1145. free_cells[free_cell][0] = j+*x;
  1146. free_cells[free_cell++][1] = i+*y;
  1147. }
  1148. }
  1149. if(free_cell==0)
  1150. return 0;
  1151. free_cell = rnd()%free_cell;
  1152. *x = free_cells[free_cell][0];
  1153. *y = free_cells[free_cell][1];
  1154. return 1;
  1155. }
  1156. static int map_count_sub(struct block_list *bl,va_list ap)
  1157. {
  1158. return 1;
  1159. }
  1160. /*==========================================
  1161. * Locates a random spare cell around the object given, using range as max
  1162. * distance from that spot. Used for warping functions. Use range < 0 for
  1163. * whole map range.
  1164. * Returns 1 on success. when it fails and src is available, x/y are set to src's
  1165. * src can be null as long as flag&1
  1166. * when ~flag&1, m is not needed.
  1167. * Flag values:
  1168. * &1 = random cell must be around given m,x,y, not around src
  1169. * &2 = the target should be able to walk to the target tile.
  1170. * &4 = there shouldn't be any players around the target tile (use the no_spawn_on_player setting)
  1171. *------------------------------------------*/
  1172. int map_search_freecell(struct block_list *src, int16 m, int16 *x,int16 *y, int16 rx, int16 ry, int flag)
  1173. {
  1174. int tries, spawn=0;
  1175. int bx, by;
  1176. int rx2 = 2*rx+1;
  1177. int ry2 = 2*ry+1;
  1178. if( !src && (!(flag&1) || flag&2) )
  1179. {
  1180. ShowDebug("map_search_freecell: Incorrect usage! When src is NULL, flag has to be &1 and can't have &2\n");
  1181. return 0;
  1182. }
  1183. if (flag&1) {
  1184. bx = *x;
  1185. by = *y;
  1186. } else {
  1187. bx = src->x;
  1188. by = src->y;
  1189. m = src->m;
  1190. }
  1191. if (!rx && !ry) {
  1192. //No range? Return the target cell then....
  1193. *x = bx;
  1194. *y = by;
  1195. return map_getcell(m,*x,*y,CELL_CHKREACH);
  1196. }
  1197. if (rx >= 0 && ry >= 0) {
  1198. tries = rx2*ry2;
  1199. if (tries > 100) tries = 100;
  1200. } else {
  1201. tries = map[m].xs*map[m].ys;
  1202. if (tries > 500) tries = 500;
  1203. }
  1204. while(tries--) {
  1205. *x = (rx >= 0)?(rnd()%rx2-rx+bx):(rnd()%(map[m].xs-2)+1);
  1206. *y = (ry >= 0)?(rnd()%ry2-ry+by):(rnd()%(map[m].ys-2)+1);
  1207. if (*x == bx && *y == by)
  1208. continue; //Avoid picking the same target tile.
  1209. if (map_getcell(m,*x,*y,CELL_CHKREACH))
  1210. {
  1211. if(flag&2 && !unit_can_reach_pos(src, *x, *y, 1))
  1212. continue;
  1213. if(flag&4) {
  1214. if (spawn >= 100) return 0; //Limit of retries reached.
  1215. if (spawn++ < battle_config.no_spawn_on_player &&
  1216. map_foreachinarea(map_count_sub, m,
  1217. *x-AREA_SIZE, *y-AREA_SIZE,
  1218. *x+AREA_SIZE, *y+AREA_SIZE, BL_PC)
  1219. )
  1220. continue;
  1221. }
  1222. return 1;
  1223. }
  1224. }
  1225. *x = bx;
  1226. *y = by;
  1227. return 0;
  1228. }
  1229. /*==========================================
  1230. * Locates the closest, walkable cell with no blocks of a certain type on it
  1231. * Returns true on success and sets x and y to cell found.
  1232. * Otherwise returns false and x and y are not changed.
  1233. * type: Types of block to count
  1234. * flag:
  1235. * 0x1 - only count standing units
  1236. *------------------------------------------*/
  1237. bool map_closest_freecell(int16 m, int16 *x, int16 *y, int type, int flag)
  1238. {
  1239. uint8 dir = 6;
  1240. int16 tx = *x;
  1241. int16 ty = *y;
  1242. int costrange = 10;
  1243. if(!map_count_oncell(m, tx, ty, type, flag))
  1244. return true; //Current cell is free
  1245. //Algorithm only works up to costrange of 34
  1246. while(costrange <= 34) {
  1247. short dx = dirx[dir];
  1248. short dy = diry[dir];
  1249. //Linear search
  1250. if(dir%2 == 0 && costrange%MOVE_COST == 0) {
  1251. tx = *x+dx*(costrange/MOVE_COST);
  1252. ty = *y+dy*(costrange/MOVE_COST);
  1253. if(!map_count_oncell(m, tx, ty, type, flag) && map_getcell(m,tx,ty,CELL_CHKPASS)) {
  1254. *x = tx;
  1255. *y = ty;
  1256. return true;
  1257. }
  1258. }
  1259. //Full diagonal search
  1260. else if(dir%2 == 1 && costrange%MOVE_DIAGONAL_COST == 0) {
  1261. tx = *x+dx*(costrange/MOVE_DIAGONAL_COST);
  1262. ty = *y+dy*(costrange/MOVE_DIAGONAL_COST);
  1263. if(!map_count_oncell(m, tx, ty, type, flag) && map_getcell(m,tx,ty,CELL_CHKPASS)) {
  1264. *x = tx;
  1265. *y = ty;
  1266. return true;
  1267. }
  1268. }
  1269. //One cell diagonal, rest linear (TODO: Find a better algorithm for this)
  1270. else if(dir%2 == 1 && costrange%MOVE_COST == 4) {
  1271. tx = *x+dx*((dir%4==3)?(costrange/MOVE_COST):1);
  1272. ty = *y+dy*((dir%4==1)?(costrange/MOVE_COST):1);
  1273. if(!map_count_oncell(m, tx, ty, type, flag) && map_getcell(m,tx,ty,CELL_CHKPASS)) {
  1274. *x = tx;
  1275. *y = ty;
  1276. return true;
  1277. }
  1278. tx = *x+dx*((dir%4==1)?(costrange/MOVE_COST):1);
  1279. ty = *y+dy*((dir%4==3)?(costrange/MOVE_COST):1);
  1280. if(!map_count_oncell(m, tx, ty, type, flag) && map_getcell(m,tx,ty,CELL_CHKPASS)) {
  1281. *x = tx;
  1282. *y = ty;
  1283. return true;
  1284. }
  1285. }
  1286. //Get next direction
  1287. if (dir == 5) {
  1288. //Diagonal search complete, repeat with higher cost range
  1289. if(costrange == 14) costrange += 6;
  1290. else if(costrange == 28 || costrange >= 38) costrange += 2;
  1291. else costrange += 4;
  1292. dir = 6;
  1293. } else if (dir == 4) {
  1294. //Linear search complete, switch to diagonal directions
  1295. dir = 7;
  1296. } else {
  1297. dir = (dir+2)%8;
  1298. }
  1299. }
  1300. return false;
  1301. }
  1302. /*==========================================
  1303. * Add an item in floor to location (m,x,y) and add restriction for those who could pickup later
  1304. * NB : If charids are null their no restriction for pickup
  1305. * @param item_data : item attributes
  1306. * @param amount : items quantity
  1307. * @param m : mapid
  1308. * @param x : x coordinates
  1309. * @param y : y coordinates
  1310. * @param first_charid : 1st player that could loot the item (only charid that could loot for first_get_tick duration)
  1311. * @param second_charid : 2nd player that could loot the item (2nd charid that could loot for second_get_charid duration)
  1312. * @param third_charid : 3rd player that could loot the item (3rd charid that could loot for third_get_charid duration)
  1313. * @param flag: &1 MVP item. &2 do stacking check. &4 bypass droppable check.
  1314. * @return 0:failure, x:item_gid [MIN_FLOORITEM;MAX_FLOORITEM]==[2;START_ACCOUNT_NUM]
  1315. *------------------------------------------*/
  1316. int map_addflooritem(struct item *item,int amount,int16 m,int16 x,int16 y,int first_charid,int second_charid,int third_charid,int flags)
  1317. {
  1318. int r;
  1319. struct flooritem_data *fitem = NULL;
  1320. nullpo_ret(item);
  1321. if (!(flags&4) && battle_config.item_onfloor && (itemdb_traderight(item->nameid)&1))
  1322. return 0; //can't be dropped
  1323. if (!map_searchrandfreecell(m,&x,&y,flags&2?1:0))
  1324. return 0;
  1325. r = rnd();
  1326. CREATE(fitem, struct flooritem_data, 1);
  1327. fitem->bl.type=BL_ITEM;
  1328. fitem->bl.prev = fitem->bl.next = NULL;
  1329. fitem->bl.m=m;
  1330. fitem->bl.x=x;
  1331. fitem->bl.y=y;
  1332. fitem->bl.id = map_get_new_object_id();
  1333. if (fitem->bl.id==0) {
  1334. aFree(fitem);
  1335. return 0;
  1336. }
  1337. fitem->first_get_charid = first_charid;
  1338. fitem->first_get_tick = gettick() + (flags&1 ? battle_config.mvp_item_first_get_time : battle_config.item_first_get_time);
  1339. fitem->second_get_charid = second_charid;
  1340. fitem->second_get_tick = fitem->first_get_tick + (flags&1 ? battle_config.mvp_item_second_get_time : battle_config.item_second_get_time);
  1341. fitem->third_get_charid = third_charid;
  1342. fitem->third_get_tick = fitem->second_get_tick + (flags&1 ? battle_config.mvp_item_third_get_time : battle_config.item_third_get_time);
  1343. memcpy(&fitem->item,item,sizeof(*item));
  1344. fitem->item.amount = amount;
  1345. fitem->subx = (r&3)*3+3;
  1346. fitem->suby = ((r>>2)&3)*3+3;
  1347. fitem->cleartimer = add_timer(gettick()+battle_config.flooritem_lifetime,map_clearflooritem_timer,fitem->bl.id,0);
  1348. map_addiddb(&fitem->bl);
  1349. if (map_addblock(&fitem->bl))
  1350. return 0;
  1351. clif_dropflooritem(fitem);
  1352. return fitem->bl.id;
  1353. }
  1354. /**
  1355. * @see DBCreateData
  1356. */
  1357. static DBData create_charid2nick(DBKey key, va_list args)
  1358. {
  1359. struct charid2nick *p;
  1360. CREATE(p, struct charid2nick, 1);
  1361. return db_ptr2data(p);
  1362. }
  1363. /// Adds(or replaces) the nick of charid to nick_db and fulfils pending requests.
  1364. /// Does nothing if the character is online.
  1365. void map_addnickdb(int charid, const char* nick)
  1366. {
  1367. struct charid2nick* p;
  1368. if( map_charid2sd(charid) )
  1369. return;// already online
  1370. p = idb_ensure(nick_db, charid, create_charid2nick);
  1371. safestrncpy(p->nick, nick, sizeof(p->nick));
  1372. while( p->requests ) {
  1373. struct map_session_data* sd;
  1374. struct charid_request* req;
  1375. req = p->requests;
  1376. p->requests = req->next;
  1377. sd = map_charid2sd(req->charid);
  1378. if( sd )
  1379. clif_solved_charname(sd->fd, charid, p->nick);
  1380. aFree(req);
  1381. }
  1382. }
  1383. /// Removes the nick of charid from nick_db.
  1384. /// Sends name to all pending requests on charid.
  1385. void map_delnickdb(int charid, const char* name)
  1386. {
  1387. struct charid2nick* p;
  1388. DBData data;
  1389. if (!nick_db->remove(nick_db, db_i2key(charid), &data) || (p = db_data2ptr(&data)) == NULL)
  1390. return;
  1391. while( p->requests ) {
  1392. struct charid_request* req;
  1393. struct map_session_data* sd;
  1394. req = p->requests;
  1395. p->requests = req->next;
  1396. sd = map_charid2sd(req->charid);
  1397. if( sd )
  1398. clif_solved_charname(sd->fd, charid, name);
  1399. aFree(req);
  1400. }
  1401. aFree(p);
  1402. }
  1403. /// Notifies sd of the nick of charid.
  1404. /// Uses the name in the character if online.
  1405. /// Uses the name in nick_db if offline.
  1406. void map_reqnickdb(struct map_session_data * sd, int charid)
  1407. {
  1408. struct charid2nick* p;
  1409. struct charid_request* req;
  1410. struct map_session_data* tsd;
  1411. nullpo_retv(sd);
  1412. tsd = map_charid2sd(charid);
  1413. if( tsd )
  1414. {
  1415. clif_solved_charname(sd->fd, charid, tsd->status.name);
  1416. return;
  1417. }
  1418. p = idb_ensure(nick_db, charid, create_charid2nick);
  1419. if( *p->nick )
  1420. {
  1421. clif_solved_charname(sd->fd, charid, p->nick);
  1422. return;
  1423. }
  1424. // not in cache, request it
  1425. CREATE(req, struct charid_request, 1);
  1426. req->next = p->requests;
  1427. p->requests = req;
  1428. chrif_searchcharid(charid);
  1429. }
  1430. /*==========================================
  1431. * add bl to id_db
  1432. *------------------------------------------*/
  1433. void map_addiddb(struct block_list *bl)
  1434. {
  1435. nullpo_retv(bl);
  1436. if( bl->type == BL_PC )
  1437. {
  1438. TBL_PC* sd = (TBL_PC*)bl;
  1439. idb_put(pc_db,sd->bl.id,sd);
  1440. idb_put(charid_db,sd->status.char_id,sd);
  1441. }
  1442. else if( bl->type == BL_MOB )
  1443. {
  1444. TBL_MOB* md = (TBL_MOB*)bl;
  1445. idb_put(mobid_db,bl->id,bl);
  1446. if( md->state.boss )
  1447. idb_put(bossid_db, bl->id, bl);
  1448. }
  1449. if( bl->type & BL_REGEN )
  1450. idb_put(regen_db, bl->id, bl);
  1451. idb_put(id_db,bl->id,bl);
  1452. }
  1453. /*==========================================
  1454. * remove bl from id_db
  1455. *------------------------------------------*/
  1456. void map_deliddb(struct block_list *bl)
  1457. {
  1458. nullpo_retv(bl);
  1459. if( bl->type == BL_PC )
  1460. {
  1461. TBL_PC* sd = (TBL_PC*)bl;
  1462. idb_remove(pc_db,sd->bl.id);
  1463. idb_remove(charid_db,sd->status.char_id);
  1464. }
  1465. else if( bl->type == BL_MOB )
  1466. {
  1467. idb_remove(mobid_db,bl->id);
  1468. idb_remove(bossid_db,bl->id);
  1469. }
  1470. if( bl->type & BL_REGEN )
  1471. idb_remove(regen_db,bl->id);
  1472. idb_remove(id_db,bl->id);
  1473. }
  1474. /*==========================================
  1475. * Standard call when a player connection is closed.
  1476. *------------------------------------------*/
  1477. int map_quit(struct map_session_data *sd) {
  1478. int i;
  1479. if(!sd->state.active) { //Removing a player that is not active.
  1480. struct auth_node *node = chrif_search(sd->status.account_id);
  1481. if (node && node->char_id == sd->status.char_id &&
  1482. node->state != ST_LOGOUT)
  1483. //Except when logging out, clear the auth-connect data immediately.
  1484. chrif_auth_delete(node->account_id, node->char_id, node->state);
  1485. //Non-active players should not have loaded any data yet (or it was cleared already) so no additional cleanups are needed.
  1486. return 0;
  1487. }
  1488. if (sd->expiration_tid != INVALID_TIMER)
  1489. delete_timer(sd->expiration_tid, pc_expiration_timer);
  1490. if (sd->npc_timer_id != INVALID_TIMER) //Cancel the event timer.
  1491. npc_timerevent_quit(sd);
  1492. if (sd->autotrade_tid != INVALID_TIMER)
  1493. delete_timer(sd->autotrade_tid, pc_autotrade_timer);
  1494. if (sd->npc_id)
  1495. npc_event_dequeue(sd);
  1496. if( sd->bg_id )
  1497. bg_team_leave(sd,1);
  1498. pc_itemcd_do(sd,false);
  1499. npc_script_event(sd, NPCE_LOGOUT);
  1500. //Unit_free handles clearing the player related data,
  1501. //map_quit handles extra specific data which is related to quitting normally
  1502. //(changing map-servers invokes unit_free but bypasses map_quit)
  1503. if( sd->sc.count ) {
  1504. //Status that are not saved...
  1505. status_change_end(&sd->bl, SC_BOSSMAPINFO, INVALID_TIMER);
  1506. status_change_end(&sd->bl, SC_AUTOTRADE, INVALID_TIMER);
  1507. status_change_end(&sd->bl, SC_SPURT, INVALID_TIMER);
  1508. status_change_end(&sd->bl, SC_BERSERK, INVALID_TIMER);
  1509. status_change_end(&sd->bl, SC__BLOODYLUST, INVALID_TIMER);
  1510. status_change_end(&sd->bl, SC_TRICKDEAD, INVALID_TIMER);
  1511. status_change_end(&sd->bl, SC_LEADERSHIP, INVALID_TIMER);
  1512. status_change_end(&sd->bl, SC_GLORYWOUNDS, INVALID_TIMER);
  1513. status_change_end(&sd->bl, SC_SOULCOLD, INVALID_TIMER);
  1514. status_change_end(&sd->bl, SC_HAWKEYES, INVALID_TIMER);
  1515. status_change_end(&sd->bl, SC_CHASEWALK2, INVALID_TIMER);
  1516. if(sd->sc.data[SC_ENDURE] && sd->sc.data[SC_ENDURE]->val4)
  1517. status_change_end(&sd->bl, SC_ENDURE, INVALID_TIMER); //No need to save infinite endure.
  1518. status_change_end(&sd->bl, SC_WEIGHT50, INVALID_TIMER);
  1519. status_change_end(&sd->bl, SC_WEIGHT90, INVALID_TIMER);
  1520. status_change_end(&sd->bl, SC_SATURDAYNIGHTFEVER, INVALID_TIMER);
  1521. status_change_end(&sd->bl, SC_KYOUGAKU, INVALID_TIMER);
  1522. status_change_end(&sd->bl, SC_C_MARKER, INVALID_TIMER);
  1523. status_change_end(&sd->bl, SC_READYSTORM, INVALID_TIMER);
  1524. status_change_end(&sd->bl, SC_READYDOWN, INVALID_TIMER);
  1525. status_change_end(&sd->bl, SC_READYTURN, INVALID_TIMER);
  1526. status_change_end(&sd->bl, SC_READYCOUNTER, INVALID_TIMER);
  1527. status_change_end(&sd->bl, SC_CBC, INVALID_TIMER);
  1528. status_change_end(&sd->bl, SC_EQC, INVALID_TIMER);
  1529. if (battle_config.debuff_on_logout&1) { //Remove negative buffs
  1530. status_change_end(&sd->bl, SC_ORCISH, INVALID_TIMER);
  1531. status_change_end(&sd->bl, SC_STRIPWEAPON, INVALID_TIMER);
  1532. status_change_end(&sd->bl, SC_STRIPARMOR, INVALID_TIMER);
  1533. status_change_end(&sd->bl, SC_STRIPSHIELD, INVALID_TIMER);
  1534. status_change_end(&sd->bl, SC_STRIPHELM, INVALID_TIMER);
  1535. status_change_end(&sd->bl, SC_EXTREMITYFIST, INVALID_TIMER);
  1536. status_change_end(&sd->bl, SC_EXPLOSIONSPIRITS, INVALID_TIMER);
  1537. if(sd->sc.data[SC_REGENERATION] && sd->sc.data[SC_REGENERATION]->val4)
  1538. status_change_end(&sd->bl, SC_REGENERATION, INVALID_TIMER);
  1539. //TO-DO Probably there are way more NPC_type negative status that are removed
  1540. status_change_end(&sd->bl, SC_CHANGEUNDEAD, INVALID_TIMER);
  1541. // Both these statuses are removed on logout. [L0ne_W0lf]
  1542. status_change_end(&sd->bl, SC_SLOWCAST, INVALID_TIMER);
  1543. status_change_end(&sd->bl, SC_CRITICALWOUND, INVALID_TIMER);
  1544. status_change_end(&sd->bl, SC_HEAT_BARREL_AFTER, INVALID_TIMER);
  1545. status_change_end(&sd->bl, SC_H_MINE, INVALID_TIMER);
  1546. status_change_end(&sd->bl, SC_ANTI_M_BLAST, INVALID_TIMER);
  1547. status_change_end(&sd->bl, SC_B_TRAP, INVALID_TIMER);
  1548. }
  1549. if (battle_config.debuff_on_logout&2) { //Remove positive buffs
  1550. status_change_end(&sd->bl, SC_MAXIMIZEPOWER, INVALID_TIMER);
  1551. status_change_end(&sd->bl, SC_MAXOVERTHRUST, INVALID_TIMER);
  1552. status_change_end(&sd->bl, SC_STEELBODY, INVALID_TIMER);
  1553. status_change_end(&sd->bl, SC_PRESERVE, INVALID_TIMER);
  1554. status_change_end(&sd->bl, SC_KAAHI, INVALID_TIMER);
  1555. status_change_end(&sd->bl, SC_SPIRIT, INVALID_TIMER);
  1556. status_change_end(&sd->bl, SC_HEAT_BARREL, INVALID_TIMER);
  1557. status_change_end(&sd->bl, SC_P_ALTER, INVALID_TIMER);
  1558. status_change_end(&sd->bl, SC_E_CHAIN, INVALID_TIMER);
  1559. status_change_end(&sd->bl, SC_SIGHTBLASTER, INVALID_TIMER);
  1560. }
  1561. }
  1562. for (i = 0; i < EQI_MAX; i++) {
  1563. if (sd->equip_index[i] >= 0)
  1564. if (pc_isequip(sd,sd->equip_index[i]))
  1565. pc_unequipitem(sd,sd->equip_index[i],2);
  1566. }
  1567. // Return loot to owner
  1568. if( sd->pd ) pet_lootitem_drop(sd->pd, sd);
  1569. if( sd->state.storage_flag == 1 ) sd->state.storage_flag = 0; // No need to Double Save Storage on Quit.
  1570. if (sd->state.permanent_speed == 1) sd->state.permanent_speed = 0; // Remove lock so speed is set back to normal at login.
  1571. if( map[sd->bl.m].instance_id )
  1572. instance_delusers(map[sd->bl.m].instance_id);
  1573. if( sd->ed ) {
  1574. elemental_clean_effect(sd->ed);
  1575. unit_remove_map(&sd->ed->bl,CLR_RESPAWN);
  1576. }
  1577. unit_remove_map_pc(sd,CLR_RESPAWN);
  1578. if( map[sd->bl.m].instance_id ) { // Avoid map conflicts and warnings on next login
  1579. int16 m;
  1580. struct point *pt;
  1581. if( map[sd->bl.m].save.map )
  1582. pt = &map[sd->bl.m].save;
  1583. else
  1584. pt = &sd->status.save_point;
  1585. if( (m=map_mapindex2mapid(pt->map)) >= 0 )
  1586. {
  1587. sd->bl.m = m;
  1588. sd->bl.x = pt->x;
  1589. sd->bl.y = pt->y;
  1590. sd->mapindex = pt->map;
  1591. }
  1592. }
  1593. if (sd->state.vending)
  1594. idb_remove(vending_getdb(), sd->status.char_id);
  1595. if (sd->state.buyingstore)
  1596. idb_remove(buyingstore_getdb(), sd->status.char_id);
  1597. pc_damage_log_clear(sd,0);
  1598. party_booking_delete(sd); // Party Booking [Spiria]
  1599. pc_makesavestatus(sd);
  1600. pc_clean_skilltree(sd);
  1601. pc_crimson_marker_clear(sd);
  1602. chrif_save(sd,1);
  1603. unit_free_pc(sd);
  1604. return 0;
  1605. }
  1606. /*==========================================
  1607. * Lookup, id to session (player,mob,npc,homon,merc..)
  1608. *------------------------------------------*/
  1609. struct map_session_data * map_id2sd(int id){
  1610. if (id <= 0) return NULL;
  1611. return (struct map_session_data*)idb_get(pc_db,id);
  1612. }
  1613. struct mob_data * map_id2md(int id){
  1614. if (id <= 0) return NULL;
  1615. return (struct mob_data*)idb_get(mobid_db,id);
  1616. }
  1617. struct npc_data * map_id2nd(int id){
  1618. struct block_list* bl = map_id2bl(id);
  1619. return BL_CAST(BL_NPC, bl);
  1620. }
  1621. struct homun_data* map_id2hd(int id){
  1622. struct block_list* bl = map_id2bl(id);
  1623. return BL_CAST(BL_HOM, bl);
  1624. }
  1625. struct mercenary_data* map_id2mc(int id){
  1626. struct block_list* bl = map_id2bl(id);
  1627. return BL_CAST(BL_MER, bl);
  1628. }
  1629. struct pet_data* map_id2pd(int id){
  1630. struct block_list* bl = map_id2bl(id);
  1631. return BL_CAST(BL_PET, bl);
  1632. }
  1633. struct elemental_data* map_id2ed(int id) {
  1634. struct block_list* bl = map_id2bl(id);
  1635. return BL_CAST(BL_ELEM, bl);
  1636. }
  1637. struct chat_data* map_id2cd(int id){
  1638. struct block_list* bl = map_id2bl(id);
  1639. return BL_CAST(BL_CHAT, bl);
  1640. }
  1641. /// Returns the nick of the target charid or NULL if unknown (requests the nick to the char server).
  1642. const char* map_charid2nick(int charid)
  1643. {
  1644. struct charid2nick *p;
  1645. struct map_session_data* sd;
  1646. sd = map_charid2sd(charid);
  1647. if( sd )
  1648. return sd->status.name;// character is online, return it's name
  1649. p = idb_ensure(nick_db, charid, create_charid2nick);
  1650. if( *p->nick )
  1651. return p->nick;// name in nick_db
  1652. chrif_searchcharid(charid);// request the name
  1653. return NULL;
  1654. }
  1655. /// Returns the struct map_session_data of the charid or NULL if the char is not online.
  1656. struct map_session_data* map_charid2sd(int charid)
  1657. {
  1658. return (struct map_session_data*)idb_get(charid_db, charid);
  1659. }
  1660. /*==========================================
  1661. * Search session data from a nick name
  1662. * (without sensitive case if necessary)
  1663. * return map_session_data pointer or NULL
  1664. *------------------------------------------*/
  1665. struct map_session_data * map_nick2sd(const char *nick)
  1666. {
  1667. struct map_session_data* sd;
  1668. struct map_session_data* found_sd;
  1669. struct s_mapiterator* iter;
  1670. size_t nicklen;
  1671. int qty = 0;
  1672. if( nick == NULL )
  1673. return NULL;
  1674. nicklen = strlen(nick);
  1675. iter = mapit_getallusers();
  1676. found_sd = NULL;
  1677. for( sd = (TBL_PC*)mapit_first(iter); mapit_exists(iter); sd = (TBL_PC*)mapit_next(iter) )
  1678. {
  1679. if( battle_config.partial_name_scan )
  1680. {// partial name search
  1681. if( strnicmp(sd->status.name, nick, nicklen) == 0 )
  1682. {
  1683. found_sd = sd;
  1684. if( strcmp(sd->status.name, nick) == 0 )
  1685. {// Perfect Match
  1686. qty = 1;
  1687. break;
  1688. }
  1689. qty++;
  1690. }
  1691. }
  1692. else if( strcasecmp(sd->status.name, nick) == 0 )
  1693. {// exact search only
  1694. found_sd = sd;
  1695. break;
  1696. }
  1697. }
  1698. mapit_free(iter);
  1699. if( battle_config.partial_name_scan && qty != 1 )
  1700. found_sd = NULL;
  1701. return found_sd;
  1702. }
  1703. /*==========================================
  1704. * Looksup id_db DBMap and returns BL pointer of 'id' or NULL if not found
  1705. *------------------------------------------*/
  1706. struct block_list * map_id2bl(int id) {
  1707. return (struct block_list*)idb_get(id_db,id);
  1708. }
  1709. /**
  1710. * Same as map_id2bl except it only checks for its existence
  1711. **/
  1712. bool map_blid_exists( int id ) {
  1713. return (idb_exists(id_db,id));
  1714. }
  1715. /*==========================================
  1716. * Convex Mirror
  1717. *------------------------------------------*/
  1718. struct mob_data * map_getmob_boss(int16 m)
  1719. {
  1720. DBIterator* iter;
  1721. struct mob_data *md = NULL;
  1722. bool found = false;
  1723. iter = db_iterator(bossid_db);
  1724. for( md = (struct mob_data*)dbi_first(iter); dbi_exists(iter); md = (struct mob_data*)dbi_next(iter) )
  1725. {
  1726. if( md->bl.m == m )
  1727. {
  1728. found = true;
  1729. break;
  1730. }
  1731. }
  1732. dbi_destroy(iter);
  1733. return (found)? md : NULL;
  1734. }
  1735. struct mob_data * map_id2boss(int id)
  1736. {
  1737. if (id <= 0) return NULL;
  1738. return (struct mob_data*)idb_get(bossid_db,id);
  1739. }
  1740. /// Applies func to all the players in the db.
  1741. /// Stops iterating if func returns -1.
  1742. void map_foreachpc(int (*func)(struct map_session_data* sd, va_list args), ...)
  1743. {
  1744. DBIterator* iter;
  1745. struct map_session_data* sd;
  1746. iter = db_iterator(pc_db);
  1747. for( sd = dbi_first(iter); dbi_exists(iter); sd = dbi_next(iter) )
  1748. {
  1749. va_list args;
  1750. int ret;
  1751. va_start(args, func);
  1752. ret = func(sd, args);
  1753. va_end(args);
  1754. if( ret == -1 )
  1755. break;// stop iterating
  1756. }
  1757. dbi_destroy(iter);
  1758. }
  1759. /// Applies func to all the mobs in the db.
  1760. /// Stops iterating if func returns -1.
  1761. void map_foreachmob(int (*func)(struct mob_data* md, va_list args), ...)
  1762. {
  1763. DBIterator* iter;
  1764. struct mob_data* md;
  1765. iter = db_iterator(mobid_db);
  1766. for( md = (struct mob_data*)dbi_first(iter); dbi_exists(iter); md = (struct mob_data*)dbi_next(iter) )
  1767. {
  1768. va_list args;
  1769. int ret;
  1770. va_start(args, func);
  1771. ret = func(md, args);
  1772. va_end(args);
  1773. if( ret == -1 )
  1774. break;// stop iterating
  1775. }
  1776. dbi_destroy(iter);
  1777. }
  1778. /// Applies func to all the npcs in the db.
  1779. /// Stops iterating if func returns -1.
  1780. void map_foreachnpc(int (*func)(struct npc_data* nd, va_list args), ...)
  1781. {
  1782. DBIterator* iter;
  1783. struct block_list* bl;
  1784. iter = db_iterator(id_db);
  1785. for( bl = (struct block_list*)dbi_first(iter); dbi_exists(iter); bl = (struct block_list*)dbi_next(iter) )
  1786. {
  1787. if( bl->type == BL_NPC )
  1788. {
  1789. struct npc_data* nd = (struct npc_data*)bl;
  1790. va_list args;
  1791. int ret;
  1792. va_start(args, func);
  1793. ret = func(nd, args);
  1794. va_end(args);
  1795. if( ret == -1 )
  1796. break;// stop iterating
  1797. }
  1798. }
  1799. dbi_destroy(iter);
  1800. }
  1801. /// Applies func to everything in the db.
  1802. /// Stops iterating if func returns -1.
  1803. void map_foreachregen(int (*func)(struct block_list* bl, va_list args), ...)
  1804. {
  1805. DBIterator* iter;
  1806. struct block_list* bl;
  1807. iter = db_iterator(regen_db);
  1808. for( bl = (struct block_list*)dbi_first(iter); dbi_exists(iter); bl = (struct block_list*)dbi_next(iter) )
  1809. {
  1810. va_list args;
  1811. int ret;
  1812. va_start(args, func);
  1813. ret = func(bl, args);
  1814. va_end(args);
  1815. if( ret == -1 )
  1816. break;// stop iterating
  1817. }
  1818. dbi_destroy(iter);
  1819. }
  1820. /// Applies func to everything in the db.
  1821. /// Stops iterating if func returns -1.
  1822. void map_foreachiddb(int (*func)(struct block_list* bl, va_list args), ...)
  1823. {
  1824. DBIterator* iter;
  1825. struct block_list* bl;
  1826. iter = db_iterator(id_db);
  1827. for( bl = (struct block_list*)dbi_first(iter); dbi_exists(iter); bl = (struct block_list*)dbi_next(iter) )
  1828. {
  1829. va_list args;
  1830. int ret;
  1831. va_start(args, func);
  1832. ret = func(bl, args);
  1833. va_end(args);
  1834. if( ret == -1 )
  1835. break;// stop iterating
  1836. }
  1837. dbi_destroy(iter);
  1838. }
  1839. /// Iterator.
  1840. /// Can filter by bl type.
  1841. struct s_mapiterator
  1842. {
  1843. enum e_mapitflags flags;// flags for special behaviour
  1844. enum bl_type types;// what bl types to return
  1845. DBIterator* dbi;// database iterator
  1846. };
  1847. /// Returns true if the block_list matches the description in the iterator.
  1848. ///
  1849. /// @param _mapit_ Iterator
  1850. /// @param _bl_ block_list
  1851. /// @return true if it matches
  1852. #define MAPIT_MATCHES(_mapit_,_bl_) \
  1853. ( \
  1854. ( (_bl_)->type & (_mapit_)->types /* type matches */ ) \
  1855. )
  1856. /// Allocates a new iterator.
  1857. /// Returns the new iterator.
  1858. /// types can represent several BL's as a bit field.
  1859. /// TODO should this be expanded to allow filtering of map/guild/party/chat/cell/area/...?
  1860. ///
  1861. /// @param flags Flags of the iterator
  1862. /// @param type Target types
  1863. /// @return Iterator
  1864. struct s_mapiterator* mapit_alloc(enum e_mapitflags flags, enum bl_type types)
  1865. {
  1866. struct s_mapiterator* mapit;
  1867. CREATE(mapit, struct s_mapiterator, 1);
  1868. mapit->flags = flags;
  1869. mapit->types = types;
  1870. if( types == BL_PC ) mapit->dbi = db_iterator(pc_db);
  1871. else if( types == BL_MOB ) mapit->dbi = db_iterator(mobid_db);
  1872. else mapit->dbi = db_iterator(id_db);
  1873. return mapit;
  1874. }
  1875. /// Frees the iterator.
  1876. ///
  1877. /// @param mapit Iterator
  1878. void mapit_free(struct s_mapiterator* mapit)
  1879. {
  1880. nullpo_retv(mapit);
  1881. dbi_destroy(mapit->dbi);
  1882. aFree(mapit);
  1883. }
  1884. /// Returns the first block_list that matches the description.
  1885. /// Returns NULL if not found.
  1886. ///
  1887. /// @param mapit Iterator
  1888. /// @return first block_list or NULL
  1889. struct block_list* mapit_first(struct s_mapiterator* mapit)
  1890. {
  1891. struct block_list* bl;
  1892. nullpo_retr(NULL,mapit);
  1893. for( bl = (struct block_list*)dbi_first(mapit->dbi); bl != NULL; bl = (struct block_list*)dbi_next(mapit->dbi) )
  1894. {
  1895. if( MAPIT_MATCHES(mapit,bl) )
  1896. break;// found match
  1897. }
  1898. return bl;
  1899. }
  1900. /// Returns the last block_list that matches the description.
  1901. /// Returns NULL if not found.
  1902. ///
  1903. /// @param mapit Iterator
  1904. /// @return last block_list or NULL
  1905. struct block_list* mapit_last(struct s_mapiterator* mapit)
  1906. {
  1907. struct block_list* bl;
  1908. nullpo_retr(NULL,mapit);
  1909. for( bl = (struct block_list*)dbi_last(mapit->dbi); bl != NULL; bl = (struct block_list*)dbi_prev(mapit->dbi) )
  1910. {
  1911. if( MAPIT_MATCHES(mapit,bl) )
  1912. break;// found match
  1913. }
  1914. return bl;
  1915. }
  1916. /// Returns the next block_list that matches the description.
  1917. /// Returns NULL if not found.
  1918. ///
  1919. /// @param mapit Iterator
  1920. /// @return next block_list or NULL
  1921. struct block_list* mapit_next(struct s_mapiterator* mapit)
  1922. {
  1923. struct block_list* bl;
  1924. nullpo_retr(NULL,mapit);
  1925. for( ; ; )
  1926. {
  1927. bl = (struct block_list*)dbi_next(mapit->dbi);
  1928. if( bl == NULL )
  1929. break;// end
  1930. if( MAPIT_MATCHES(mapit,bl) )
  1931. break;// found a match
  1932. // try next
  1933. }
  1934. return bl;
  1935. }
  1936. /// Returns the previous block_list that matches the description.
  1937. /// Returns NULL if not found.
  1938. ///
  1939. /// @param mapit Iterator
  1940. /// @return previous block_list or NULL
  1941. struct block_list* mapit_prev(struct s_mapiterator* mapit)
  1942. {
  1943. struct block_list* bl;
  1944. nullpo_retr(NULL,mapit);
  1945. for( ; ; )
  1946. {
  1947. bl = (struct block_list*)dbi_prev(mapit->dbi);
  1948. if( bl == NULL )
  1949. break;// end
  1950. if( MAPIT_MATCHES(mapit,bl) )
  1951. break;// found a match
  1952. // try prev
  1953. }
  1954. return bl;
  1955. }
  1956. /// Returns true if the current block_list exists in the database.
  1957. ///
  1958. /// @param mapit Iterator
  1959. /// @return true if it exists
  1960. bool mapit_exists(struct s_mapiterator* mapit)
  1961. {
  1962. nullpo_retr(false,mapit);
  1963. return dbi_exists(mapit->dbi);
  1964. }
  1965. /*==========================================
  1966. * Add npc-bl to id_db, basically register npc to map
  1967. *------------------------------------------*/
  1968. bool map_addnpc(int16 m,struct npc_data *nd)
  1969. {
  1970. nullpo_ret(nd);
  1971. if( m < 0 || m >= map_num )
  1972. return false;
  1973. if( map[m].npc_num == MAX_NPC_PER_MAP )
  1974. {
  1975. ShowWarning("too many NPCs in one map %s\n",map[m].name);
  1976. return false;
  1977. }
  1978. map[m].npc[map[m].npc_num]=nd;
  1979. map[m].npc_num++;
  1980. idb_put(id_db,nd->bl.id,nd);
  1981. return true;
  1982. }
  1983. /*==========================================
  1984. * Add an instance map
  1985. *------------------------------------------*/
  1986. int map_addinstancemap(const char *name, int id)
  1987. {
  1988. int src_m = map_mapname2mapid(name);
  1989. int dst_m = -1, i;
  1990. char iname[MAP_NAME_LENGTH];
  1991. size_t num_cell, size;
  1992. if(src_m < 0)
  1993. return -1;
  1994. if(strlen(name) > 20) {
  1995. // against buffer overflow
  1996. ShowError("map_addisntancemap: can't add long map name \"%s\"\n", name);
  1997. return -2;
  1998. }
  1999. for(i = instance_start; i < MAX_MAP_PER_SERVER; i++) {
  2000. if(!map[i].name[0])
  2001. break;
  2002. }
  2003. if(i < map_num) // Destination map value overwrites another
  2004. dst_m = i;
  2005. else if(i < MAX_MAP_PER_SERVER) // Destination map value increments to new map
  2006. dst_m = map_num++;
  2007. else {
  2008. // Out of bounds
  2009. ShowError("map_addinstancemap failed. map_num(%d) > map_max(%d)\n",map_num, MAX_MAP_PER_SERVER);
  2010. return -3;
  2011. }
  2012. // Copy the map
  2013. memcpy(&map[dst_m], &map[src_m], sizeof(struct map_data));
  2014. strcpy(iname,name);
  2015. // Alter the name
  2016. // Due to this being custom we only worry about preserving as many characters as necessary for accurate map distinguishing
  2017. // This also allows us to maintain complete independence with main map functions
  2018. if((strchr(iname,'@') == NULL) && strlen(iname) > 8) {
  2019. memmove(iname, iname+(strlen(iname)-9), strlen(iname));
  2020. snprintf(map[dst_m].name, sizeof(map[dst_m].name),"%d#%s", id, iname);
  2021. } else
  2022. snprintf(map[dst_m].name, sizeof(map[dst_m].name),"%.3d%s", id, iname);
  2023. map[dst_m].name[MAP_NAME_LENGTH-1] = '\0';
  2024. // Mimic questinfo
  2025. if( map[src_m].qi_count ) {
  2026. map[dst_m].qi_count = map[src_m].qi_count;
  2027. CREATE( map[dst_m].qi_data, struct questinfo, map[dst_m].qi_count );
  2028. memcpy( map[dst_m].qi_data, map[src_m].qi_data, map[dst_m].qi_count * sizeof(struct questinfo) );
  2029. }
  2030. map[dst_m].m = dst_m;
  2031. map[dst_m].instance_id = id;
  2032. map[dst_m].instance_src_map = src_m;
  2033. map[dst_m].users = 0;
  2034. memset(map[dst_m].npc, 0, sizeof(map[dst_m].npc));
  2035. map[dst_m].npc_num = 0;
  2036. // Reallocate cells
  2037. num_cell = map[dst_m].xs * map[dst_m].ys;
  2038. CREATE( map[dst_m].cell, struct mapcell, num_cell );
  2039. memcpy( map[dst_m].cell, map[src_m].cell, num_cell * sizeof(struct mapcell) );
  2040. size = map[dst_m].bxs * map[dst_m].bys * sizeof(struct block_list*);
  2041. map[dst_m].block = (struct block_list **)aCalloc(1,size);
  2042. map[dst_m].block_mob = (struct block_list **)aCalloc(1,size);
  2043. map[dst_m].index = mapindex_addmap(-1, map[dst_m].name);
  2044. map[dst_m].channel = NULL;
  2045. map_addmap2db(&map[dst_m]);
  2046. return dst_m;
  2047. }
  2048. /*==========================================
  2049. * Set player to save point when they leave
  2050. *------------------------------------------*/
  2051. static int map_instancemap_leave(struct block_list *bl, va_list ap)
  2052. {
  2053. struct map_session_data* sd;
  2054. nullpo_retr(0, bl);
  2055. nullpo_retr(0, sd = (struct map_session_data *)bl);
  2056. pc_setpos(sd, sd->status.save_point.map, sd->status.save_point.x, sd->status.save_point.y, 3);
  2057. return 1;
  2058. }
  2059. /*==========================================
  2060. * Remove all units from instance
  2061. *------------------------------------------*/
  2062. static int map_instancemap_clean(struct block_list *bl, va_list ap)
  2063. {
  2064. nullpo_retr(0, bl);
  2065. switch(bl->type) {
  2066. case BL_PC:
  2067. map_quit((struct map_session_data *) bl);
  2068. break;
  2069. case BL_NPC:
  2070. npc_unload((struct npc_data *)bl,true);
  2071. break;
  2072. case BL_MOB:
  2073. unit_free(bl,CLR_OUTSIGHT);
  2074. break;
  2075. case BL_PET:
  2076. //There is no need for this, the pet is removed together with the player. [Skotlex]
  2077. break;
  2078. case BL_ITEM:
  2079. map_clearflooritem(bl);
  2080. break;
  2081. case BL_SKILL:
  2082. skill_delunit((struct skill_unit *) bl);
  2083. break;
  2084. }
  2085. return 1;
  2086. }
  2087. /*==========================================
  2088. * Deleting an instance map
  2089. *------------------------------------------*/
  2090. int map_delinstancemap(int m)
  2091. {
  2092. if(m < 0 || !map[m].instance_id)
  2093. return 0;
  2094. // Kick everyone out
  2095. map_foreachinmap(map_instancemap_leave, m, BL_PC);
  2096. // Do the unit cleanup
  2097. map_foreachinmap(map_instancemap_clean, m, BL_ALL);
  2098. if( map[m].mob_delete_timer != INVALID_TIMER )
  2099. delete_timer(map[m].mob_delete_timer, map_removemobs_timer);
  2100. mapindex_removemap( map[m].index );
  2101. // Free memory
  2102. aFree(map[m].cell);
  2103. aFree(map[m].block);
  2104. aFree(map[m].block_mob);
  2105. map_removemapdb(&map[m]);
  2106. memset(&map[m], 0x00, sizeof(map[0]));
  2107. if( map[m].qi_data )
  2108. aFree(map[m].qi_data);
  2109. // Make delete timers invalid to avoid errors
  2110. map[m].mob_delete_timer = INVALID_TIMER;
  2111. return 1;
  2112. }
  2113. /*=========================================
  2114. * Dynamic Mobs [Wizputer]
  2115. *-----------------------------------------*/
  2116. // Stores the spawn data entry in the mob list.
  2117. // Returns the index of successful, or -1 if the list was full.
  2118. int map_addmobtolist(unsigned short m, struct spawn_data *spawn)
  2119. {
  2120. size_t i;
  2121. ARR_FIND( 0, MAX_MOB_LIST_PER_MAP, i, map[m].moblist[i] == NULL );
  2122. if( i < MAX_MOB_LIST_PER_MAP )
  2123. {
  2124. map[m].moblist[i] = spawn;
  2125. return i;
  2126. }
  2127. return -1;
  2128. }
  2129. void map_spawnmobs(int16 m)
  2130. {
  2131. int i, k=0;
  2132. if (map[m].mob_delete_timer != INVALID_TIMER)
  2133. { //Mobs have not been removed yet [Skotlex]
  2134. delete_timer(map[m].mob_delete_timer, map_removemobs_timer);
  2135. map[m].mob_delete_timer = INVALID_TIMER;
  2136. return;
  2137. }
  2138. for(i=0; i<MAX_MOB_LIST_PER_MAP; i++)
  2139. if(map[m].moblist[i]!=NULL)
  2140. {
  2141. k+=map[m].moblist[i]->num;
  2142. npc_parse_mob2(map[m].moblist[i]);
  2143. }
  2144. if (battle_config.etc_log && k > 0)
  2145. {
  2146. ShowStatus("Map %s: Spawned '"CL_WHITE"%d"CL_RESET"' mobs.\n",map[m].name, k);
  2147. }
  2148. }
  2149. int map_removemobs_sub(struct block_list *bl, va_list ap)
  2150. {
  2151. struct mob_data *md = (struct mob_data *)bl;
  2152. nullpo_ret(md);
  2153. //When not to remove mob:
  2154. // doesn't respawn and is not a slave
  2155. if( !md->spawn && !md->master_id )
  2156. return 0;
  2157. // respawn data is not in cache
  2158. if( md->spawn && !md->spawn->state.dynamic )
  2159. return 0;
  2160. // hasn't spawned yet
  2161. if( md->spawn_timer != INVALID_TIMER )
  2162. return 0;
  2163. // is damaged and mob_remove_damaged is off
  2164. if( !battle_config.mob_remove_damaged && md->status.hp < md->status.max_hp )
  2165. return 0;
  2166. // is a mvp
  2167. if( md->db->mexp > 0 )
  2168. return 0;
  2169. unit_free(&md->bl,CLR_OUTSIGHT);
  2170. return 1;
  2171. }
  2172. int map_removemobs_timer(int tid, unsigned int tick, int id, intptr_t data)
  2173. {
  2174. int count;
  2175. const int16 m = id;
  2176. if (m < 0 || m >= MAX_MAP_PER_SERVER)
  2177. { //Incorrect map id!
  2178. ShowError("map_removemobs_timer error: timer %d points to invalid map %d\n",tid, m);
  2179. return 0;
  2180. }
  2181. if (map[m].mob_delete_timer != tid)
  2182. { //Incorrect timer call!
  2183. ShowError("map_removemobs_timer mismatch: %d != %d (map %s)\n",map[m].mob_delete_timer, tid, map[m].name);
  2184. return 0;
  2185. }
  2186. map[m].mob_delete_timer = INVALID_TIMER;
  2187. if (map[m].users > 0) //Map not empty!
  2188. return 1;
  2189. count = map_foreachinmap(map_removemobs_sub, m, BL_MOB);
  2190. if (battle_config.etc_log && count > 0)
  2191. ShowStatus("Map %s: Removed '"CL_WHITE"%d"CL_RESET"' mobs.\n",map[m].name, count);
  2192. return 1;
  2193. }
  2194. void map_removemobs(int16 m)
  2195. {
  2196. if (map[m].mob_delete_timer != INVALID_TIMER) // should never happen
  2197. return; //Mobs are already scheduled for removal
  2198. map[m].mob_delete_timer = add_timer(gettick()+battle_config.mob_remove_delay, map_removemobs_timer, m, 0);
  2199. }
  2200. /*==========================================
  2201. * Check for map_name from map_id
  2202. *------------------------------------------*/
  2203. const char* map_mapid2mapname(int m)
  2204. {
  2205. if (map[m].instance_id) { // Instance map check
  2206. struct instance_data *im = &instance_data[map[m].instance_id];
  2207. if (!im) // This shouldn't happen but if it does give them the map we intended to give
  2208. return map[m].name;
  2209. else {
  2210. int i;
  2211. for (i = 0; i < MAX_MAP_PER_INSTANCE; i++) { // Loop to find the src map we want
  2212. if (im->map[i].m == m)
  2213. return map[im->map[i].src_m].name;
  2214. }
  2215. }
  2216. }
  2217. return map[m].name;
  2218. }
  2219. /*==========================================
  2220. * Hookup, get map_id from map_name
  2221. *------------------------------------------*/
  2222. int16 map_mapname2mapid(const char* name)
  2223. {
  2224. unsigned short map_index;
  2225. map_index = mapindex_name2id(name);
  2226. if (!map_index)
  2227. return -1;
  2228. return map_mapindex2mapid(map_index);
  2229. }
  2230. /*==========================================
  2231. * Returns the map of the given mapindex. [Skotlex]
  2232. *------------------------------------------*/
  2233. int16 map_mapindex2mapid(unsigned short mapindex)
  2234. {
  2235. struct map_data *md=NULL;
  2236. if (!mapindex)
  2237. return -1;
  2238. md = (struct map_data*)uidb_get(map_db,(unsigned int)mapindex);
  2239. if(md==NULL || md->cell==NULL)
  2240. return -1;
  2241. return md->m;
  2242. }
  2243. /*==========================================
  2244. * Switching Ip, port ? (like changing map_server) get ip/port from map_name
  2245. *------------------------------------------*/
  2246. int map_mapname2ipport(unsigned short name, uint32* ip, uint16* port)
  2247. {
  2248. struct map_data_other_server *mdos;
  2249. mdos = (struct map_data_other_server*)uidb_get(map_db,(unsigned int)name);
  2250. if(mdos==NULL || mdos->cell) //If gat isn't null, this is a local map.
  2251. return -1;
  2252. *ip=mdos->ip;
  2253. *port=mdos->port;
  2254. return 0;
  2255. }
  2256. /*==========================================
  2257. * Checks if both dirs point in the same direction.
  2258. *------------------------------------------*/
  2259. int map_check_dir(int s_dir,int t_dir)
  2260. {
  2261. if(s_dir == t_dir)
  2262. return 0;
  2263. switch(s_dir) {
  2264. case 0: if(t_dir == 7 || t_dir == 1 || t_dir == 0) return 0; break;
  2265. case 1: if(t_dir == 0 || t_dir == 2 || t_dir == 1) return 0; break;
  2266. case 2: if(t_dir == 1 || t_dir == 3 || t_dir == 2) return 0; break;
  2267. case 3: if(t_dir == 2 || t_dir == 4 || t_dir == 3) return 0; break;
  2268. case 4: if(t_dir == 3 || t_dir == 5 || t_dir == 4) return 0; break;
  2269. case 5: if(t_dir == 4 || t_dir == 6 || t_dir == 5) return 0; break;
  2270. case 6: if(t_dir == 5 || t_dir == 7 || t_dir == 6) return 0; break;
  2271. case 7: if(t_dir == 6 || t_dir == 0 || t_dir == 7) return 0; break;
  2272. }
  2273. return 1;
  2274. }
  2275. /*==========================================
  2276. * Returns the direction of the given cell, relative to 'src'
  2277. *------------------------------------------*/
  2278. uint8 map_calc_dir(struct block_list* src, int16 x, int16 y)
  2279. {
  2280. uint8 dir = 0;
  2281. nullpo_ret(src);
  2282. dir = map_calc_dir_xy(src->x, src->y, x, y, unit_getdir(src));
  2283. return dir;
  2284. }
  2285. /*==========================================
  2286. * Returns the direction of the given cell, relative to source cell
  2287. * Use this if you don't have a block list available to check against
  2288. *------------------------------------------*/
  2289. uint8 map_calc_dir_xy(int16 srcx, int16 srcy, int16 x, int16 y, uint8 srcdir) {
  2290. uint8 dir = 0;
  2291. int dx, dy;
  2292. dx = x-srcx;
  2293. dy = y-srcy;
  2294. if( dx == 0 && dy == 0 )
  2295. { // both are standing on the same spot
  2296. // aegis-style, makes knockback default to the left
  2297. // athena-style, makes knockback default to behind 'src'
  2298. dir = (battle_config.knockback_left ? 6 : srcdir);
  2299. }
  2300. else if( dx >= 0 && dy >=0 )
  2301. { // upper-right
  2302. if( dx >= dy*3 ) dir = 6; // right
  2303. else if( dx*3 < dy ) dir = 0; // up
  2304. else dir = 7; // up-right
  2305. }
  2306. else if( dx >= 0 && dy <= 0 )
  2307. { // lower-right
  2308. if( dx >= -dy*3 ) dir = 6; // right
  2309. else if( dx*3 < -dy ) dir = 4; // down
  2310. else dir = 5; // down-right
  2311. }
  2312. else if( dx <= 0 && dy <= 0 )
  2313. { // lower-left
  2314. if( dx*3 >= dy ) dir = 4; // down
  2315. else if( dx < dy*3 ) dir = 2; // left
  2316. else dir = 3; // down-left
  2317. }
  2318. else
  2319. { // upper-left
  2320. if( -dx*3 <= dy ) dir = 0; // up
  2321. else if( -dx > dy*3 ) dir = 2; // left
  2322. else dir = 1; // up-left
  2323. }
  2324. return dir;
  2325. }
  2326. /*==========================================
  2327. * Randomizes target cell x,y to a random walkable cell that
  2328. * has the same distance from object as given coordinates do. [Skotlex]
  2329. *------------------------------------------*/
  2330. int map_random_dir(struct block_list *bl, int16 *x, int16 *y)
  2331. {
  2332. short xi = *x-bl->x;
  2333. short yi = *y-bl->y;
  2334. short i=0;
  2335. int dist2 = xi*xi + yi*yi;
  2336. short dist = (short)sqrt((float)dist2);
  2337. if (dist < 1) dist =1;
  2338. do {
  2339. short j = 1 + 2*(rnd()%4); //Pick a random diagonal direction
  2340. short segment = 1+(rnd()%dist); //Pick a random interval from the whole vector in that direction
  2341. xi = bl->x + segment*dirx[j];
  2342. segment = (short)sqrt((float)(dist2 - segment*segment)); //The complement of the previously picked segment
  2343. yi = bl->y + segment*diry[j];
  2344. } while (
  2345. (map_getcell(bl->m,xi,yi,CELL_CHKNOPASS) || !path_search(NULL,bl->m,bl->x,bl->y,xi,yi,1,CELL_CHKNOREACH))
  2346. && (++i)<100 );
  2347. if (i < 100) {
  2348. *x = xi;
  2349. *y = yi;
  2350. return 1;
  2351. }
  2352. return 0;
  2353. }
  2354. // gat system
  2355. inline static struct mapcell map_gat2cell(int gat) {
  2356. struct mapcell cell;
  2357. memset(&cell,0,sizeof(struct mapcell));
  2358. switch( gat ) {
  2359. case 0: cell.walkable = 1; cell.shootable = 1; cell.water = 0; break; // walkable ground
  2360. case 1: cell.walkable = 0; cell.shootable = 0; cell.water = 0; break; // non-walkable ground
  2361. case 2: cell.walkable = 1; cell.shootable = 1; cell.water = 0; break; // ???
  2362. case 3: cell.walkable = 1; cell.shootable = 1; cell.water = 1; break; // walkable water
  2363. case 4: cell.walkable = 1; cell.shootable = 1; cell.water = 0; break; // ???
  2364. case 5: cell.walkable = 0; cell.shootable = 1; cell.water = 0; break; // gap (snipable)
  2365. case 6: cell.walkable = 1; cell.shootable = 1; cell.water = 0; break; // ???
  2366. default:
  2367. ShowWarning("map_gat2cell: unrecognized gat type '%d'\n", gat);
  2368. break;
  2369. }
  2370. return cell;
  2371. }
  2372. static int map_cell2gat(struct mapcell cell)
  2373. {
  2374. if( cell.walkable == 1 && cell.shootable == 1 && cell.water == 0 ) return 0;
  2375. if( cell.walkable == 0 && cell.shootable == 0 && cell.water == 0 ) return 1;
  2376. if( cell.walkable == 1 && cell.shootable == 1 && cell.water == 1 ) return 3;
  2377. if( cell.walkable == 0 && cell.shootable == 1 && cell.water == 0 ) return 5;
  2378. ShowWarning("map_cell2gat: cell has no matching gat type\n");
  2379. return 1; // default to 'wall'
  2380. }
  2381. /*==========================================
  2382. * Confirm if celltype in (m,x,y) match the one given in cellchk
  2383. *------------------------------------------*/
  2384. int map_getcell(int16 m,int16 x,int16 y,cell_chk cellchk)
  2385. {
  2386. return (m < 0 || m >= MAX_MAP_PER_SERVER) ? 0 : map_getcellp(&map[m],x,y,cellchk);
  2387. }
  2388. int map_getcellp(struct map_data* m,int16 x,int16 y,cell_chk cellchk)
  2389. {
  2390. struct mapcell cell;
  2391. nullpo_ret(m);
  2392. //NOTE: this intentionally overrides the last row and column
  2393. if(x<0 || x>=m->xs-1 || y<0 || y>=m->ys-1)
  2394. return( cellchk == CELL_CHKNOPASS );
  2395. cell = m->cell[x + y*m->xs];
  2396. switch(cellchk)
  2397. {
  2398. // gat type retrieval
  2399. case CELL_GETTYPE:
  2400. return map_cell2gat(cell);
  2401. // base gat type checks
  2402. case CELL_CHKWALL:
  2403. return (!cell.walkable && !cell.shootable);
  2404. case CELL_CHKWATER:
  2405. return (cell.water);
  2406. case CELL_CHKCLIFF:
  2407. return (!cell.walkable && cell.shootable);
  2408. // base cell type checks
  2409. case CELL_CHKNPC:
  2410. return (cell.npc);
  2411. case CELL_CHKBASILICA:
  2412. return (cell.basilica);
  2413. case CELL_CHKLANDPROTECTOR:
  2414. return (cell.landprotector);
  2415. case CELL_CHKNOVENDING:
  2416. return (cell.novending);
  2417. case CELL_CHKNOCHAT:
  2418. return (cell.nochat);
  2419. case CELL_CHKMAELSTROM:
  2420. return (cell.maelstrom);
  2421. case CELL_CHKICEWALL:
  2422. return (cell.icewall);
  2423. // special checks
  2424. case CELL_CHKPASS:
  2425. #ifdef CELL_NOSTACK
  2426. if (cell.cell_bl >= battle_config.custom_cell_stack_limit) return 0;
  2427. #endif
  2428. case CELL_CHKREACH:
  2429. return (cell.walkable);
  2430. case CELL_CHKNOPASS:
  2431. #ifdef CELL_NOSTACK
  2432. if (cell.cell_bl >= battle_config.custom_cell_stack_limit) return 1;
  2433. #endif
  2434. case CELL_CHKNOREACH:
  2435. return (!cell.walkable);
  2436. case CELL_CHKSTACK:
  2437. #ifdef CELL_NOSTACK
  2438. return (cell.cell_bl >= battle_config.custom_cell_stack_limit);
  2439. #else
  2440. return 0;
  2441. #endif
  2442. default:
  2443. return 0;
  2444. }
  2445. }
  2446. /*==========================================
  2447. * Change the type/flags of a map cell
  2448. * 'cell' - which flag to modify
  2449. * 'flag' - true = on, false = off
  2450. *------------------------------------------*/
  2451. void map_setcell(int16 m, int16 x, int16 y, cell_t cell, bool flag)
  2452. {
  2453. int j;
  2454. if( m < 0 || m >= map_num || x < 0 || x >= map[m].xs || y < 0 || y >= map[m].ys )
  2455. return;
  2456. j = x + y*map[m].xs;
  2457. switch( cell ) {
  2458. case CELL_WALKABLE: map[m].cell[j].walkable = flag; break;
  2459. case CELL_SHOOTABLE: map[m].cell[j].shootable = flag; break;
  2460. case CELL_WATER: map[m].cell[j].water = flag; break;
  2461. case CELL_NPC: map[m].cell[j].npc = flag; break;
  2462. case CELL_BASILICA: map[m].cell[j].basilica = flag; break;
  2463. case CELL_LANDPROTECTOR: map[m].cell[j].landprotector = flag; break;
  2464. case CELL_NOVENDING: map[m].cell[j].novending = flag; break;
  2465. case CELL_NOCHAT: map[m].cell[j].nochat = flag; break;
  2466. case CELL_MAELSTROM: map[m].cell[j].maelstrom = flag; break;
  2467. case CELL_ICEWALL: map[m].cell[j].icewall = flag; break;
  2468. default:
  2469. ShowWarning("map_setcell: invalid cell type '%d'\n", (int)cell);
  2470. break;
  2471. }
  2472. }
  2473. void map_setgatcell(int16 m, int16 x, int16 y, int gat)
  2474. {
  2475. int j;
  2476. struct mapcell cell;
  2477. if( m < 0 || m >= map_num || x < 0 || x >= map[m].xs || y < 0 || y >= map[m].ys )
  2478. return;
  2479. j = x + y*map[m].xs;
  2480. cell = map_gat2cell(gat);
  2481. map[m].cell[j].walkable = cell.walkable;
  2482. map[m].cell[j].shootable = cell.shootable;
  2483. map[m].cell[j].water = cell.water;
  2484. }
  2485. /*==========================================
  2486. * Invisible Walls
  2487. *------------------------------------------*/
  2488. static DBMap* iwall_db;
  2489. void map_iwall_nextxy(int16 x, int16 y, int8 dir, int pos, int16 *x1, int16 *y1)
  2490. {
  2491. if( dir == 0 || dir == 4 )
  2492. *x1 = x; // Keep X
  2493. else if( dir > 0 && dir < 4 )
  2494. *x1 = x - pos; // Going left
  2495. else
  2496. *x1 = x + pos; // Going right
  2497. if( dir == 2 || dir == 6 )
  2498. *y1 = y;
  2499. else if( dir > 2 && dir < 6 )
  2500. *y1 = y - pos;
  2501. else
  2502. *y1 = y + pos;
  2503. }
  2504. bool map_iwall_set(int16 m, int16 x, int16 y, int size, int8 dir, bool shootable, const char* wall_name)
  2505. {
  2506. struct iwall_data *iwall;
  2507. int i;
  2508. int16 x1 = 0, y1 = 0;
  2509. if( size < 1 || !wall_name )
  2510. return false;
  2511. if( (iwall = (struct iwall_data *)strdb_get(iwall_db, wall_name)) != NULL )
  2512. return false; // Already Exists
  2513. if( map_getcell(m, x, y, CELL_CHKNOREACH) )
  2514. return false; // Starting cell problem
  2515. CREATE(iwall, struct iwall_data, 1);
  2516. iwall->m = m;
  2517. iwall->x = x;
  2518. iwall->y = y;
  2519. iwall->size = size;
  2520. iwall->dir = dir;
  2521. iwall->shootable = shootable;
  2522. safestrncpy(iwall->wall_name, wall_name, sizeof(iwall->wall_name));
  2523. for( i = 0; i < size; i++ )
  2524. {
  2525. map_iwall_nextxy(x, y, dir, i, &x1, &y1);
  2526. if( map_getcell(m, x1, y1, CELL_CHKNOREACH) )
  2527. break; // Collision
  2528. map_setcell(m, x1, y1, CELL_WALKABLE, false);
  2529. map_setcell(m, x1, y1, CELL_SHOOTABLE, shootable);
  2530. clif_changemapcell(0, m, x1, y1, map_getcell(m, x1, y1, CELL_GETTYPE), ALL_SAMEMAP);
  2531. }
  2532. iwall->size = i;
  2533. strdb_put(iwall_db, iwall->wall_name, iwall);
  2534. map[m].iwall_num++;
  2535. return true;
  2536. }
  2537. void map_iwall_get(struct map_session_data *sd) {
  2538. struct iwall_data *iwall;
  2539. DBIterator* iter;
  2540. int16 x1, y1;
  2541. int i;
  2542. if( map[sd->bl.m].iwall_num < 1 )
  2543. return;
  2544. iter = db_iterator(iwall_db);
  2545. for( iwall = dbi_first(iter); dbi_exists(iter); iwall = dbi_next(iter) ) {
  2546. if( iwall->m != sd->bl.m )
  2547. continue;
  2548. for( i = 0; i < iwall->size; i++ ) {
  2549. map_iwall_nextxy(iwall->x, iwall->y, iwall->dir, i, &x1, &y1);
  2550. clif_changemapcell(sd->fd, iwall->m, x1, y1, map_getcell(iwall->m, x1, y1, CELL_GETTYPE), SELF);
  2551. }
  2552. }
  2553. dbi_destroy(iter);
  2554. }
  2555. void map_iwall_remove(const char *wall_name)
  2556. {
  2557. struct iwall_data *iwall;
  2558. int16 i, x1, y1;
  2559. if( (iwall = (struct iwall_data *)strdb_get(iwall_db, wall_name)) == NULL )
  2560. return; // Nothing to do
  2561. for( i = 0; i < iwall->size; i++ ) {
  2562. map_iwall_nextxy(iwall->x, iwall->y, iwall->dir, i, &x1, &y1);
  2563. map_setcell(iwall->m, x1, y1, CELL_SHOOTABLE, true);
  2564. map_setcell(iwall->m, x1, y1, CELL_WALKABLE, true);
  2565. clif_changemapcell(0, iwall->m, x1, y1, map_getcell(iwall->m, x1, y1, CELL_GETTYPE), ALL_SAMEMAP);
  2566. }
  2567. map[iwall->m].iwall_num--;
  2568. strdb_remove(iwall_db, iwall->wall_name);
  2569. }
  2570. /**
  2571. * @see DBCreateData
  2572. */
  2573. static DBData create_map_data_other_server(DBKey key, va_list args)
  2574. {
  2575. struct map_data_other_server *mdos;
  2576. unsigned short mapindex = (unsigned short)key.ui;
  2577. mdos=(struct map_data_other_server *)aCalloc(1,sizeof(struct map_data_other_server));
  2578. mdos->index = mapindex;
  2579. memcpy(mdos->name, mapindex_id2name(mapindex), MAP_NAME_LENGTH);
  2580. return db_ptr2data(mdos);
  2581. }
  2582. /*==========================================
  2583. * Add mapindex to db of another map server
  2584. *------------------------------------------*/
  2585. int map_setipport(unsigned short mapindex, uint32 ip, uint16 port)
  2586. {
  2587. struct map_data_other_server *mdos;
  2588. mdos= uidb_ensure(map_db,(unsigned int)mapindex, create_map_data_other_server);
  2589. if(mdos->cell) //Local map,Do nothing. Give priority to our own local maps over ones from another server. [Skotlex]
  2590. return 0;
  2591. if(ip == clif_getip() && port == clif_getport()) {
  2592. //That's odd, we received info that we are the ones with this map, but... we don't have it.
  2593. ShowFatalError("map_setipport : received info that this map-server SHOULD have map '%s', but it is not loaded.\n",mapindex_id2name(mapindex));
  2594. exit(EXIT_FAILURE);
  2595. }
  2596. mdos->ip = ip;
  2597. mdos->port = port;
  2598. return 1;
  2599. }
  2600. /**
  2601. * Delete all the other maps server management
  2602. * @see DBApply
  2603. */
  2604. int map_eraseallipport_sub(DBKey key, DBData *data, va_list va)
  2605. {
  2606. struct map_data_other_server *mdos = db_data2ptr(data);
  2607. if(mdos->cell == NULL) {
  2608. db_remove(map_db,key);
  2609. aFree(mdos);
  2610. }
  2611. return 0;
  2612. }
  2613. int map_eraseallipport(void)
  2614. {
  2615. map_db->foreach(map_db,map_eraseallipport_sub);
  2616. return 1;
  2617. }
  2618. /*==========================================
  2619. * Delete mapindex from db of another map server
  2620. *------------------------------------------*/
  2621. int map_eraseipport(unsigned short mapindex, uint32 ip, uint16 port)
  2622. {
  2623. struct map_data_other_server *mdos;
  2624. mdos = (struct map_data_other_server*)uidb_get(map_db,(unsigned int)mapindex);
  2625. if(!mdos || mdos->cell) //Map either does not exists or is a local map.
  2626. return 0;
  2627. if(mdos->ip==ip && mdos->port == port) {
  2628. uidb_remove(map_db,(unsigned int)mapindex);
  2629. aFree(mdos);
  2630. return 1;
  2631. }
  2632. return 0;
  2633. }
  2634. /*==========================================
  2635. * [Shinryo]: Init the mapcache
  2636. *------------------------------------------*/
  2637. static char *map_init_mapcache(FILE *fp)
  2638. {
  2639. size_t size = 0;
  2640. char *buffer;
  2641. // No file open? Return..
  2642. nullpo_ret(fp);
  2643. // Get file size
  2644. fseek(fp, 0, SEEK_END);
  2645. size = ftell(fp);
  2646. fseek(fp, 0, SEEK_SET);
  2647. // Allocate enough space
  2648. CREATE(buffer, char, size);
  2649. // No memory? Return..
  2650. nullpo_ret(buffer);
  2651. // Read file into buffer..
  2652. if(fread(buffer, 1, size, fp) != size) {
  2653. ShowError("map_init_mapcache: Could not read entire mapcache file\n");
  2654. return NULL;
  2655. }
  2656. return buffer;
  2657. }
  2658. /*==========================================
  2659. * Map cache reading
  2660. * [Shinryo]: Optimized some behaviour to speed this up
  2661. *==========================================*/
  2662. int map_readfromcache(struct map_data *m, char *buffer, char *decode_buffer)
  2663. {
  2664. int i;
  2665. struct map_cache_main_header *header = (struct map_cache_main_header *)buffer;
  2666. struct map_cache_map_info *info = NULL;
  2667. char *p = buffer + sizeof(struct map_cache_main_header);
  2668. for(i = 0; i < header->map_count; i++) {
  2669. info = (struct map_cache_map_info *)p;
  2670. if( strcmp(m->name, info->name) == 0 )
  2671. break; // Map found
  2672. // Jump to next entry..
  2673. p += sizeof(struct map_cache_map_info) + info->len;
  2674. }
  2675. if( info && i < header->map_count ) {
  2676. unsigned long size, xy;
  2677. if( info->xs <= 0 || info->ys <= 0 )
  2678. return 0;// Invalid
  2679. m->xs = info->xs;
  2680. m->ys = info->ys;
  2681. size = (unsigned long)info->xs*(unsigned long)info->ys;
  2682. if(size > MAX_MAP_SIZE) {
  2683. ShowWarning("map_readfromcache: %s exceeded MAX_MAP_SIZE of %d\n", info->name, MAX_MAP_SIZE);
  2684. return 0; // Say not found to remove it from list.. [Shinryo]
  2685. }
  2686. // TO-DO: Maybe handle the scenario, if the decoded buffer isn't the same size as expected? [Shinryo]
  2687. decode_zip(decode_buffer, &size, p+sizeof(struct map_cache_map_info), info->len);
  2688. CREATE(m->cell, struct mapcell, size);
  2689. for( xy = 0; xy < size; ++xy )
  2690. m->cell[xy] = map_gat2cell(decode_buffer[xy]);
  2691. return 1;
  2692. }
  2693. return 0; // Not found
  2694. }
  2695. int map_addmap(char* mapname)
  2696. {
  2697. if( strcmpi(mapname,"clear")==0 )
  2698. {
  2699. map_num = 0;
  2700. instance_start = 0;
  2701. return 0;
  2702. }
  2703. if( map_num >= MAX_MAP_PER_SERVER - 1 )
  2704. {
  2705. ShowError("Could not add map '"CL_WHITE"%s"CL_RESET"', the limit of maps has been reached.\n",mapname);
  2706. return 1;
  2707. }
  2708. mapindex_getmapname(mapname, map[map_num].name);
  2709. map_num++;
  2710. return 0;
  2711. }
  2712. static void map_delmapid(int id)
  2713. {
  2714. ShowNotice("Removing map [ %s ] from maplist"CL_CLL"\n",map[id].name);
  2715. memmove(map+id, map+id+1, sizeof(map[0])*(map_num-id-1));
  2716. map_num--;
  2717. }
  2718. int map_delmap(char* mapname)
  2719. {
  2720. int i;
  2721. char map_name[MAP_NAME_LENGTH];
  2722. if (strcmpi(mapname, "all") == 0) {
  2723. map_num = 0;
  2724. return 0;
  2725. }
  2726. mapindex_getmapname(mapname, map_name);
  2727. for(i = 0; i < map_num; i++) {
  2728. if (strcmp(map[i].name, map_name) == 0) {
  2729. map_delmapid(i);
  2730. return 1;
  2731. }
  2732. }
  2733. return 0;
  2734. }
  2735. /// Initializes map flags and adjusts them depending on configuration.
  2736. void map_flags_init(void)
  2737. {
  2738. int i;
  2739. for( i = 0; i < map_num; i++ )
  2740. {
  2741. // mapflags
  2742. memset(&map[i].flag, 0, sizeof(map[i].flag));
  2743. // additional mapflag data
  2744. map[i].zone = 0; // restricted mapflag zone
  2745. map[i].nocommand = 0; // nocommand mapflag level
  2746. map[i].adjust.bexp = 100; // per map base exp multiplicator
  2747. map[i].adjust.jexp = 100; // per map job exp multiplicator
  2748. memset(map[i].drop_list, 0, sizeof(map[i].drop_list)); // pvp nightmare drop list
  2749. // skill damage
  2750. #ifdef ADJUST_SKILL_DAMAGE
  2751. memset(&map[i].adjust.damage, 0, sizeof(map[i].adjust.damage));
  2752. if (map[i].skill_damage.count)
  2753. map_skill_damage_free(&map[i]);
  2754. #endif
  2755. // adjustments
  2756. if( battle_config.pk_mode )
  2757. map[i].flag.pvp = 1; // make all maps pvp for pk_mode [Valaris]
  2758. if( map[i].qi_data )
  2759. aFree(map[i].qi_data);
  2760. map[i].qi_data = NULL;
  2761. map[i].qi_count = 0;
  2762. }
  2763. }
  2764. #define NO_WATER 1000000
  2765. /*
  2766. * Reads from the .rsw for each map
  2767. * Returns water height (or NO_WATER if file doesn't exist) or other error is encountered.
  2768. * Assumed path for file is data/mapname.rsw
  2769. * Credits to LittleWolf
  2770. */
  2771. int map_waterheight(char* mapname)
  2772. {
  2773. char fn[256];
  2774. char *rsw, *found;
  2775. //Look up for the rsw
  2776. sprintf(fn, "data\\%s.rsw", mapname);
  2777. found = grfio_find_file(fn);
  2778. if (found) strcpy(fn, found); // replace with real name
  2779. // read & convert fn
  2780. rsw = (char *) grfio_read (fn);
  2781. if (rsw)
  2782. { //Load water height from file
  2783. int wh = (int) *(float*)(rsw+166); //FIXME Casting between integer* and float* which have an incompatible binary data representation.
  2784. aFree(rsw);
  2785. return wh;
  2786. }
  2787. ShowWarning("Failed to find water level for (%s)\n", mapname, fn);
  2788. return NO_WATER;
  2789. }
  2790. /*==================================
  2791. * .GAT format
  2792. *----------------------------------*/
  2793. int map_readgat (struct map_data* m)
  2794. {
  2795. char filename[256];
  2796. uint8* gat;
  2797. int water_height;
  2798. size_t xy, off, num_cells;
  2799. sprintf(filename, "data\\%s.gat", m->name);
  2800. gat = (uint8 *) grfio_read(filename);
  2801. if (gat == NULL)
  2802. return 0;
  2803. m->xs = *(int32*)(gat+6);
  2804. m->ys = *(int32*)(gat+10);
  2805. num_cells = m->xs * m->ys;
  2806. CREATE(m->cell, struct mapcell, num_cells);
  2807. water_height = map_waterheight(m->name);
  2808. // Set cell properties
  2809. off = 14;
  2810. for( xy = 0; xy < num_cells; ++xy )
  2811. {
  2812. // read cell data
  2813. float height = *(float*)( gat + off );
  2814. uint32 type = *(uint32*)( gat + off + 16 );
  2815. off += 20;
  2816. if( type == 0 && water_height != NO_WATER && height > water_height )
  2817. type = 3; // Cell is 0 (walkable) but under water level, set to 3 (walkable water)
  2818. m->cell[xy] = map_gat2cell(type);
  2819. }
  2820. aFree(gat);
  2821. return 1;
  2822. }
  2823. /*======================================
  2824. * Add/Remove map to the map_db
  2825. *--------------------------------------*/
  2826. void map_addmap2db(struct map_data *m)
  2827. {
  2828. uidb_put(map_db, (unsigned int)m->index, m);
  2829. }
  2830. void map_removemapdb(struct map_data *m)
  2831. {
  2832. uidb_remove(map_db, (unsigned int)m->index);
  2833. }
  2834. /*======================================
  2835. * Initiate maps loading stage
  2836. *--------------------------------------*/
  2837. int map_readallmaps (void)
  2838. {
  2839. int i;
  2840. FILE* fp=NULL;
  2841. int maps_removed = 0;
  2842. // Has the uncompressed gat data of all maps, so just one allocation has to be made
  2843. char *map_cache_buffer[2] = {
  2844. NULL,
  2845. NULL
  2846. };
  2847. char map_cache_decode_buffer[MAX_MAP_SIZE];
  2848. if( enable_grf )
  2849. ShowStatus("Loading maps (using GRF files)...\n");
  2850. else {
  2851. char* mapcachefilepath[] = {
  2852. "db/"DBPATH"map_cache.dat",
  2853. "db/import/map_cache.dat"
  2854. };
  2855. for( i = 0; i < 2; i++ ){
  2856. ShowStatus( "Loading maps (using %s as map cache)...\n", mapcachefilepath[i] );
  2857. if( ( fp = fopen(mapcachefilepath[i], "rb") ) == NULL ){
  2858. if( i == 0 ){
  2859. ShowFatalError( "Unable to open map cache file "CL_WHITE"%s"CL_RESET"\n", mapcachefilepath[i] );
  2860. exit(EXIT_FAILURE); //No use launching server if maps can't be read.
  2861. }else{
  2862. ShowWarning( "Unable to open map cache file "CL_WHITE"%s"CL_RESET"\n", mapcachefilepath[i] );
  2863. break;
  2864. }
  2865. }
  2866. // Init mapcache data. [Shinryo]
  2867. map_cache_buffer[i] = map_init_mapcache(fp);
  2868. if( !map_cache_buffer[i] ) {
  2869. ShowFatalError( "Failed to initialize mapcache data (%s)..\n", mapcachefilepath );
  2870. exit(EXIT_FAILURE);
  2871. }
  2872. fclose(fp);
  2873. }
  2874. }
  2875. for(i = 0; i < map_num; i++) {
  2876. size_t size;
  2877. bool success = false;
  2878. unsigned short idx = 0;
  2879. if( enable_grf ){
  2880. // show progress
  2881. ShowStatus("Loading maps [%i/%i]: %s"CL_CLL"\r", i, map_num, map[i].name);
  2882. // try to load the map
  2883. success = map_readgat(&map[i]) != 0;
  2884. }else{
  2885. // try to load the map
  2886. // Read from import first, in case of override
  2887. if( map_cache_buffer[1] != NULL ){
  2888. success = map_readfromcache( &map[i], map_cache_buffer[1], map_cache_decode_buffer ) != 0;
  2889. }
  2890. // Nothing was found in import - try to find it in the main file
  2891. if( !success ){
  2892. success = map_readfromcache( &map[i], map_cache_buffer[0], map_cache_decode_buffer ) != 0;
  2893. }
  2894. }
  2895. // The map was not found - remove it
  2896. if( !(idx = mapindex_name2id(map[i].name)) || !success ){
  2897. map_delmapid(i);
  2898. maps_removed++;
  2899. i--;
  2900. continue;
  2901. }
  2902. map[i].index = idx;
  2903. if (uidb_get(map_db,(unsigned int)map[i].index) != NULL)
  2904. {
  2905. ShowWarning("Map %s already loaded!"CL_CLL"\n", map[i].name);
  2906. if (map[i].cell) {
  2907. aFree(map[i].cell);
  2908. map[i].cell = NULL;
  2909. }
  2910. map_delmapid(i);
  2911. maps_removed++;
  2912. i--;
  2913. continue;
  2914. }
  2915. map_addmap2db(&map[i]);
  2916. map[i].m = i;
  2917. memset(map[i].moblist, 0, sizeof(map[i].moblist)); //Initialize moblist [Skotlex]
  2918. map[i].mob_delete_timer = INVALID_TIMER; //Initialize timer [Skotlex]
  2919. map[i].bxs = (map[i].xs + BLOCK_SIZE - 1) / BLOCK_SIZE;
  2920. map[i].bys = (map[i].ys + BLOCK_SIZE - 1) / BLOCK_SIZE;
  2921. size = map[i].bxs * map[i].bys * sizeof(struct block_list*);
  2922. map[i].block = (struct block_list**)aCalloc(size, 1);
  2923. map[i].block_mob = (struct block_list**)aCalloc(size, 1);
  2924. }
  2925. // intialization and configuration-dependent adjustments of mapflags
  2926. map_flags_init();
  2927. if( !enable_grf ) {
  2928. // The cache isn't needed anymore, so free it. [Shinryo]
  2929. if( map_cache_buffer[1] != NULL ){
  2930. aFree(map_cache_buffer[1]);
  2931. }
  2932. aFree(map_cache_buffer[0]);
  2933. }
  2934. // finished map loading
  2935. ShowInfo("Successfully loaded '"CL_WHITE"%d"CL_RESET"' maps."CL_CLL"\n",map_num);
  2936. instance_start = map_num; // Next Map Index will be instances
  2937. if (maps_removed)
  2938. ShowNotice("Maps removed: '"CL_WHITE"%d"CL_RESET"'\n",maps_removed);
  2939. return 0;
  2940. }
  2941. ////////////////////////////////////////////////////////////////////////
  2942. static int map_ip_set = 0;
  2943. static int char_ip_set = 0;
  2944. /*==========================================
  2945. * Console Command Parser [Wizputer]
  2946. *------------------------------------------*/
  2947. int parse_console(const char* buf){
  2948. char type[64];
  2949. char command[64];
  2950. char mapname[64];
  2951. int16 x = 0;
  2952. int16 y = 0;
  2953. int16 m;
  2954. int n;
  2955. struct map_session_data sd;
  2956. memset(&sd, 0, sizeof(struct map_session_data));
  2957. strcpy(sd.status.name, "console");
  2958. if( ( n = sscanf(buf, "%63[^:]:%63[^:]:%63s %hd %hd[^\n]", type, command, mapname, &x, &y) ) < 5 ){
  2959. if( ( n = sscanf(buf, "%63[^:]:%63[^\n]", type, command) ) < 2 ) {
  2960. if((n = sscanf(buf, "%63[^\n]", type))<1) return -1; //nothing to do no arg
  2961. }
  2962. }
  2963. if( n != 5 ){ //end string and display
  2964. if( n < 2 ) {
  2965. ShowNotice("Type of command: '%s'\n", type);
  2966. command[0] = '\0';
  2967. mapname[0] = '\0';
  2968. }
  2969. else {
  2970. ShowNotice("Type of command: '%s' || Command: '%s'\n", type, command);
  2971. mapname[0] = '\0';
  2972. }
  2973. }
  2974. else
  2975. ShowNotice("Type of command: '%s' || Command: '%s' || Map: '%s' Coords: %d %d\n", type, command, mapname, x, y);
  2976. if(strcmpi("admin",type) == 0 ) {
  2977. if(strcmpi("map",command) == 0){
  2978. m = map_mapname2mapid(mapname);
  2979. if( m < 0 ){
  2980. ShowWarning("Console: Unknown map.\n");
  2981. return 0;
  2982. }
  2983. sd.bl.m = m;
  2984. map_search_freecell(&sd.bl, m, &sd.bl.x, &sd.bl.y, -1, -1, 0);
  2985. if( x > 0 )
  2986. sd.bl.x = x;
  2987. if( y > 0 )
  2988. sd.bl.y = y;
  2989. ShowNotice("Now at: '%s' Coords: %d %d\n", mapname, x, y);
  2990. }
  2991. else if( !is_atcommand(sd.fd, &sd, command, 2) )
  2992. ShowInfo("Console: Invalid atcommand.\n");
  2993. }
  2994. else if( n == 2 && strcmpi("server", type) == 0 ){
  2995. if( strcmpi("shutdown", command) == 0 || strcmpi("exit", command) == 0 || strcmpi("quit", command) == 0 ){
  2996. runflag = 0;
  2997. }
  2998. }
  2999. else if( strcmpi("ers_report", type) == 0 ){
  3000. ers_report();
  3001. }
  3002. else if( strcmpi("help", type) == 0 ) {
  3003. ShowInfo("Available commands:\n");
  3004. ShowInfo("\t admin:@<atcommand> => Uses an atcommand. Do NOT use commands requiring an attached player.\n");
  3005. ShowInfo("\t admin:map:<map> <x> <y> => Changes the map from which console commands are executed.\n");
  3006. ShowInfo("\t server:shutdown => Stops the server.\n");
  3007. ShowInfo("\t ers_report => Displays database usage.\n");
  3008. }
  3009. return 0;
  3010. }
  3011. /*==========================================
  3012. * Read map server configuration files (conf/map_athena.conf...)
  3013. *------------------------------------------*/
  3014. int map_config_read(char *cfgName)
  3015. {
  3016. char line[1024], w1[32], w2[1024];
  3017. FILE *fp;
  3018. fp = fopen(cfgName,"r");
  3019. if( fp == NULL )
  3020. {
  3021. ShowError("Map configuration file not found at: %s\n", cfgName);
  3022. return 1;
  3023. }
  3024. while( fgets(line, sizeof(line), fp) )
  3025. {
  3026. char* ptr;
  3027. if( line[0] == '/' && line[1] == '/' )
  3028. continue;
  3029. if( (ptr = strstr(line, "//")) != NULL )
  3030. *ptr = '\n'; //Strip comments
  3031. if( sscanf(line, "%31[^:]: %1023[^\t\r\n]", w1, w2) < 2 )
  3032. continue;
  3033. //Strip trailing spaces
  3034. ptr = w2 + strlen(w2);
  3035. while (--ptr >= w2 && *ptr == ' ');
  3036. ptr++;
  3037. *ptr = '\0';
  3038. if(strcmpi(w1,"timestamp_format")==0)
  3039. safestrncpy(timestamp_format, w2, 20);
  3040. else if(strcmpi(w1,"stdout_with_ansisequence")==0)
  3041. stdout_with_ansisequence = config_switch(w2);
  3042. else if(strcmpi(w1,"console_silent")==0) {
  3043. msg_silent = atoi(w2);
  3044. if( msg_silent ) // only bother if its actually enabled
  3045. ShowInfo("Console Silent Setting: %d\n", atoi(w2));
  3046. } else if (strcmpi(w1, "userid")==0)
  3047. chrif_setuserid(w2);
  3048. else if (strcmpi(w1, "passwd") == 0)
  3049. chrif_setpasswd(w2);
  3050. else if (strcmpi(w1, "char_ip") == 0)
  3051. char_ip_set = chrif_setip(w2);
  3052. else if (strcmpi(w1, "char_port") == 0)
  3053. chrif_setport(atoi(w2));
  3054. else if (strcmpi(w1, "map_ip") == 0)
  3055. map_ip_set = clif_setip(w2);
  3056. else if (strcmpi(w1, "bind_ip") == 0)
  3057. clif_setbindip(w2);
  3058. else if (strcmpi(w1, "map_port") == 0) {
  3059. clif_setport(atoi(w2));
  3060. map_port = (atoi(w2));
  3061. } else if (strcmpi(w1, "map") == 0)
  3062. map_addmap(w2);
  3063. else if (strcmpi(w1, "delmap") == 0)
  3064. map_delmap(w2);
  3065. else if (strcmpi(w1, "npc") == 0)
  3066. npc_addsrcfile(w2);
  3067. else if (strcmpi(w1, "delnpc") == 0)
  3068. npc_delsrcfile(w2);
  3069. else if (strcmpi(w1, "autosave_time") == 0) {
  3070. autosave_interval = atoi(w2);
  3071. if (autosave_interval < 1) //Revert to default saving.
  3072. autosave_interval = DEFAULT_AUTOSAVE_INTERVAL;
  3073. else
  3074. autosave_interval *= 1000; //Pass from sec to ms
  3075. } else if (strcmpi(w1, "minsave_time") == 0) {
  3076. minsave_interval= atoi(w2);
  3077. if (minsave_interval < 1)
  3078. minsave_interval = 1;
  3079. } else if (strcmpi(w1, "save_settings") == 0)
  3080. save_settings = cap_value(atoi(w2),CHARSAVE_NONE,CHARSAVE_ALL);
  3081. else if (strcmpi(w1, "motd_txt") == 0)
  3082. strcpy(motd_txt, w2);
  3083. else if (strcmpi(w1, "help_txt") == 0)
  3084. strcpy(help_txt, w2);
  3085. else if (strcmpi(w1, "help2_txt") == 0)
  3086. strcpy(help2_txt, w2);
  3087. else if (strcmpi(w1, "charhelp_txt") == 0)
  3088. strcpy(charhelp_txt, w2);
  3089. else if(strcmpi(w1,"db_path") == 0)
  3090. safestrncpy(db_path,w2,ARRAYLENGTH(db_path));
  3091. else if (strcmpi(w1, "console") == 0) {
  3092. console = config_switch(w2);
  3093. if (console)
  3094. ShowNotice("Console Commands are enabled.\n");
  3095. } else if (strcmpi(w1, "enable_spy") == 0)
  3096. enable_spy = config_switch(w2);
  3097. else if (strcmpi(w1, "use_grf") == 0)
  3098. enable_grf = config_switch(w2);
  3099. else if (strcmpi(w1, "console_msg_log") == 0)
  3100. console_msg_log = atoi(w2);//[Ind]
  3101. else if (strcmpi(w1, "import") == 0)
  3102. map_config_read(w2);
  3103. else
  3104. ShowWarning("Unknown setting '%s' in file %s\n", w1, cfgName);
  3105. }
  3106. fclose(fp);
  3107. return 0;
  3108. }
  3109. void map_reloadnpc_sub(char *cfgName)
  3110. {
  3111. char line[1024], w1[1024], w2[1024];
  3112. FILE *fp;
  3113. fp = fopen(cfgName,"r");
  3114. if( fp == NULL )
  3115. {
  3116. ShowError("Map configuration file not found at: %s\n", cfgName);
  3117. return;
  3118. }
  3119. while( fgets(line, sizeof(line), fp) )
  3120. {
  3121. char* ptr;
  3122. if( line[0] == '/' && line[1] == '/' )
  3123. continue;
  3124. if( (ptr = strstr(line, "//")) != NULL )
  3125. *ptr = '\n'; //Strip comments
  3126. if( sscanf(line, "%1023[^:]: %1023[^\t\r\n]", w1, w2) < 2 )
  3127. continue;
  3128. //Strip trailing spaces
  3129. ptr = w2 + strlen(w2);
  3130. while (--ptr >= w2 && *ptr == ' ');
  3131. ptr++;
  3132. *ptr = '\0';
  3133. if (strcmpi(w1, "npc") == 0)
  3134. npc_addsrcfile(w2);
  3135. else if (strcmpi(w1, "delnpc") == 0)
  3136. npc_delsrcfile(w2);
  3137. else if (strcmpi(w1, "import") == 0)
  3138. map_reloadnpc_sub(w2);
  3139. else
  3140. ShowWarning("Unknown setting '%s' in file %s\n", w1, cfgName);
  3141. }
  3142. fclose(fp);
  3143. }
  3144. void map_reloadnpc(bool clear)
  3145. {
  3146. if (clear)
  3147. npc_addsrcfile("clear"); // this will clear the current script list
  3148. #ifdef RENEWAL
  3149. map_reloadnpc_sub("npc/re/scripts_main.conf");
  3150. #else
  3151. map_reloadnpc_sub("npc/pre-re/scripts_main.conf");
  3152. #endif
  3153. }
  3154. int inter_config_read(char *cfgName)
  3155. {
  3156. char line[1024],w1[1024],w2[1024];
  3157. FILE *fp;
  3158. fp=fopen(cfgName,"r");
  3159. if(fp==NULL){
  3160. ShowError("File not found: %s\n",cfgName);
  3161. return 1;
  3162. }
  3163. while(fgets(line, sizeof(line), fp))
  3164. {
  3165. if(line[0] == '/' && line[1] == '/')
  3166. continue;
  3167. if( sscanf(line,"%1023[^:]: %1023[^\r\n]",w1,w2) < 2 )
  3168. continue;
  3169. if( strcmpi( w1, "buyingstore_db" ) == 0 )
  3170. strcpy( buyingstores_db, w2 );
  3171. else if( strcmpi( w1, "buyingstore_items_db" ) == 0 )
  3172. strcpy( buyingstore_items_db, w2 );
  3173. else if(strcmpi(w1,"item_db_db")==0)
  3174. strcpy(item_db_db,w2);
  3175. else if(strcmpi(w1,"item_db2_db")==0)
  3176. strcpy(item_db2_db,w2);
  3177. else if(strcmpi(w1,"item_db_re_db")==0)
  3178. strcpy(item_db_re_db,w2);
  3179. else if(strcmpi(w1,"mob_db_db")==0)
  3180. strcpy(mob_db_db,w2);
  3181. else if(strcmpi(w1,"mob_db_re_db")==0)
  3182. strcpy(mob_db_re_db,w2);
  3183. else if(strcmpi(w1,"mob_db2_db")==0)
  3184. strcpy(mob_db2_db,w2);
  3185. else if(strcmpi(w1,"mob_skill_db_db")==0)
  3186. strcpy(mob_skill_db_db,w2);
  3187. else if(strcmpi(w1,"mob_skill_db_re_db")==0)
  3188. strcpy(mob_skill_db_re_db,w2);
  3189. else if(strcmpi(w1,"mob_skill_db2_db")==0)
  3190. strcpy(mob_skill_db2_db,w2);
  3191. else if( strcmpi( w1, "item_cash_db_db" ) == 0 )
  3192. strcpy( item_cash_db_db, w2 );
  3193. else if( strcmpi( w1, "item_cash_db2_db" ) == 0 )
  3194. strcpy( item_cash_db2_db, w2 );
  3195. else if( strcmpi( w1, "vending_db" ) == 0 )
  3196. strcpy( vendings_db, w2 );
  3197. else if( strcmpi( w1, "vending_items_db" ) == 0 )
  3198. strcpy( vending_items_db, w2 );
  3199. else
  3200. //Map Server SQL DB
  3201. if(strcmpi(w1,"map_server_ip")==0)
  3202. strcpy(map_server_ip, w2);
  3203. else
  3204. if(strcmpi(w1,"map_server_port")==0)
  3205. map_server_port=atoi(w2);
  3206. else
  3207. if(strcmpi(w1,"map_server_id")==0)
  3208. strcpy(map_server_id, w2);
  3209. else
  3210. if(strcmpi(w1,"map_server_pw")==0)
  3211. strcpy(map_server_pw, w2);
  3212. else
  3213. if(strcmpi(w1,"map_server_db")==0)
  3214. strcpy(map_server_db, w2);
  3215. else
  3216. if(strcmpi(w1,"default_codepage")==0)
  3217. strcpy(default_codepage, w2);
  3218. else
  3219. if(strcmpi(w1,"use_sql_db")==0) {
  3220. db_use_sqldbs = config_switch(w2);
  3221. ShowStatus ("Using SQL dbs: %s\n",w2);
  3222. } else
  3223. if(strcmpi(w1,"log_db_ip")==0)
  3224. strcpy(log_db_ip, w2);
  3225. else
  3226. if(strcmpi(w1,"log_db_id")==0)
  3227. strcpy(log_db_id, w2);
  3228. else
  3229. if(strcmpi(w1,"log_db_pw")==0)
  3230. strcpy(log_db_pw, w2);
  3231. else
  3232. if(strcmpi(w1,"log_db_port")==0)
  3233. log_db_port = atoi(w2);
  3234. else
  3235. if(strcmpi(w1,"log_db_db")==0)
  3236. strcpy(log_db_db, w2);
  3237. else
  3238. if( mapreg_config_read(w1,w2) )
  3239. continue;
  3240. //support the import command, just like any other config
  3241. else
  3242. if(strcmpi(w1,"import")==0)
  3243. inter_config_read(w2);
  3244. }
  3245. fclose(fp);
  3246. return 0;
  3247. }
  3248. /*=======================================
  3249. * MySQL Init
  3250. *---------------------------------------*/
  3251. int map_sql_init(void)
  3252. {
  3253. // main db connection
  3254. mmysql_handle = Sql_Malloc();
  3255. qsmysql_handle = Sql_Malloc();
  3256. ShowInfo("Connecting to the Map DB Server....\n");
  3257. if( SQL_ERROR == Sql_Connect(mmysql_handle, map_server_id, map_server_pw, map_server_ip, map_server_port, map_server_db) ||
  3258. SQL_ERROR == Sql_Connect(qsmysql_handle, map_server_id, map_server_pw, map_server_ip, map_server_port, map_server_db) )
  3259. {
  3260. ShowError("Couldn't connect with uname='%s',passwd='%s',host='%s',port='%d',database='%s'\n",
  3261. map_server_id, map_server_pw, map_server_ip, map_server_port, map_server_db);
  3262. Sql_ShowDebug(mmysql_handle);
  3263. Sql_Free(mmysql_handle);
  3264. Sql_ShowDebug(qsmysql_handle);
  3265. Sql_Free(qsmysql_handle);
  3266. exit(EXIT_FAILURE);
  3267. }
  3268. ShowStatus("Connect success! (Map Server Connection)\n");
  3269. if( strlen(default_codepage) > 0 ) {
  3270. if ( SQL_ERROR == Sql_SetEncoding(mmysql_handle, default_codepage) )
  3271. Sql_ShowDebug(mmysql_handle);
  3272. if ( SQL_ERROR == Sql_SetEncoding(qsmysql_handle, default_codepage) )
  3273. Sql_ShowDebug(qsmysql_handle);
  3274. }
  3275. return 0;
  3276. }
  3277. int map_sql_close(void)
  3278. {
  3279. ShowStatus("Close Map DB Connection....\n");
  3280. Sql_Free(mmysql_handle);
  3281. Sql_Free(qsmysql_handle);
  3282. mmysql_handle = NULL;
  3283. qsmysql_handle = NULL;
  3284. #ifndef BETA_THREAD_TEST
  3285. if (log_config.sql_logs)
  3286. {
  3287. ShowStatus("Close Log DB Connection....\n");
  3288. Sql_Free(logmysql_handle);
  3289. logmysql_handle = NULL;
  3290. }
  3291. #endif
  3292. return 0;
  3293. }
  3294. int log_sql_init(void)
  3295. {
  3296. #ifndef BETA_THREAD_TEST
  3297. // log db connection
  3298. logmysql_handle = Sql_Malloc();
  3299. ShowInfo(""CL_WHITE"[SQL]"CL_RESET": Connecting to the Log Database "CL_WHITE"%s"CL_RESET" At "CL_WHITE"%s"CL_RESET"...\n",log_db_db,log_db_ip);
  3300. if ( SQL_ERROR == Sql_Connect(logmysql_handle, log_db_id, log_db_pw, log_db_ip, log_db_port, log_db_db) ){
  3301. ShowError("Couldn't connect with uname='%s',passwd='%s',host='%s',port='%d',database='%s'\n",
  3302. log_db_id, log_db_pw, log_db_ip, log_db_port, log_db_db);
  3303. Sql_ShowDebug(logmysql_handle);
  3304. Sql_Free(logmysql_handle);
  3305. exit(EXIT_FAILURE);
  3306. }
  3307. ShowStatus(""CL_WHITE"[SQL]"CL_RESET": Successfully '"CL_GREEN"connected"CL_RESET"' to Database '"CL_WHITE"%s"CL_RESET"'.\n", log_db_db);
  3308. if( strlen(default_codepage) > 0 )
  3309. if ( SQL_ERROR == Sql_SetEncoding(logmysql_handle, default_codepage) )
  3310. Sql_ShowDebug(logmysql_handle);
  3311. #endif
  3312. return 0;
  3313. }
  3314. void map_add_questinfo(int m, struct questinfo *qi) {
  3315. unsigned short i;
  3316. /* duplicate, override */
  3317. for(i = 0; i < map[m].qi_count; i++) {
  3318. if( map[m].qi_data[i].nd == qi->nd )
  3319. break;
  3320. }
  3321. if( i == map[m].qi_count )
  3322. RECREATE(map[m].qi_data, struct questinfo, ++map[m].qi_count);
  3323. memcpy(&map[m].qi_data[i], qi, sizeof(struct questinfo));
  3324. }
  3325. bool map_remove_questinfo(int m, struct npc_data *nd) {
  3326. unsigned short i;
  3327. for(i = 0; i < map[m].qi_count; i++) {
  3328. struct questinfo *qi = &map[m].qi_data[i];
  3329. if( qi->nd == nd ) {
  3330. memset(&map[m].qi_data[i], 0, sizeof(struct questinfo));
  3331. if( i != --map[m].qi_count )
  3332. memmove(&map[m].qi_data[i],&map[m].qi_data[i+1],sizeof(struct questinfo)*(map[m].qi_count-i));
  3333. return true;
  3334. }
  3335. }
  3336. return false;
  3337. }
  3338. /**
  3339. * @see DBApply
  3340. */
  3341. int map_db_final(DBKey key, DBData *data, va_list ap)
  3342. {
  3343. struct map_data_other_server *mdos = db_data2ptr(data);
  3344. if(mdos && mdos->cell == NULL)
  3345. aFree(mdos);
  3346. return 0;
  3347. }
  3348. /**
  3349. * @see DBApply
  3350. */
  3351. int nick_db_final(DBKey key, DBData *data, va_list args)
  3352. {
  3353. struct charid2nick* p = db_data2ptr(data);
  3354. struct charid_request* req;
  3355. if( p == NULL )
  3356. return 0;
  3357. while( p->requests )
  3358. {
  3359. req = p->requests;
  3360. p->requests = req->next;
  3361. aFree(req);
  3362. }
  3363. aFree(p);
  3364. return 0;
  3365. }
  3366. int cleanup_sub(struct block_list *bl, va_list ap)
  3367. {
  3368. nullpo_ret(bl);
  3369. switch(bl->type) {
  3370. case BL_PC:
  3371. map_quit((struct map_session_data *) bl);
  3372. break;
  3373. case BL_NPC:
  3374. npc_unload((struct npc_data *)bl,false);
  3375. break;
  3376. case BL_MOB:
  3377. unit_free(bl,CLR_OUTSIGHT);
  3378. break;
  3379. case BL_PET:
  3380. //There is no need for this, the pet is removed together with the player. [Skotlex]
  3381. break;
  3382. case BL_ITEM:
  3383. map_clearflooritem(bl);
  3384. break;
  3385. case BL_SKILL:
  3386. skill_delunit((struct skill_unit *) bl);
  3387. break;
  3388. }
  3389. return 1;
  3390. }
  3391. #ifdef ADJUST_SKILL_DAMAGE
  3392. /**
  3393. * Free all skill damage entries for a map
  3394. * @param m Map data
  3395. **/
  3396. void map_skill_damage_free(struct map_data *m) {
  3397. uint8 i;
  3398. for (i = 0; i < m->skill_damage.count; i++) {
  3399. ers_free(map_skill_damage_ers, m->skill_damage.entries[i]);
  3400. m->skill_damage.entries[i] = NULL;
  3401. }
  3402. aFree(m->skill_damage.entries);
  3403. m->skill_damage.entries = NULL;
  3404. m->skill_damage.count = 0;
  3405. }
  3406. /**
  3407. * Add new skill damage adjustment entry for a map
  3408. * @param m Map data
  3409. * @param skill_id Skill
  3410. * @param pc Rate to PC
  3411. * @param mobs Rate to Monster
  3412. * @param boss Rate to Boss-monster
  3413. * @param other Rate to Other target
  3414. * @param caster Caster type
  3415. **/
  3416. void map_skill_damage_add(struct map_data *m, uint16 skill_id, int pc, int mob, int boss, int other, uint8 caster) {
  3417. struct s_skill_damage *entry;
  3418. int i = 0;
  3419. if (m->skill_damage.count >= UINT8_MAX)
  3420. return;
  3421. for (i = 0; i < m->skill_damage.count; i++) {
  3422. if (m->skill_damage.entries[i]->skill_id == skill_id) {
  3423. m->skill_damage.entries[i]->pc = pc;
  3424. m->skill_damage.entries[i]->mob = mob;
  3425. m->skill_damage.entries[i]->boss = boss;
  3426. m->skill_damage.entries[i]->other = other;
  3427. m->skill_damage.entries[i]->caster = caster;
  3428. return;
  3429. }
  3430. }
  3431. entry = ers_alloc(map_skill_damage_ers, struct s_skill_damage);
  3432. entry->skill_id = skill_id;
  3433. entry->pc = pc;
  3434. entry->mob = mob;
  3435. entry->boss = boss;
  3436. entry->other = other;
  3437. entry->caster = caster;
  3438. RECREATE(m->skill_damage.entries, struct s_skill_damage *, m->skill_damage.count+1);
  3439. m->skill_damage.entries[m->skill_damage.count++] = entry;
  3440. }
  3441. #endif
  3442. /**
  3443. * @see DBApply
  3444. */
  3445. static int cleanup_db_sub(DBKey key, DBData *data, va_list va)
  3446. {
  3447. return cleanup_sub(db_data2ptr(data), va);
  3448. }
  3449. /*==========================================
  3450. * map destructor
  3451. *------------------------------------------*/
  3452. void do_final(void)
  3453. {
  3454. int i, j;
  3455. struct map_session_data* sd;
  3456. struct s_mapiterator* iter;
  3457. ShowStatus("Terminating...\n");
  3458. channel_config.closing = true;
  3459. //Ladies and babies first.
  3460. iter = mapit_getallusers();
  3461. for( sd = (TBL_PC*)mapit_first(iter); mapit_exists(iter); sd = (TBL_PC*)mapit_next(iter) )
  3462. map_quit(sd);
  3463. mapit_free(iter);
  3464. /* prepares npcs for a faster shutdown process */
  3465. do_clear_npc();
  3466. // remove all objects on maps
  3467. for (i = 0; i < map_num; i++) {
  3468. ShowStatus("Cleaning up maps [%d/%d]: %s..."CL_CLL"\r", i+1, map_num, map[i].name);
  3469. if (map[i].m >= 0) {
  3470. map_foreachinmap(cleanup_sub, i, BL_ALL);
  3471. channel_delete(map[i].channel);
  3472. }
  3473. }
  3474. ShowStatus("Cleaned up %d maps."CL_CLL"\n", map_num);
  3475. id_db->foreach(id_db,cleanup_db_sub);
  3476. chrif_char_reset_offline();
  3477. chrif_flush_fifo();
  3478. do_final_atcommand();
  3479. do_final_battle();
  3480. do_final_chrif();
  3481. do_final_clif();
  3482. do_final_npc();
  3483. do_final_quest();
  3484. do_final_script();
  3485. do_final_instance();
  3486. do_final_itemdb();
  3487. do_final_storage();
  3488. do_final_guild();
  3489. do_final_party();
  3490. do_final_pc();
  3491. do_final_pet();
  3492. do_final_homunculus();
  3493. do_final_mercenary();
  3494. do_final_mob();
  3495. do_final_msg();
  3496. do_final_skill();
  3497. do_final_status();
  3498. do_final_unit();
  3499. do_final_battleground();
  3500. do_final_duel();
  3501. do_final_elemental();
  3502. do_final_cashshop();
  3503. do_final_channel(); //should be called after final guild
  3504. do_final_vending();
  3505. do_final_buyingstore();
  3506. map_db->destroy(map_db, map_db_final);
  3507. for (i=0; i<map_num; i++) {
  3508. if(map[i].cell) aFree(map[i].cell);
  3509. if(map[i].block) aFree(map[i].block);
  3510. if(map[i].block_mob) aFree(map[i].block_mob);
  3511. if(map[i].qi_data) aFree(map[i].qi_data);
  3512. if(battle_config.dynamic_mobs) { //Dynamic mobs flag by [random]
  3513. if(map[i].mob_delete_timer != INVALID_TIMER)
  3514. delete_timer(map[i].mob_delete_timer, map_removemobs_timer);
  3515. for (j=0; j<MAX_MOB_LIST_PER_MAP; j++)
  3516. if (map[i].moblist[j]) aFree(map[i].moblist[j]);
  3517. }
  3518. #ifdef ADJUST_SKILL_DAMAGE
  3519. if (map[i].skill_damage.count)
  3520. map_skill_damage_free(&map[i]);
  3521. #endif
  3522. }
  3523. mapindex_final();
  3524. if(enable_grf)
  3525. grfio_final();
  3526. id_db->destroy(id_db, NULL);
  3527. pc_db->destroy(pc_db, NULL);
  3528. mobid_db->destroy(mobid_db, NULL);
  3529. bossid_db->destroy(bossid_db, NULL);
  3530. nick_db->destroy(nick_db, nick_db_final);
  3531. charid_db->destroy(charid_db, NULL);
  3532. iwall_db->destroy(iwall_db, NULL);
  3533. regen_db->destroy(regen_db, NULL);
  3534. #ifdef ADJUST_SKILL_DAMAGE
  3535. ers_destroy(map_skill_damage_ers);
  3536. #endif
  3537. map_sql_close();
  3538. ShowStatus("Finished.\n");
  3539. }
  3540. static int map_abort_sub(struct map_session_data* sd, va_list ap)
  3541. {
  3542. chrif_save(sd,1);
  3543. return 1;
  3544. }
  3545. //------------------------------
  3546. // Function called when the server
  3547. // has received a crash signal.
  3548. //------------------------------
  3549. void do_abort(void)
  3550. {
  3551. static int run = 0;
  3552. //Save all characters and then flush the inter-connection.
  3553. if (run) {
  3554. ShowFatalError("Server has crashed while trying to save characters. Character data can't be saved!\n");
  3555. return;
  3556. }
  3557. run = 1;
  3558. if (!chrif_isconnected())
  3559. {
  3560. if (pc_db->size(pc_db))
  3561. ShowFatalError("Server has crashed without a connection to the char-server, %u characters can't be saved!\n", pc_db->size(pc_db));
  3562. return;
  3563. }
  3564. ShowError("Server received crash signal! Attempting to save all online characters!\n");
  3565. map_foreachpc(map_abort_sub);
  3566. chrif_flush_fifo();
  3567. }
  3568. /*======================================================
  3569. * Map-Server help options screen
  3570. *------------------------------------------------------*/
  3571. void display_helpscreen(bool do_exit)
  3572. {
  3573. ShowInfo("Usage: %s [options]\n", SERVER_NAME);
  3574. ShowInfo("\n");
  3575. ShowInfo("Options:\n");
  3576. ShowInfo(" -?, -h [--help]\t\tDisplays this help screen.\n");
  3577. ShowInfo(" -v [--version]\t\tDisplays the server's version.\n");
  3578. ShowInfo(" --run-once\t\t\tCloses server after loading (testing).\n");
  3579. ShowInfo(" --map-config <file>\t\tAlternative map-server configuration.\n");
  3580. ShowInfo(" --battle-config <file>\tAlternative battle configuration.\n");
  3581. ShowInfo(" --atcommand-config <file>\tAlternative atcommand configuration.\n");
  3582. ShowInfo(" --script-config <file>\tAlternative script configuration.\n");
  3583. ShowInfo(" --msg-config <file>\t\tAlternative message configuration.\n");
  3584. ShowInfo(" --grf-path <file>\t\tAlternative GRF path configuration.\n");
  3585. ShowInfo(" --inter-config <file>\t\tAlternative inter-server configuration.\n");
  3586. ShowInfo(" --log-config <file>\t\tAlternative logging configuration.\n");
  3587. if( do_exit )
  3588. exit(EXIT_SUCCESS);
  3589. }
  3590. /*======================================================
  3591. * Map-Server Init and Command-line Arguments [Valaris]
  3592. *------------------------------------------------------*/
  3593. void set_server_type(void)
  3594. {
  3595. SERVER_TYPE = ATHENA_SERVER_MAP;
  3596. }
  3597. /*======================================================
  3598. * Message System
  3599. *------------------------------------------------------*/
  3600. struct msg_data {
  3601. char* msg[MAP_MAX_MSG];
  3602. };
  3603. struct msg_data *map_lang2msgdb(uint8 lang){
  3604. return (struct msg_data*)idb_get(map_msg_db, lang);
  3605. }
  3606. void map_do_init_msg(void){
  3607. int test=0, i=0, size;
  3608. char * listelang[] = {
  3609. MSG_CONF_NAME_EN, //default
  3610. MSG_CONF_NAME_RUS,
  3611. MSG_CONF_NAME_SPN,
  3612. MSG_CONF_NAME_GRM,
  3613. MSG_CONF_NAME_CHN,
  3614. MSG_CONF_NAME_MAL,
  3615. MSG_CONF_NAME_IDN,
  3616. MSG_CONF_NAME_FRN,
  3617. MSG_CONF_NAME_POR,
  3618. MSG_CONF_NAME_THA
  3619. };
  3620. map_msg_db = idb_alloc(DB_OPT_BASE);
  3621. size = ARRAYLENGTH(listelang); //avoid recalc
  3622. while(test!=-1 && size>i){ //for all enable lang +(English default)
  3623. test = msg_checklangtype(i,false);
  3624. if(test == 1) msg_config_read(listelang[i],i); //if enabled read it and assign i to langtype
  3625. i++;
  3626. }
  3627. }
  3628. void map_do_final_msg(void){
  3629. DBIterator *iter = db_iterator(map_msg_db);
  3630. struct msg_data *mdb;
  3631. for (mdb = dbi_first(iter); dbi_exists(iter); mdb = dbi_next(iter)) {
  3632. _do_final_msg(MAP_MAX_MSG,mdb->msg);
  3633. aFree(mdb);
  3634. }
  3635. dbi_destroy(iter);
  3636. map_msg_db->destroy(map_msg_db, NULL);
  3637. }
  3638. void map_msg_reload(void){
  3639. map_do_final_msg(); //clear data
  3640. map_do_init_msg();
  3641. }
  3642. int map_msg_config_read(char *cfgName, int lang){
  3643. struct msg_data *mdb;
  3644. if( (mdb = map_lang2msgdb(lang)) == NULL )
  3645. CREATE(mdb, struct msg_data, 1);
  3646. else
  3647. idb_remove(map_msg_db, lang);
  3648. idb_put(map_msg_db, lang, mdb);
  3649. if(_msg_config_read(cfgName,MAP_MAX_MSG,mdb->msg)!=0){ //an error occur
  3650. idb_remove(map_msg_db, lang); //@TRYME
  3651. aFree(mdb);
  3652. }
  3653. return 0;
  3654. }
  3655. const char* map_msg_txt(struct map_session_data *sd, int msg_number){
  3656. struct msg_data *mdb;
  3657. uint8 lang = 0; //default
  3658. if(sd && sd->langtype) lang = sd->langtype;
  3659. if( (mdb = map_lang2msgdb(lang)) != NULL){
  3660. const char *tmp = _msg_txt(msg_number,MAP_MAX_MSG,mdb->msg);
  3661. if(strcmp(tmp,"??")) //to verify result
  3662. return tmp;
  3663. ShowDebug("Message #%d not found for langtype %d.\n",msg_number,lang);
  3664. }
  3665. ShowDebug("Selected langtype %d not loaded, trying fallback...\n",lang);
  3666. if(lang != 0 && (mdb = map_lang2msgdb(0)) != NULL) //fallback
  3667. return _msg_txt(msg_number,MAP_MAX_MSG,mdb->msg);
  3668. return "??";
  3669. }
  3670. /// Called when a terminate signal is received.
  3671. void do_shutdown(void)
  3672. {
  3673. if( runflag != MAPSERVER_ST_SHUTDOWN )
  3674. {
  3675. runflag = MAPSERVER_ST_SHUTDOWN;
  3676. ShowStatus("Shutting down...\n");
  3677. {
  3678. struct map_session_data* sd;
  3679. struct s_mapiterator* iter = mapit_getallusers();
  3680. for( sd = (TBL_PC*)mapit_first(iter); mapit_exists(iter); sd = (TBL_PC*)mapit_next(iter) )
  3681. clif_GM_kick(NULL, sd);
  3682. mapit_free(iter);
  3683. flush_fifos();
  3684. }
  3685. chrif_check_shutdown();
  3686. }
  3687. }
  3688. int do_init(int argc, char *argv[])
  3689. {
  3690. runflag = MAPSERVER_ST_STARTING;
  3691. #ifdef GCOLLECT
  3692. GC_enable_incremental();
  3693. #endif
  3694. INTER_CONF_NAME="conf/inter_athena.conf";
  3695. LOG_CONF_NAME="conf/log_athena.conf";
  3696. MAP_CONF_NAME = "conf/map_athena.conf";
  3697. BATTLE_CONF_FILENAME = "conf/battle_athena.conf";
  3698. ATCOMMAND_CONF_FILENAME = "conf/atcommand_athena.conf";
  3699. SCRIPT_CONF_NAME = "conf/script_athena.conf";
  3700. GRF_PATH_FILENAME = "conf/grf-files.txt";
  3701. /* Multilanguage */
  3702. MSG_CONF_NAME_EN = "conf/msg_conf/map_msg.conf"; // English (default)
  3703. MSG_CONF_NAME_RUS = "conf/msg_conf/map_msg_rus.conf"; // Russian
  3704. MSG_CONF_NAME_SPN = "conf/msg_conf/map_msg_spn.conf"; // Spanish
  3705. MSG_CONF_NAME_GRM = "conf/msg_conf/map_msg_grm.conf"; // German
  3706. MSG_CONF_NAME_CHN = "conf/msg_conf/map_msg_chn.conf"; // Chinese
  3707. MSG_CONF_NAME_MAL = "conf/msg_conf/map_msg_mal.conf"; // Malaysian
  3708. MSG_CONF_NAME_IDN = "conf/msg_conf/map_msg_idn.conf"; // Indonesian
  3709. MSG_CONF_NAME_FRN = "conf/msg_conf/map_msg_frn.conf"; // French
  3710. MSG_CONF_NAME_POR = "conf/msg_conf/map_msg_por.conf"; // Brazilian Portuguese
  3711. MSG_CONF_NAME_THA = "conf/msg_conf/map_msg_tha.conf"; // Thai
  3712. /* Multilanguage */
  3713. // Default map
  3714. safestrncpy(map_default.mapname, "prontera", MAP_NAME_LENGTH);
  3715. map_default.x = 156;
  3716. map_default.y = 191;
  3717. cli_get_options(argc,argv);
  3718. rnd_init();
  3719. map_config_read(MAP_CONF_NAME);
  3720. // loads npcs
  3721. map_reloadnpc(false);
  3722. chrif_checkdefaultlogin();
  3723. if (!map_ip_set || !char_ip_set) {
  3724. char ip_str[16];
  3725. ip2str(addr_[0], ip_str);
  3726. ShowWarning("Not all IP addresses in map_athena.conf configured, autodetecting...\n");
  3727. if (naddr_ == 0)
  3728. ShowError("Unable to determine your IP address...\n");
  3729. else if (naddr_ > 1)
  3730. ShowNotice("Multiple interfaces detected...\n");
  3731. ShowInfo("Defaulting to %s as our IP address\n", ip_str);
  3732. if (!map_ip_set)
  3733. clif_setip(ip_str);
  3734. if (!char_ip_set)
  3735. chrif_setip(ip_str);
  3736. }
  3737. battle_config_read(BATTLE_CONF_FILENAME);
  3738. script_config_read(SCRIPT_CONF_NAME);
  3739. inter_config_read(INTER_CONF_NAME);
  3740. log_config_read(LOG_CONF_NAME);
  3741. id_db = idb_alloc(DB_OPT_BASE);
  3742. pc_db = idb_alloc(DB_OPT_BASE); //Added for reliable map_id2sd() use. [Skotlex]
  3743. mobid_db = idb_alloc(DB_OPT_BASE); //Added to lower the load of the lazy mob ai. [Skotlex]
  3744. bossid_db = idb_alloc(DB_OPT_BASE); // Used for Convex Mirror quick MVP search
  3745. map_db = uidb_alloc(DB_OPT_BASE);
  3746. nick_db = idb_alloc(DB_OPT_BASE);
  3747. charid_db = idb_alloc(DB_OPT_BASE);
  3748. regen_db = idb_alloc(DB_OPT_BASE); // efficient status_natural_heal processing
  3749. iwall_db = strdb_alloc(DB_OPT_RELEASE_DATA,2*NAME_LENGTH+2+1); // [Zephyrus] Invisible Walls
  3750. #ifdef ADJUST_SKILL_DAMAGE
  3751. map_skill_damage_ers = ers_new(sizeof(struct s_skill_damage), "map.c:map_skill_damage_ers", ERS_OPT_NONE);
  3752. #endif
  3753. map_sql_init();
  3754. if (log_config.sql_logs)
  3755. log_sql_init();
  3756. mapindex_init();
  3757. if(enable_grf)
  3758. grfio_init(GRF_PATH_FILENAME);
  3759. map_readallmaps();
  3760. add_timer_func_list(map_freeblock_timer, "map_freeblock_timer");
  3761. add_timer_func_list(map_clearflooritem_timer, "map_clearflooritem_timer");
  3762. add_timer_func_list(map_removemobs_timer, "map_removemobs_timer");
  3763. add_timer_interval(gettick()+1000, map_freeblock_timer, 0, 0, 60*1000);
  3764. map_do_init_msg();
  3765. do_init_atcommand();
  3766. do_init_battle();
  3767. do_init_instance();
  3768. do_init_channel();
  3769. do_init_chrif();
  3770. do_init_clif();
  3771. do_init_script();
  3772. do_init_itemdb();
  3773. do_init_cashshop();
  3774. do_init_skill();
  3775. do_init_mob();
  3776. do_init_pc();
  3777. do_init_status();
  3778. do_init_party();
  3779. do_init_guild();
  3780. do_init_storage();
  3781. do_init_pet();
  3782. do_init_homunculus();
  3783. do_init_mercenary();
  3784. do_init_elemental();
  3785. do_init_quest();
  3786. do_init_npc();
  3787. do_init_unit();
  3788. do_init_battleground();
  3789. do_init_duel();
  3790. do_init_vending();
  3791. do_init_buyingstore();
  3792. npc_event_do_oninit(); // Init npcs (OnInit)
  3793. if (battle_config.pk_mode)
  3794. ShowNotice("Server is running on '"CL_WHITE"PK Mode"CL_RESET"'.\n");
  3795. ShowStatus("Server is '"CL_GREEN"ready"CL_RESET"' and listening on port '"CL_WHITE"%d"CL_RESET"'.\n\n", map_port);
  3796. if( runflag != CORE_ST_STOP )
  3797. {
  3798. shutdown_callback = do_shutdown;
  3799. runflag = MAPSERVER_ST_RUNNING;
  3800. }
  3801. #if defined(BUILDBOT)
  3802. if( buildbotflag )
  3803. exit(EXIT_FAILURE);
  3804. #endif
  3805. if( console ){ //start listening
  3806. add_timer_func_list(parse_console_timer, "parse_console_timer");
  3807. add_timer_interval(gettick()+1000, parse_console_timer, 0, 0, 1000); //start in 1s each 1sec
  3808. }
  3809. return 0;
  3810. }