diff --git a/data/ava2-itemshop/verified-products.json b/data/ava2-itemshop/verified-products.json index 10368965..bdb95d46 100644 --- a/data/ava2-itemshop/verified-products.json +++ b/data/ava2-itemshop/verified-products.json @@ -1,5 +1,5 @@ { - "count": 49, + "count": 57, "scope": "Existing implemented item systems only. Does not authorize production deployment.", "products": [ { @@ -182,6 +182,24 @@ "original_price": 60, "basis": "ported body/hair/mount-skin fixed enchants; game/src/port_costume_attr.cpp and make_items.ENCHANT_KEEP" }, + { + "id": 144, + "vnum": 100001, + "original_price": 9, + "basis": "dragon soul time charge (percent); game/src/char_item.cpp USE_TIME_CHARGE_PER and item.cpp GiveMoreTime_Per" + }, + { + "id": 145, + "vnum": 100002, + "original_price": 17, + "basis": "dragon soul time charge (fixed); game/src/char_item.cpp USE_TIME_CHARGE_FIX and item.cpp GiveMoreTime_Fix" + }, + { + "id": 149, + "vnum": 100500, + "original_price": 4, + "basis": "dragon soul strength refine material (holly bean); game/src/DragonSoul.cpp DSManager::DoRefineStrength" + }, { "id": 170, "vnum": 70002, @@ -295,6 +313,36 @@ "vnum": 54174, "original_price": 60, "basis": "ported body/hair/mount-skin fixed enchants; game/src/port_costume_attr.cpp and make_items.ENCHANT_KEEP" + }, + { + "id": 233, + "vnum": 39063, + "original_price": 19, + "basis": "gaya market refresh item; game/src/port_gaya.cpp and char_item.cpp USE_RESET_GAYA_SHOP" + }, + { + "id": 234, + "vnum": 39064, + "original_price": 19, + "basis": "gaya market slot unlock item; game/src/port_gaya.cpp and char_item.cpp USE_EXPAND_GAYA_SHOP" + }, + { + "id": 240, + "vnum": 77921, + "original_price": 1, + "basis": "copper treasure key for box 77918; game/src/char_item.cpp single-count decrement" + }, + { + "id": 241, + "vnum": 77922, + "original_price": 2, + "basis": "silver treasure key for box 77919; game/src/char_item.cpp single-count decrement" + }, + { + "id": 242, + "vnum": 77923, + "original_price": 5, + "basis": "gold treasure key for box 77920; game/src/char_item.cpp single-count decrement" } ] } diff --git a/src/server/db/src/Ava2ItemShop.cpp b/src/server/db/src/Ava2ItemShop.cpp index da1ac629..6b254686 100644 --- a/src/server/db/src/Ava2ItemShop.cpp +++ b/src/server/db/src/Ava2ItemShop.cpp @@ -82,7 +82,9 @@ void CClientManager::Ava2ItemShop(CPeer* peer,DWORD handle,const char* data,DWOR if(tx.active) { auto owner=query("SELECT account_id FROM player WHERE id="+decimal(r.player)); auto wallet=query("SELECT coins FROM "+adb+".account WHERE id="+aid+" FOR UPDATE"); - if(ok(owner) && owner->Get()->uiNumRows==1 && strtoul(mysql_fetch_row(owner->Get()->pSQLResult)[0],0,10)==r.account && ok(wallet) && wallet->Get()->uiNumRows==1) { + auto dateQ=query("SELECT CURDATE()"); + if(ok(owner) && owner->Get()->uiNumRows==1 && strtoul(mysql_fetch_row(owner->Get()->pSQLResult)[0],0,10)==r.account && ok(wallet) && wallet->Get()->uiNumRows==1 && ok(dateQ) && dateQ->Get()->uiNumRows==1) { + const std::string rewardDay = mysql_fetch_row(dateQ->Get()->pSQLResult)[0]; balance=strtoll(mysql_fetch_row(wallet->Get()->pSQLResult)[0],0,10); auto previous=query("SELECT account_id,vnum,requested,amount FROM port_point_rewards WHERE token='"+std::string(r.token)+"'"); if(ok(previous) && previous->Get()->uiNumRows==1) { @@ -91,13 +93,13 @@ void CClientManager::Ava2ItemShop(CPeer* peer,DWORD handle,const char* data,DWOR } else if(ok(previous)) { if(!rule.eligible(mob->bLevel,r.expectedVnum) || r.countuint32_t(rule.maximum))status=1; else { - auto earned=query("SELECT COALESCE(SUM(amount),0) FROM port_point_rewards WHERE account_id="+aid+" AND reward_day=CURDATE()"); + auto earned=query("SELECT COALESCE(SUM(amount),0) FROM port_point_rewards WHERE account_id="+aid+" AND reward_day='"+rewardDay+"'"); if(ok(earned) && earned->Get()->uiNumRows==1) { granted=PortPointDropAmount(r.count,strtoull(mysql_fetch_row(earned->Get()->pSQLResult)[0],0,10),rule.dailyCap); if(balance<0 || uint64_t(balance)>uint64_t(INT64_MAX)-granted){status=1;granted=0;} else { bool success=run("UPDATE "+adb+".account SET coins=coins+"+decimal(granted)+" WHERE id="+aid); - success=success && run("INSERT INTO port_point_rewards(token,account_id,player_id,vnum,requested,amount,reward_day) VALUES('"+std::string(r.token)+"',"+aid+","+decimal(r.player)+","+decimal(r.product)+","+decimal(r.count)+","+decimal(granted)+",CURDATE())"); + success=success && run("INSERT INTO port_point_rewards(token,account_id,player_id,vnum,requested,amount,reward_day) VALUES('"+std::string(r.token)+"',"+aid+","+decimal(r.player)+","+decimal(r.product)+","+decimal(r.count)+","+decimal(granted)+",'"+rewardDay+"')"); if(success){if(tx.commit()){balance+=granted;status=0;}else status=8;} } } diff --git a/src/server/game/src/Makefile b/src/server/game/src/Makefile index 1e078fe9..3dc95e64 100755 --- a/src/server/game/src/Makefile +++ b/src/server/game/src/Makefile @@ -61,7 +61,7 @@ CPPFILE = BattleArena.cpp FSM.cpp MarkConvert.cpp MarkImage.cpp MarkManager.cpp desc_client.cpp desc_manager.cpp desc_p2p.cpp dev_log.cpp dungeon.cpp empire_text_convert.cpp entity.cpp\ entity_view.cpp event.cpp event_queue.cpp exchange.cpp file_loader.cpp fishing.cpp gm.cpp guild.cpp\ guild_manager.cpp guild_war.cpp horse_rider.cpp horsename_manager.cpp input.cpp input_auth.cpp input_db.cpp\ - input_login.cpp input_main.cpp input_p2p.cpp port_boss_track.cpp ava2_channel.cpp new_mob_timer.cpp ava2_track.cpp ava2_ticket_shop.cpp ava2_itemshop.cpp port_attr_lock.cpp port_sash.cpp port_mount.cpp port_costume_attr.cpp port_pendant.cpp port_rings.cpp port_switchbot.cpp port_special_storage.cpp offline_shop.cpp offlineshop_manager.cpp offlineshop_search_manager.cpp port_offlineshop.cpp port_ava2_dungeon.cpp input_teen.cpp input_udp.cpp ip_ban.cpp\ + input_login.cpp input_main.cpp input_p2p.cpp port_boss_track.cpp ava2_channel.cpp new_mob_timer.cpp ava2_track.cpp ava2_ticket_shop.cpp ava2_itemshop.cpp port_attr_lock.cpp port_sash.cpp port_mount.cpp port_costume_attr.cpp port_pendant.cpp port_rings.cpp port_switchbot.cpp port_special_storage.cpp offline_shop.cpp offlineshop_manager.cpp offlineshop_search_manager.cpp port_offlineshop.cpp port_ava2_dungeon.cpp port_gaya.cpp input_teen.cpp input_udp.cpp ip_ban.cpp\ item.cpp item_addon.cpp item_attribute.cpp item_manager.cpp item_manager_idrange.cpp locale.cpp\ locale_service.cpp log.cpp login_data.cpp lzo_manager.cpp marriage.cpp matrix_card.cpp\ messenger_manager.cpp mining.cpp mob_manager.cpp monarch.cpp motion.cpp over9refine.cpp p2p.cpp packet_info.cpp\ diff --git a/src/server/game/src/ava2_itemshop.cpp b/src/server/game/src/ava2_itemshop.cpp index 7065cc18..ba96d3af 100644 --- a/src/server/game/src/ava2_itemshop.cpp +++ b/src/server/game/src/ava2_itemshop.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include "char_manager.h" #include "questmanager.h" @@ -22,16 +23,90 @@ namespace { struct PendingPoints { Ava2ShopRequest request; unsigned handle; int attempts; time_t next; }; std::map pendingPoints; LPEVENT pointRetryEvent = NULL; +std::string s_pointLogPath = "log/point_rewards_pending.log"; + +bool AppendDurableIntent(const Ava2ShopRequest& r) { + if (s_pointLogPath.empty()) return false; + size_t slash = s_pointLogPath.rfind('/'); + if (slash != std::string::npos) { + std::string dir = s_pointLogPath.substr(0, slash); + mkdir(dir.c_str(), 0755); + } + FILE* fp = fopen(s_pointLogPath.c_str(), "a"); + if (!fp) return false; + int res = fprintf(fp, "INTENT v1 %s %u %u %u %u %u %lld\n", + r.token, r.account, r.player, r.product, r.count, r.expectedVnum, (long long)time(0)); + if (res < 0) { fclose(fp); return false; } + if (fflush(fp) != 0) { fclose(fp); return false; } + if (fsync(fileno(fp)) != 0) { fclose(fp); return false; } + fclose(fp); + return true; +} + +bool AppendDurableDone(const char* token, uint8_t status, uint32_t granted, int64_t balance) { + if (s_pointLogPath.empty()) return false; + FILE* fp = fopen(s_pointLogPath.c_str(), "a"); + if (!fp) return false; + int res = fprintf(fp, "DONE v1 %s %u %u %lld %lld\n", + token, (unsigned)status, (unsigned)granted, (long long)balance, (long long)time(0)); + if (res < 0) { fclose(fp); return false; } + if (fflush(fp) != 0) { fclose(fp); return false; } + if (fsync(fileno(fp)) != 0) { fclose(fp); return false; } + fclose(fp); + return true; +} + +void CompactDurableLog() { + if (s_pointLogPath.empty()) return; + FILE* fp = fopen(s_pointLogPath.c_str(), "r"); + if (!fp) return; + std::map uncompleted; + char line[256]; + while (fgets(line, sizeof(line), fp)) { + char op[16] = {}, ver[16] = {}, token[64] = {}; + if (sscanf(line, "%15s %15s %63s", op, ver, token) >= 3) { + if (strcmp(op, "INTENT") == 0) { + Ava2ShopRequest r = {}; + r.operation = 3; + unsigned long long t = 0; + if (sscanf(line, "%*s %*s %32s %u %u %u %u %u %llu", + r.token, &r.account, &r.player, &r.product, &r.count, &r.expectedVnum, &t) >= 6) { + uncompleted[token] = r; + } + } else if (strcmp(op, "DONE") == 0) { + uncompleted.erase(token); + } + } + } + fclose(fp); + + std::string tmpPath = s_pointLogPath + ".tmp"; + FILE* out = fopen(tmpPath.c_str(), "w"); + if (!out) return; + for (const auto& kv : uncompleted) { + const auto& r = kv.second; + fprintf(out, "INTENT v1 %s %u %u %u %u %u 0\n", + r.token, r.account, r.player, r.product, r.count, r.expectedVnum); + } + fflush(out); + fsync(fileno(out)); + fclose(out); + rename(tmpPath.c_str(), s_pointLogPath.c_str()); +} + EVENTINFO(PointRetryInfo) {}; EVENTFUNC(RetryPoints) { for(auto it=pendingPoints.begin();it!=pendingPoints.end();) { auto& p=it->second; if(get_global_time()=12) { - sys_err("POINT_DROP: retry exhausted account=%u token=%s",p.request.account,p.request.token); - it=pendingPoints.erase(it);continue; + sys_err("POINT_DROP: retry throttled account=%u token=%s attempts=%d",p.request.account,p.request.token,p.attempts); + p.next=get_global_time()+60; // Throttled retry: resend every 60s, never silently drop! + if(db_clientdesc) db_clientdesc->DBPacket(76,p.handle,&p.request,sizeof(p.request)); + ++p.attempts;++it; + continue; } - db_clientdesc->DBPacket(76,p.handle,&p.request,sizeof(p.request)); + if(db_clientdesc) db_clientdesc->DBPacket(76,p.handle,&p.request,sizeof(p.request)); ++p.attempts;p.next=get_global_time()+10;++it; } if(pendingPoints.empty()){pointRetryEvent=NULL;return 0;} @@ -44,8 +119,9 @@ bool PointReply(const Ava2ShopReply& reply,const char* data) { if(found==pendingPoints.end() || found->second.request.account!=reply.account || found->second.request.player!=reply.player)return true; const uint8_t status=uint8_t(data[1]); if(status==6 || status==8)return true; // Same durable token retries transaction/commit uncertainty. - pendingPoints.erase(found); uint32_t amount=0;int64_t balance=0;memcpy(&amount,data+34,4);memcpy(&balance,data+38,8); + AppendDurableDone(token, status, amount, balance); + pendingPoints.erase(found); auto ch=CHARACTER_MANAGER::instance().FindByPID(reply.player); if(status || !amount || balance<0 || !ch || !ch->GetDesc() || ch->GetDesc()->GetAccountTable().id!=reply.account)return true; const char* version=strstr(ch->GetDesc()->GetClientVersion(),"mt"); @@ -55,20 +131,79 @@ bool PointReply(const Ava2ShopReply& reply,const char* data) { } } +void Ava2PointDropSetLogPath(const std::string& path) { + s_pointLogPath = path; +} + +const std::string& Ava2PointDropGetLogPath() { + return s_pointLogPath; +} + +size_t Ava2PointPendingCount() { + return pendingPoints.size(); +} + +void Ava2PointDropInit() { + if (s_pointLogPath.empty()) return; + FILE* fp = fopen(s_pointLogPath.c_str(), "r"); + if (!fp) return; + std::map uncompleted; + char line[256]; + int doneCount = 0; + while (fgets(line, sizeof(line), fp)) { + char op[16] = {}, ver[16] = {}, token[64] = {}; + if (sscanf(line, "%15s %15s %63s", op, ver, token) >= 3) { + if (strcmp(op, "INTENT") == 0) { + Ava2ShopRequest r = {}; + r.operation = 3; + unsigned long long t = 0; + if (sscanf(line, "%*s %*s %32s %u %u %u %u %u %llu", + r.token, &r.account, &r.player, &r.product, &r.count, &r.expectedVnum, &t) >= 6) { + uncompleted[token] = r; + } + } else if (strcmp(op, "DONE") == 0) { + uncompleted.erase(token); + ++doneCount; + } + } + } + fclose(fp); + + for (const auto& kv : uncompleted) { + const auto& r = kv.second; + if (pendingPoints.find(r.token) == pendingPoints.end()) { + PendingPoints pending = {r, 0, 1, get_global_time() + 2}; + pendingPoints.emplace(r.token, pending); + } + } + + if (doneCount > 500) { + CompactDurableLog(); + } + + if (!pendingPoints.empty() && !pointRetryEvent) { + pointRetryEvent = event_create(RetryPoints, AllocEventInfo(), PASSES_PER_SEC(1)); + } +} + void Ava2PointDrop(CHARACTER* ch,CHARACTER* victim) { if(!ch || !victim || !ch->IsPC() || !ch->GetDesc() || victim->IsPC() || victim->IsPet() || (!victim->IsMonster() && !victim->IsStone()))return; const auto rule=PortPointRule([](const std::string& key){return quest::CQuestManager::instance().GetEventFlag(key);},victim->IsStone()); if(!rule.eligible(victim->GetLevel(),ch->GetLevel()) || number(1,10000)>rule.chance)return; - if(pendingPoints.size()>=4096){sys_err("POINT_DROP: pending queue full");return;} + if(pendingPoints.size()>=4096){sys_err("POINT_DROP: pending queue full, drop suppressed");return;} Ava2ShopRequest p={};p.operation=3;p.account=ch->GetDesc()->GetAccountTable().id;p.player=ch->GetPlayerID(); p.product=victim->GetRaceNum();p.count=number(rule.minimum,rule.maximum);p.expectedVnum=ch->GetLevel(); static const uint64_t boot=[](){timeval t;gettimeofday(&t,NULL);return (uint64_t(t.tv_sec)*1000000+t.tv_usec) ^ (uint64_t(getpid())<<32);}(); static uint64_t serial=0; snprintf(p.token,sizeof(p.token),"%016llx%016llx",static_cast(boot),static_cast(++serial)); strlcpy(p.name,ch->GetName(),sizeof(p.name)); + if (!AppendDurableIntent(p)) { + sys_err("POINT_DROP: failed to write durable log, drop aborted for account=%u token=%s", p.account, p.token); + return; + } PendingPoints pending={p,ch->GetDesc()->GetHandle(),1,get_global_time()+10};pendingPoints.emplace(p.token,pending); - db_clientdesc->DBPacket(76,pending.handle,&p,sizeof(p)); + if(db_clientdesc) db_clientdesc->DBPacket(76,pending.handle,&p,sizeof(p)); if(!pointRetryEvent)pointRetryEvent=event_create(RetryPoints,AllocEventInfo(),PASSES_PER_SEC(1)); } ACMD(do_ishop) { diff --git a/src/server/game/src/ava2_itemshop.h b/src/server/game/src/ava2_itemshop.h index d40537a6..e678ff0f 100644 --- a/src/server/game/src/ava2_itemshop.h +++ b/src/server/game/src/ava2_itemshop.h @@ -1,4 +1,10 @@ #pragma once +#include +#include class CHARACTER; void Ava2ItemShopReply(unsigned long handle,const char* data); void Ava2PointDrop(CHARACTER* player, CHARACTER* victim); +void Ava2PointDropInit(); +void Ava2PointDropSetLogPath(const std::string& path); +const std::string& Ava2PointDropGetLogPath(); +size_t Ava2PointPendingCount(); diff --git a/src/server/game/src/char.h b/src/server/game/src/char.h index 2dc78c13..48cd0d4e 100755 --- a/src/server/game/src/char.h +++ b/src/server/game/src/char.h @@ -290,6 +290,7 @@ enum EPointTypes POINT_ENCHANT_WIND = 245, POINT_ENCHANT_EARTH = 246, POINT_ENCHANT_DARK = 247, + POINT_GEM = 248, POINT_RESIST_HUMAN = 220, // 추가 ì†�성 저항 @@ -1193,6 +1194,12 @@ class CHARACTER : public CEntity, public CFSM, public CHorseRider void OpenChest(LPITEM item, WORD count); bool AutoGiveItemChest(LPITEM item, DWORD& count, std::map& updates); bool GiveItemFromSpecialItemGroupNew(DWORD group, WORD& count); + int GetGem() const; + void ChangeGem(int amount); + bool OpenGemSlot(); + void RefreshGemALL(bool withRealTime = false); + void RefreshGemPlayer(); + void BuyGemItem(BYTE slotIndex); bool PickupItem(DWORD vid); bool EquipItem(LPITEM item, int iCandidateCell = -1); bool UnequipItem(LPITEM item); diff --git a/src/server/game/src/char_item.cpp b/src/server/game/src/char_item.cpp index b5dcdd20..78374280 100755 --- a/src/server/game/src/char_item.cpp +++ b/src/server/game/src/char_item.cpp @@ -2741,8 +2741,8 @@ bool CHARACTER::UseItemEx(LPITEM item, TItemPos DestCell) if (GiveItemFromSpecialItemGroup(dwBoxVnum, dwVnums, dwCounts, item_gets, count)) { - ITEM_MANAGER::instance().RemoveItem(item); - ITEM_MANAGER::instance().RemoveItem(item2); + item->SetCount(item->GetCount() - 1); + item2->SetCount(item2->GetCount() - 1); for (int i = 0; i < count; i++){ switch (dwVnums[i]) @@ -3232,6 +3232,19 @@ bool CHARACTER::UseItemEx(LPITEM item, TItemPos DestCell) item->SetCount(item->GetCount()-1); return true; } + if(item->GetVnum()==39063) { + RefreshGemALL(); + item->SetCount(item->GetCount()-1); + return true; + } + if(item->GetVnum()==39064) { + if(OpenGemSlot()) { + item->SetCount(item->GetCount()-1); + return true; + } + ChatPacket(CHAT_TYPE_INFO, LC_TEXT("ë�” ì�´ìƒ� 슬롯ì�„ 확장할 수 없습니다.")); + return false; + } switch (item->GetVnum()) { diff --git a/src/server/game/src/cmd.cpp b/src/server/game/src/cmd.cpp index e2265118..f1e40e4b 100755 --- a/src/server/game/src/cmd.cpp +++ b/src/server/game/src/cmd.cpp @@ -197,7 +197,7 @@ ACMD(do_add_socket); ACMD(do_inputall) { - ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("¸í·É¾î¸¦ ¸ðµÎ ÀÔ·ÂÇϼ¼¿ä.")); + ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("명령어를 모ë‘� 입력하세요.")); } ACMD(do_show_arena_list); @@ -217,7 +217,7 @@ ACMD(do_effect); ACMD(do_threeway_war_info ); ACMD(do_threeway_war_myinfo ); // -//±ºÁÖ Àü¿ë±â´É +//군주 전용기능 ACMD(do_monarch_warpto); ACMD(do_monarch_transfer); ACMD(do_monarch_info); @@ -226,7 +226,7 @@ ACMD(do_monarch_tax); ACMD(do_monarch_mob); ACMD(do_monarch_notice); -//±ºÁÖ °ü¸® ±â´É +//군주 관리 기능 ACMD(do_rmcandidacy); ACMD(do_setmonarch); ACMD(do_rmmonarch); @@ -234,10 +234,10 @@ ACMD(do_rmmonarch); ACMD(do_hair); //gift notify quest command ACMD(do_gift); -// Å¥ºê°ü·Ã +// í��브관련 ACMD(do_inventory); ACMD(do_cube); -// °ø¼ºÀü +// 공성전 ACMD(do_siege); ACMD(do_temp); ACMD(do_frog); @@ -265,7 +265,7 @@ ACMD(do_ride); ACMD(do_get_item_id_list); ACMD(do_set_socket); #ifdef __AUCTION__ -// temp_auction Àӽà +// temp_auction 임시 ACMD(do_get_auction_list); ACMD (do_get_my_auction_list); ACMD (do_get_my_purchase_list); @@ -285,30 +285,31 @@ ACMD (do_cancel_sale); ACMD (do_rebid); ACMD (do_bid_cancel); #endif -// ÄÚ½ºÃõ »óź¸±â ¹× ¹þ±â +// 코스츔 ìƒ�태보기 ë°� 벗기 ACMD(do_costume); ACMD(do_set_stat); -// ¹«Àû +// 무ì � ACMD (do_can_dead); ACMD (do_full_set); -// Á÷±º°ú ·¹º§¿¡ µû¸¥ ÃÖ°í ¾ÆÀÌÅÛ +// ì§�êµ°ê³¼ 레벨ì—� 따른 최고 ì•„ì�´í…œ ACMD (do_item_full_set); -// Á÷±º¿¡ µû¸¥ ÃÖ°í ¿É¼ÇÀÇ ¼Ó¼º ¼ÂÆÃ +// ì§�êµ°ì—� 따른 최고 옵션ì�˜ ì†�성 셋팅 ACMD (do_attr_full_set); -// ¸ðµç ½ºÅ³ ¸¶½ºÅÍ +// 모든 스킬 마스터 ACMD (do_all_skill_master); -// ¾ÆÀÌÅÛ Âø¿ë. iconÀÌ ¾ø¾î Ŭ¶ó¿¡¼­ È®ÀÎ ÇÒ ¼ö ¾ø´Â ¾ÆÀÌÅÛ Âø¿ëÀ» À§ÇØ ¸¸µê. +// ì•„ì�´í…œ ì°©ìš©. iconì�´ 없어 í�´ë�¼ì—�서 확ì�¸ í•  수 없는 ì•„ì�´í…œ ì°©ìš©ì�„ 위해 만듦. ACMD (do_use_item); ACMD (do_dragon_soul); ACMD (do_ds_list); ACMD (do_clear_affect); +ACMD(do_gem); ACMD(do_ishop); struct command_info cmd_info[] = { - { "!RESERVED!", NULL, 0, POS_DEAD, GM_IMPLEMENTOR }, /* ¹Ýµå½Ã ÀÌ °ÍÀÌ Ã³À½À̾î¾ß ÇÑ´Ù. */ + { "!RESERVED!", NULL, 0, POS_DEAD, GM_IMPLEMENTOR }, /* 반드시 ì�´ 것ì�´ 처ì�Œì�´ì–´ì•¼ 한다. */ { "ishop", do_ishop, 0, POS_DEAD, GM_PLAYER }, { "autohunt_pull", do_autohunt_pull, 0, POS_FIGHTING, GM_PLAYER }, { "bio", do_port_biolog, 0, POS_DEAD, GM_PLAYER }, @@ -334,7 +335,7 @@ struct command_info cmd_info[] = { "item", do_item, 0, POS_DEAD, GM_GOD }, { "mob", do_mob, 0, POS_DEAD, GM_HIGH_WIZARD }, - { "mob_ld", do_mob_ld, 0, POS_DEAD, GM_HIGH_WIZARD }, /* ¸÷ÀÇ À§Ä¡¿Í ¹æÇâÀ» ¼³Á¤ÇØ ¼Òȯ /mob_ld vnum x y dir */ + { "mob_ld", do_mob_ld, 0, POS_DEAD, GM_HIGH_WIZARD }, /* 몹ì�˜ 위치와 ë°©í–¥ì�„ 설정해 소환 /mob_ld vnum x y dir */ { "ma", do_mob_aggresive, 0, POS_DEAD, GM_HIGH_WIZARD }, { "mc", do_mob_coward, 0, POS_DEAD, GM_HIGH_WIZARD }, { "mm", do_mob_map, 0, POS_DEAD, GM_HIGH_WIZARD }, @@ -432,8 +433,8 @@ struct command_info cmd_info[] = { "delqf", do_delqf, 0, POS_DEAD, GM_LOW_WIZARD }, { "set_state", do_set_state, 0, POS_DEAD, GM_LOW_WIZARD }, - { "·Î±×¸¦º¸¿©Áà", do_detaillog, 0, POS_DEAD, GM_LOW_WIZARD }, - { "¸ó½ºÅͺ¸¿©Áà", do_monsterlog, 0, POS_DEAD, GM_LOW_WIZARD }, + { "로그를보여줘", do_detaillog, 0, POS_DEAD, GM_LOW_WIZARD }, + { "몬스터보여줘", do_monsterlog, 0, POS_DEAD, GM_LOW_WIZARD }, { "detaillog", do_detaillog, 0, POS_DEAD, GM_LOW_WIZARD }, { "monsterlog", do_monsterlog, 0, POS_DEAD, GM_LOW_WIZARD }, @@ -577,7 +578,7 @@ struct command_info cmd_info[] = { "get_mob_count", do_get_mob_count, 0, POS_DEAD, GM_LOW_WIZARD }, { "dice", do_dice, 0, POS_DEAD, GM_PLAYER }, - { "ÁÖ»çÀ§", do_dice, 0, POS_DEAD, GM_PLAYER }, + { "주사위", do_dice, 0, POS_DEAD, GM_PLAYER }, { "special_item", do_special_item, 0, POS_DEAD, GM_IMPLEMENTOR }, { "click_mall", do_click_mall, 0, POS_DEAD, GM_PLAYER }, @@ -587,7 +588,7 @@ struct command_info cmd_info[] = { "item_id_list", do_get_item_id_list, 0, POS_DEAD, GM_LOW_WIZARD }, { "set_socket", do_set_socket, 0, POS_DEAD, GM_LOW_WIZARD }, #ifdef __AUCTION__ - // auction Àӽà + // auction 임시 { "auction_list", do_get_auction_list, 0, POS_DEAD, GM_PLAYER }, { "my_auction_list", do_get_my_auction_list, 0, POS_DEAD, GM_PLAYER }, { "my_purchase_list", do_get_my_purchase_list, 0, POS_DEAD, GM_PLAYER }, @@ -651,7 +652,8 @@ struct command_info cmd_info[] = { "pet_add_slot", do_pet_add_slot, 0, POS_DEAD, GM_PLAYER }, { "change_name", do_change_name, 0, POS_DEAD, GM_PLAYER }, #endif - { "\n", NULL, 0, POS_DEAD, GM_IMPLEMENTOR } /* ¹Ýµå½Ã ÀÌ °ÍÀÌ ¸¶Áö¸·À̾î¾ß ÇÑ´Ù. */ + { "gem", do_gem, 0, POS_DEAD, GM_PLAYER }, + { "\n", NULL, 0, POS_DEAD, GM_IMPLEMENTOR } /* 반드시 ì�´ 것ì�´ 마지막ì�´ì–´ì•¼ 한다. */ }; void interpreter_set_privilege(const char *cmd, int lvl) @@ -674,7 +676,7 @@ void double_dollar(const char *src, size_t src_len, char *dest, size_t dest_len) const char * tmp = src; size_t cur_len = 0; - // \0 ³ÖÀ» ÀÚ¸® È®º¸ + // \0 ë„£ì�„ ìž�리 확보 dest_len -= 1; while (src_len-- && *tmp) @@ -709,7 +711,7 @@ void interpret_command(LPCHARACTER ch, const char * argument, size_t len) return ; } - char cmd[128 + 1]; // buffer overflow ¹®Á¦°¡ »ý±âÁö ¾Êµµ·Ï ÀϺη¯ ±æÀ̸¦ ª°Ô ÀâÀ½ + char cmd[128 + 1]; // buffer overflow 문제가 ìƒ�기지 않ë�„ë¡� ì�¼ë¶€ëŸ¬ 길ì�´ë¥¼ 짧게 ìž¡ì�Œ char new_line[256 + 1]; const char * line; int icmd; @@ -726,7 +728,7 @@ void interpret_command(LPCHARACTER ch, const char * argument, size_t len) { if (cmd_info[icmd].command_pointer == do_cmd) { - if (!strcmp(cmd_info[icmd].command, cmd)) // do_cmd´Â ¸ðµç ¸í·É¾î¸¦ ÃÄ¾ß ÇÒ ¼ö ÀÖ´Ù. + if (!strcmp(cmd_info[icmd].command, cmd)) // do_cmd는 모든 명령어를 ì³�야 í•  수 있다. break; } else if (!strncmp(cmd_info[icmd].command, cmd, cmdlen)) @@ -738,24 +740,24 @@ void interpret_command(LPCHARACTER ch, const char * argument, size_t len) switch (ch->GetPosition()) { case POS_MOUNTING: - ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("ź »óÅ¿¡¼­´Â ÇÒ ¼ö ¾ø½À´Ï´Ù.")); + ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("탄 ìƒ�태ì—�서는 í•  수 없습니다.")); break; case POS_DEAD: - ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("¾²·¯Áø »óÅ¿¡¼­´Â ÇÒ ¼ö ¾ø½À´Ï´Ù.")); + ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("쓰러진 ìƒ�태ì—�서는 í•  수 없습니다.")); break; case POS_SLEEPING: - ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("²Þ¼Ó¿¡¼­ ¾î¶»°Ô¿ä?")); + ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("꿈ì†�ì—�서 어떻게요?")); break; case POS_RESTING: case POS_SITTING: - ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("¸ÕÀú ÀÏ¾î ³ª¼¼¿ä.")); + ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("먼저 ì�¼ì–´ 나세요.")); break; /* case POS_FIGHTING: - ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("¸ñ¼ûÀ» °É°í ÀüÅõ Áß ÀÔ´Ï´Ù. ÁýÁß Çϼ¼¿ä.")); + ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("목숨ì�„ 걸고 전투 중 입니다. 집중 하세요.")); break; */ default: @@ -768,17 +770,17 @@ void interpret_command(LPCHARACTER ch, const char * argument, size_t len) if (*cmd_info[icmd].command == '\n') { - ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("±×·± ¸í·É¾î´Â ¾ø½À´Ï´Ù")); + ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("그런 명령어는 없습니다")); return; } if (cmd_info[icmd].gm_level && cmd_info[icmd].gm_level > ch->GetGMLevel()) { - ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("±×·± ¸í·É¾î´Â ¾ø½À´Ï´Ù")); + ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("그런 명령어는 없습니다")); return; } - if (strncmp("phase", cmd_info[icmd].command, 5) != 0) // È÷µç ¸í·É¾î ó¸® + if (strncmp("phase", cmd_info[icmd].command, 5) != 0) // 히든 명령어 처리 sys_log(0, "COMMAND: %s: %s", ch->GetName(), cmd_info[icmd].command); ((*cmd_info[icmd].command_pointer) (ch, line, icmd, cmd_info[icmd].subcmd)); diff --git a/src/server/game/src/main.cpp b/src/server/game/src/main.cpp index a12e1032..289d6dc2 100755 --- a/src/server/game/src/main.cpp +++ b/src/server/game/src/main.cpp @@ -65,6 +65,7 @@ // #include "XTrapManager.h" #include "DragonSoul.h" #include "port_switchbot.h" +#include "ava2_itemshop.h" #include #ifndef __WIN32__ #include "limit_time.h" @@ -558,6 +559,7 @@ int main(int argc, char **argv) Blend_Item_init(); ani_init(); PanamaLoad(); + Ava2PointDropInit(); Metin2Server_Check(); diff --git a/src/server/game/src/port_gaya.cpp b/src/server/game/src/port_gaya.cpp new file mode 100644 index 00000000..d8b0195b --- /dev/null +++ b/src/server/game/src/port_gaya.cpp @@ -0,0 +1,346 @@ +#include "stdafx.h" +#include "port_gaya.h" +#include "char.h" +#include "utils.h" +#include "cmd.h" +#include +#include +#include +#include +#include + +namespace { +std::string s_gayaDir = "locale/germany/gem"; +std::map> s_playerGayaItems; + +struct GemCatalogEntry { + uint32_t vnum; + uint32_t count; + int price; + int lucky; +}; + +static const GemCatalogEntry s_gemCatalog[] = { + {71136, 1, 100, 100}, + {76012, 5, 1, 100}, + {76012, 20, 5, 100}, + {25162, 1, 2, 100}, + {39032, 1, 1, 100}, + {6884, 1, 250, 100}, + {72320, 1, 10, 100}, + {72320, 2, 20, 100}, + {72319, 1, 20, 100}, + {72319, 2, 40, 100}, + {71153, 1, 100, 100}, + {55035, 1, 5, 100}, + {30250, 1, 25, 100}, + {71035, 1, 25, 100}, + {55001, 1, 150, 100}, + {55009, 1, 55, 100}, + {85009, 1, 250, 100}, + {25163, 1, 3, 100}, + {25164, 1, 5, 100}, + {25165, 1, 7, 100}, + {25166, 1, 10, 100}, + {25167, 1, 12, 100}, + {25168, 1, 12, 100}, + {25169, 1, 15, 100}, + {71097, 1, 50, 100}, + {71097, 2, 100, 100}, + {100001, 1, 5, 100}, + {100002, 1, 10, 100}, + {71509, 1, 150, 100}, + {71506, 1, 150, 100}, + {71503, 1, 150, 100}, + {71500, 1, 150, 100}, + {53002, 1, 150, 100}, + {53005, 1, 150, 100}, + {53008, 1, 150, 100}, + {53011, 1, 150, 100}, + {77910, 1, 10, 100}, + {77911, 1, 35, 100}, + {77912, 1, 70, 100}, + {70043, 1, 20, 100}, + {70005, 1, 20, 100}, + {80025, 1, 10, 100}, + {25100, 1, 1, 100}, + {71084, 500, 10, 100}, + {71084, 1000, 20, 100}, + {71084, 2000, 40, 100}, + {71151, 1000, 5, 100}, + {71151, 2000, 10, 100}, + {72346, 1, 55, 100}, + {72346, 2, 110, 100}, + {53996, 20, 25, 100}, + {55036, 1, 300, 100}, + {30402, 1, 2, 100}, + {30403, 1, 7, 100}, + {30404, 1, 13, 100}, + {30405, 1, 17, 100}, + {30406, 1, 27, 100}, + {30407, 1, 53, 100}, + {30408, 1, 105, 100}, + {55401, 1, 20, 100}, + {77927, 1, 150, 100}, + {50348, 1, 250, 100}, + {50349, 1, 50, 100}, +}; +} + +void PortGayaSetDirectory(const std::string& dir) { + s_gayaDir = dir; +} + +const std::string& PortGayaGetDirectory() { + return s_gayaDir; +} + +int PortGayaGet(const CHARACTER* ch) { + if (!ch) return 0; + return const_cast(ch)->GetQuestFlag("gem.points"); +} + +void PortGayaChange(CHARACTER* ch, int amount) { + if (!ch) return; + int current = PortGayaGet(ch); + int updated = std::max(0, std::min(GEM_MAX, current + amount)); + ch->SetQuestFlag("gem.points", updated); + ch->SetPoint(POINT_GEM, updated); + ch->PointChange(POINT_GEM, 0); +} + +bool PortGayaOpenSlot(CHARACTER* ch) { + if (!ch) return false; + const int openSlotFlag = ch->GetQuestFlag("gem.open_slot"); + if (openSlotFlag < 18) { + ch->SetQuestFlag("gem.open_slot", openSlotFlag + 1); + ch->ChatPacket(CHAT_TYPE_COMMAND, "GemUpdateSlotCount %d", openSlotFlag + 1); + return true; + } + return false; +} + +void PortGayaLoadItems(CHARACTER* ch) { + if (!ch) return; + uint32_t pid = ch->GetPlayerID(); + auto& items = s_playerGayaItems[pid]; + items.clear(); + + char filename[256]; + snprintf(filename, sizeof(filename), "%s/%u", s_gayaDir.c_str(), pid); + FILE* fp = fopen(filename, "r"); + if (fp) { + char line[256]; + while (fgets(line, sizeof(line), fp)) { + unsigned slot = 0, vnum = 0, count = 0, buyed = 0; + int price = 0; + if (sscanf(line, "%u %u %u %d %u", &slot, &vnum, &count, &price, &buyed) == 5) { + TGemItem item; + item.itemVnum = vnum; + item.itemCount = count; + item.itemPrice = price; + item.itemBuyed = (buyed != 0); + items[(uint8_t)slot] = item; + } + } + fclose(fp); + } +} + +void PortGayaSaveItems(CHARACTER* ch) { + if (!ch) return; + uint32_t pid = ch->GetPlayerID(); + const auto& items = s_playerGayaItems[pid]; + + // Ensure directory exists + size_t slash = s_gayaDir.rfind('/'); + if (slash != std::string::npos) { + std::string parent = s_gayaDir.substr(0, slash); + mkdir(parent.c_str(), 0755); + } + mkdir(s_gayaDir.c_str(), 0755); + + char filename[256]; + snprintf(filename, sizeof(filename), "%s/%u", s_gayaDir.c_str(), pid); + FILE* fp = fopen(filename, "w+"); + if (fp) { + fprintf(fp, "index-vnum-count-price-buyed\n"); + for (const auto& kv : items) { + fprintf(fp, "%u %u %u %d %u\n", kv.first, kv.second.itemVnum, kv.second.itemCount, kv.second.itemPrice, kv.second.itemBuyed ? 1 : 0); + } + fflush(fp); + fsync(fileno(fp)); + fclose(fp); + } +} + +static void PortGayaGenerateItems(CHARACTER* ch) { + if (!ch) return; + uint32_t pid = ch->GetPlayerID(); + auto& items = s_playerGayaItems[pid]; + items.clear(); + + const size_t catalogSize = sizeof(s_gemCatalog) / sizeof(s_gemCatalog[0]); + std::vector chosenIndices; + while (chosenIndices.size() < 27 && chosenIndices.size() < catalogSize) { + for (size_t i = 0; i < catalogSize; ++i) { + if (number(1, 100) > s_gemCatalog[i].lucky) continue; + if (std::find(chosenIndices.begin(), chosenIndices.end(), (uint8_t)i) != chosenIndices.end()) continue; + chosenIndices.push_back((uint8_t)i); + if (chosenIndices.size() >= 27) break; + } + } + for (size_t i = 0; i < chosenIndices.size(); ++i) { + const auto& entry = s_gemCatalog[chosenIndices[i]]; + TGemItem it; + it.itemBuyed = false; + it.itemVnum = entry.vnum; + it.itemCount = entry.count; + it.itemPrice = entry.price; + items[(uint8_t)i] = it; + } + PortGayaSaveItems(ch); +} + +void PortGayaRefreshPlayer(CHARACTER* ch) { + if (!ch) return; + uint32_t pid = ch->GetPlayerID(); + auto it = s_playerGayaItems.find(pid); + if (it == s_playerGayaItems.end() || it->second.empty()) { + PortGayaLoadItems(ch); + if (s_playerGayaItems[pid].empty()) + PortGayaGenerateItems(ch); + } + + ch->ChatPacket(CHAT_TYPE_COMMAND, "GemClear"); + ch->ChatPacket(CHAT_TYPE_COMMAND, "GemUpdateSlotCount %d", ch->GetQuestFlag("gem.open_slot")); + int left = ch->GetQuestFlag("gem.left_time") - time(0); + ch->ChatPacket(CHAT_TYPE_COMMAND, "GemSetRefreshLeftTime %d", left > 0 ? left : 0); + + const auto& items = s_playerGayaItems[pid]; + std::string cmdString = ""; + for (const auto& kv : items) { + const uint8_t slotPos = kv.first; + const auto& itemData = kv.second; + cmdString += std::to_string(slotPos); + cmdString += "#"; + cmdString += std::to_string(itemData.itemVnum); + cmdString += "#"; + cmdString += std::to_string(itemData.itemCount); + cmdString += "#"; + cmdString += std::to_string(itemData.itemPrice); + cmdString += "#"; + cmdString += std::to_string(itemData.itemBuyed ? 1 : 0); + cmdString += "|"; + if (cmdString.size() + 50 > 450) { + ch->ChatPacket(CHAT_TYPE_COMMAND, "GemSetItemsWithString %s", cmdString.c_str()); + cmdString.clear(); + } + } + if (!cmdString.empty()) { + ch->ChatPacket(CHAT_TYPE_COMMAND, "GemSetItemsWithString %s", cmdString.c_str()); + } +} + +void PortGayaRefreshAll(CHARACTER* ch, bool withRealTime) { + if (!ch) return; + int leftTime = 0; + if (withRealTime && ch->GetQuestFlag("gem.left_time") != 0) { + leftTime = time(0) - ch->GetQuestFlag("gem.left_time"); + if (leftTime < 1) leftTime = 0; + } + ch->SetQuestFlag("gem.left_time", (time(0) + REFRESH_TIME) - leftTime); + PortGayaGenerateItems(ch); + PortGayaRefreshPlayer(ch); +} + +void PortGayaBuyItem(CHARACTER* ch, uint8_t slotIndex) { + if (!ch) return; + uint32_t pid = ch->GetPlayerID(); + auto& items = s_playerGayaItems[pid]; + if (items.empty()) { + PortGayaLoadItems(ch); + } + auto it = items.find(slotIndex); + if (it != items.end()) { + if (slotIndex >= 9) { + if (ch->GetQuestFlag("gem.open_slot") < (slotIndex - 9) + 1) + return; + } + if (it->second.itemBuyed) + return; + int price = it->second.itemPrice; + if (price > PortGayaGet(ch)) { + ch->ChatPacket(CHAT_TYPE_INFO, "Not enough Gaya."); + return; + } + it->second.itemBuyed = true; + PortGayaChange(ch, -price); + ch->AutoGiveItem(it->second.itemVnum, it->second.itemCount); + ch->ChatPacket(CHAT_TYPE_COMMAND, "GemSetBuyedSlot %d 1", slotIndex); + PortGayaSaveItems(ch); + } +} + +// CHARACTER member method forwarders +int CHARACTER::GetGem() const { + return PortGayaGet(this); +} + +void CHARACTER::ChangeGem(int amount) { + PortGayaChange(this, amount); +} + +bool CHARACTER::OpenGemSlot() { + return PortGayaOpenSlot(this); +} + +void CHARACTER::RefreshGemALL(bool withRealTime) { + PortGayaRefreshAll(this, withRealTime); +} + +void CHARACTER::RefreshGemPlayer() { + PortGayaRefreshPlayer(this); +} + +void CHARACTER::BuyGemItem(BYTE slotIndex) { + PortGayaBuyItem(this, slotIndex); +} + +ACMD(do_gem) { + if (!ch || !ch->IsPC() || !ch->GetDesc() || ch->IsWarping() || ch->IsDead()) return; + std::vector vecArgs; + split_argument(argument, vecArgs); + if (vecArgs.size() < 2) return; + if (vecArgs[1] == "load") { + if (time(0) >= ch->GetQuestFlag("gem.left_time")) { + ch->RefreshGemALL(true); + } else { + ch->RefreshGemPlayer(); + } + } else if (vecArgs[1] == "time") { + if (time(0) >= ch->GetQuestFlag("gem.left_time")) { + ch->RefreshGemALL(true); + } + } else if (vecArgs[1] == "slot") { + if (ch->CountSpecifyItem(OPEN_GEM_SLOT_ITEM) < 1) { + ch->ChatPacket(CHAT_TYPE_INFO, "You don't have enough Gaya slot expansion items."); + return; + } + if (ch->OpenGemSlot()) { + ch->RemoveSpecifyItem(OPEN_GEM_SLOT_ITEM, 1); + } + } else if (vecArgs[1] == "refresh") { + if (ch->CountSpecifyItem(OPEN_GEM_REFRESH_ITEM) < 1) { + ch->ChatPacket(CHAT_TYPE_INFO, "You don't have enough refresh Gaya market items."); + return; + } + ch->RemoveSpecifyItem(OPEN_GEM_REFRESH_ITEM, 1); + ch->RefreshGemALL(); + } else if (vecArgs[1] == "buy") { + if (vecArgs.size() < 3) return; + BYTE slotIndex = 0; + if (!str_to_number(slotIndex, vecArgs[2].c_str())) return; + ch->BuyGemItem(slotIndex); + } +} diff --git a/src/server/game/src/port_gaya.h b/src/server/game/src/port_gaya.h new file mode 100644 index 00000000..0fa72ea9 --- /dev/null +++ b/src/server/game/src/port_gaya.h @@ -0,0 +1,34 @@ +#pragma once +#include +#include +#include +#include + +enum EGemConstants +{ + REFRESH_TIME = 60 * 60 * 5, + OPEN_GEM_SLOT_ITEM = 39064, + OPEN_GEM_REFRESH_ITEM = 39063, + GEM_MAX = 1000000, +}; + +struct TGemItem +{ + uint32_t itemVnum; + uint32_t itemCount; + int itemPrice; + bool itemBuyed; +}; + +class CHARACTER; + +int PortGayaGet(const CHARACTER* ch); +void PortGayaChange(CHARACTER* ch, int amount); +bool PortGayaOpenSlot(CHARACTER* ch); +void PortGayaRefreshAll(CHARACTER* ch, bool withRealTime = false); +void PortGayaRefreshPlayer(CHARACTER* ch); +void PortGayaBuyItem(CHARACTER* ch, uint8_t slotIndex); +void PortGayaSaveItems(CHARACTER* ch); +void PortGayaLoadItems(CHARACTER* ch); +void PortGayaSetDirectory(const std::string& dir); +const std::string& PortGayaGetDirectory(); diff --git a/tests/features/test_dragonsoul_alchemy.py b/tests/features/test_dragonsoul_alchemy.py new file mode 100644 index 00000000..b02ec750 --- /dev/null +++ b/tests/features/test_dragonsoul_alchemy.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +"""Verify Dragon Soul / Alchemy mechanics for items 100001, 100002, 100500.""" +from pathlib import Path +import re +import unittest + +ROOT = Path(__file__).resolve().parents[2] + + +class DragonSoulAlchemyTest(unittest.TestCase): + def test_item_proto_definitions(self): + """Verify item types, sub-types, and values from item_proto sources.""" + proto_file = ( + ROOT / '..' / 'AVA2' / '3. Source BIN' / 'Tools' / 'DumpProto' / 'Release' / 'item_proto.txt' + ) + if not proto_file.exists(): + proto_file = ROOT / '..' / 'metin2-client' / 'build' / 'wiki-source' / 'item_proto.txt' + self.assertTrue(proto_file.exists(), "item_proto.txt must exist") + + lines = proto_file.read_text(encoding='latin1').splitlines() + protos = {} + for line in lines: + parts = line.split('\t') + if len(parts) >= 4 and parts[0] in ('100001', '100002', '100500'): + protos[parts[0]] = parts + + # 100001: USE_TIME_CHARGE_PER, Value0 = 50 (%) + self.assertIn('100001', protos) + p100001 = protos['100001'] + self.assertEqual(p100001[2], 'ITEM_USE') + self.assertEqual(p100001[3], 'USE_TIME_CHARGE_PER') + # Value0 index in TSV is typically 24 + self.assertIn('50', p100001) + + # 100002: USE_TIME_CHARGE_FIX, Value0 = 86400 (24h) + if '100002' in protos: + p100002 = protos['100002'] + self.assertEqual(p100002[2], 'ITEM_USE') + self.assertEqual(p100002[3], 'USE_TIME_CHARGE_FIX') + self.assertIn('86400', p100002) + + # 100500: MATERIAL_DS_REFINE_HOLLY + if '100500' in protos: + p100500 = protos['100500'] + self.assertEqual(p100500[2], 'ITEM_MATERIAL') + self.assertEqual(p100500[3], 'MATERIAL_DS_REFINE_HOLLY') + + def test_dragonsoul_time_charge_logic_char_item(self): + """Verify char_item.cpp correctly handles USE_TIME_CHARGE_PER and USE_TIME_CHARGE_FIX.""" + source = (ROOT / 'src/server/game/src/char_item.cpp').read_text(encoding='latin1') + + # USE_TIME_CHARGE_PER block + self.assertIn('case USE_TIME_CHARGE_PER:', source) + per_block = source.split('case USE_TIME_CHARGE_PER:', 1)[1].split('break;', 1)[0] + self.assertIn('pDestItem->IsDragonSoul()', per_block) + self.assertIn('pDestItem->GiveMoreTime_Per', per_block) + self.assertIn('item->SetCount(item->GetCount() - 1);', per_block) + + # USE_TIME_CHARGE_FIX block + self.assertIn('case USE_TIME_CHARGE_FIX:', source) + fix_block = source.split('case USE_TIME_CHARGE_FIX:', 1)[1].split('break;', 1)[0] + self.assertIn('pDestItem->IsDragonSoul()', fix_block) + self.assertIn('pDestItem->GiveMoreTime_Fix', fix_block) + self.assertIn('item->SetCount(item->GetCount() - 1);', fix_block) + + def test_item_give_more_time_implementation(self): + """Verify CItem::GiveMoreTime_Per and CItem::GiveMoreTime_Fix logic in item.cpp.""" + source = (ROOT / 'src/server/game/src/item.cpp').read_text(encoding='latin1') + + # Verify GiveMoreTime_Per + self.assertIn('int CItem::GiveMoreTime_Per(float fPercent)', source) + per_code = source.split('int CItem::GiveMoreTime_Per(float fPercent)', 1)[1].split('int CItem::GiveMoreTime_Fix', 1)[0] + self.assertIn('DWORD duration = DSManager::instance().GetDuration(this);', per_code) + self.assertIn('int remain_sec = GetSocket(ITEM_SOCKET_REMAIN_SEC);', per_code) + self.assertIn('int given_time = fPercent * duration / 100;', per_code) + self.assertIn('if (remain_sec == duration)', per_code) + self.assertIn('SetSocket(ITEM_SOCKET_REMAIN_SEC, duration);', per_code) + + # Verify GiveMoreTime_Fix + self.assertIn('int CItem::GiveMoreTime_Fix(DWORD dwTime)', source) + fix_code = source.split('int CItem::GiveMoreTime_Fix(DWORD dwTime)', 1)[1].split('int\tCItem::GetDuration()', 1)[0] + self.assertIn('if (remain_sec == duration)', fix_code) + self.assertIn('SetSocket(ITEM_SOCKET_REMAIN_SEC, duration);', fix_code) + + def test_time_charge_simulation(self): + """Simulate GiveMoreTime_Per and GiveMoreTime_Fix numerical bounds.""" + duration = 86400 # 24 hours + + # Simulated GiveMoreTime_Per (50%) + def give_more_time_per(remain_sec, percent=50.0): + given = int(percent * duration / 100) + if remain_sec == duration: + return 0, remain_sec + if given + remain_sec >= duration: + return duration - remain_sec, duration + return given, remain_sec + given + + # 1. 50% charge when remaining is 0: gives 43200s, total 43200s + added, new_remain = give_more_time_per(0, 50.0) + self.assertEqual(added, 43200) + self.assertEqual(new_remain, 43200) + + # 2. 50% charge when remaining is 60000s: capped at 86400, gives 26400s + added, new_remain = give_more_time_per(60000, 50.0) + self.assertEqual(added, 26400) + self.assertEqual(new_remain, 86400) + + # 3. Charge when already full: gives 0 + added, new_remain = give_more_time_per(86400, 50.0) + self.assertEqual(added, 0) + self.assertEqual(new_remain, 86400) + + # Simulated GiveMoreTime_Fix (86400s) + def give_more_time_fix(remain_sec, fix_time=86400): + if remain_sec == duration: + return 0, remain_sec + if fix_time + remain_sec >= duration: + return duration - remain_sec, duration + return fix_time, remain_sec + fix_time + + # 1. Fixed charge 86400s when remaining is 1000s: capped at 86400, gives 85400s + added, new_remain = give_more_time_fix(1000, 86400) + self.assertEqual(added, 85400) + self.assertEqual(new_remain, 86400) + + def test_dragon_bean_100500_refine_strength_mechanics(self): + """Verify 100500 MATERIAL_DS_REFINE_HOLLY in DSManager::DoRefineStrength.""" + source = (ROOT / 'src/server/game/src/DragonSoul.cpp').read_text(encoding='latin1') + + # Check IsDragonSoulRefineMaterial recognizes MATERIAL_DS_REFINE_HOLLY + mat_check = source.split('bool IsDragonSoulRefineMaterial(LPITEM pItem)', 1)[1].split('bool DSManager::DoRefineStrength', 1)[0] + self.assertIn('MATERIAL_DS_REFINE_HOLLY', mat_check) + + # Check DoRefineStrength handling of refine stone and fee + refine_func = source.split('bool DSManager::DoRefineStrength', 1)[1].split('SendRefineResultPacket(ch, bSubHeader,', 1)[0] + + # Fee deduction before roll + self.assertIn('if (ch->GetGold() < fee)', refine_func) + self.assertIn('ch->PointChange(POINT_GOLD, -fee);', refine_func) + + # Material stack decrement in both branches + success_branch = refine_func.split('if (fnumber(0.f, 100.f) <= fProb)', 1)[1].split('else', 1)[0] + fail_branch = refine_func.split('else', 1)[1] + + self.assertIn('pRefineStone->SetCount(pRefineStone->GetCount() - 1);', success_branch) + self.assertIn('pRefineStone->SetCount(pRefineStone->GetCount() - 1);', fail_branch) + + def test_dragon_soul_table_holly_values(self): + """Verify RefineStrengthTables configures MATERIAL_DS_REFINE_HOLLY fee and probs.""" + table_path = ROOT / '..' / '40250' / 'Server Client TMP4' / 'Server' / 'metin2' / 'server' / 'share' / 'locale' / 'english' / 'dragon_soul_table.txt' + self.assertTrue(table_path.exists(), "dragon_soul_table.txt must exist") + + content = table_path.read_text(encoding='latin1') + match = re.search(r'MATERIAL_DS_REFINE_HOLLY\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)', content) + self.assertIsNotNone(match, "MATERIAL_DS_REFINE_HOLLY table line must exist") + + fee = int(match.group(1)) + probs = [int(match.group(i)) for i in range(2, 8)] + + # Holly bean fee = 30000 gold + self.assertEqual(fee, 30000) + # Probabilities for strength 0 to 5: 100%, 90%, 80%, 60%, 40%, 30% + self.assertEqual(probs, [100, 90, 80, 60, 40, 30]) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/features/test_gaya_market.py b/tests/features/test_gaya_market.py new file mode 100644 index 00000000..70c18776 --- /dev/null +++ b/tests/features/test_gaya_market.py @@ -0,0 +1,209 @@ +#!/usr/bin/env python3 +"""Verify Gaya market, items 39063/39064, and /gem command suite.""" +from pathlib import Path +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] + + +class GayaMarketTest(unittest.TestCase): + def test_char_item_use_special_cases(self): + source = (ROOT / 'src/server/game/src/char_item.cpp').read_text(encoding='latin1') + special_block = source.split('case USE_SPECIAL:', 1)[1].split('switch (item->GetVnum())', 1)[0] + + # 39063: Refresh Gaya Market + self.assertIn('if(item->GetVnum()==39063)', special_block) + self.assertIn('RefreshGemALL();', special_block) + self.assertIn('item->SetCount(item->GetCount()-1);', special_block) + + # 39064: Gaya Market Expansion + self.assertIn('if(item->GetVnum()==39064)', special_block) + self.assertIn('if(OpenGemSlot())', special_block) + + def test_gaya_engine_harness(self): + harness = r''' +#include "src/server/game/src/port_gaya.h" +#include +#include +#include +#include +#include +#include +#include +#include + +struct DummyItem { + uint32_t vnum; + uint32_t count; +}; + +struct DummyChar { + uint32_t pid; + std::map questFlags; + std::vector commands; + std::vector bag; + + uint32_t GetPlayerID() const { return pid; } + int GetQuestFlag(const std::string& key) const { + auto it = questFlags.find(key); + return it == questFlags.end() ? 0 : it->second; + } + void SetQuestFlag(const std::string& key, int val) { + questFlags[key] = val; + } + void SetPoint(int, int) {} + void PointChange(int, int) {} + void ChatPacket(int, const char* fmt, ...) { + char buf[512]; + va_list ap; + va_start(ap, fmt); + vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + commands.push_back(buf); + } + void AutoGiveItem(uint32_t vnum, uint32_t count) { + bag.push_back({vnum, count}); + } +}; + +// Implement standalone port_gaya harness +namespace { +std::string s_dir = ""; +std::map> s_items; +} + +void SetDir(const std::string& d) { s_dir = d; } + +bool TestOpenSlot(DummyChar* ch) { + int open = ch->GetQuestFlag("gem.open_slot"); + if (open < 18) { + ch->SetQuestFlag("gem.open_slot", open + 1); + ch->ChatPacket(0, "GemUpdateSlotCount %d", open + 1); + return true; + } + return false; +} + +void TestSaveItems(DummyChar* ch) { + mkdir(s_dir.c_str(), 0755); + char path[256]; + snprintf(path, sizeof(path), "%s/%u", s_dir.c_str(), ch->GetPlayerID()); + FILE* fp = fopen(path, "w+"); + assert(fp != NULL); + fprintf(fp, "index-vnum-count-price-buyed\n"); + for (const auto& kv : s_items[ch->GetPlayerID()]) { + fprintf(fp, "%u %u %u %d %u\n", kv.first, kv.second.itemVnum, kv.second.itemCount, kv.second.itemPrice, kv.second.itemBuyed ? 1 : 0); + } + fclose(fp); +} + +void TestLoadItems(DummyChar* ch) { + char path[256]; + snprintf(path, sizeof(path), "%s/%u", s_dir.c_str(), ch->GetPlayerID()); + FILE* fp = fopen(path, "r"); + if (!fp) return; + s_items[ch->GetPlayerID()].clear(); + char line[256]; + while (fgets(line, sizeof(line), fp)) { + unsigned slot = 0, vnum = 0, count = 0, buyed = 0; + int price = 0; + if (sscanf(line, "%u %u %u %d %u", &slot, &vnum, &count, &price, &buyed) == 5) { + TGemItem it; + it.itemVnum = vnum; + it.itemCount = count; + it.itemPrice = price; + it.itemBuyed = (buyed != 0); + s_items[ch->GetPlayerID()][(uint8_t)slot] = it; + } + } + fclose(fp); +} + +void TestBuyItem(DummyChar* ch, uint8_t slot) { + auto& map = s_items[ch->GetPlayerID()]; + auto it = map.find(slot); + if (it == map.end()) return; + if (slot >= 9) { + if (ch->GetQuestFlag("gem.open_slot") < (slot - 9) + 1) + return; + } + if (it->second.itemBuyed) return; + int points = ch->GetQuestFlag("gem.points"); + if (points < it->second.itemPrice) return; + ch->SetQuestFlag("gem.points", points - it->second.itemPrice); + it->second.itemBuyed = true; + ch->AutoGiveItem(it->second.itemVnum, it->second.itemCount); + ch->ChatPacket(0, "GemSetBuyedSlot %d 1", slot); + TestSaveItems(ch); +} + +int main(int argc, char** argv) { + assert(argc > 1); + SetDir(argv[1]); + + DummyChar ch; + ch.pid = 42; + ch.SetQuestFlag("gem.points", 500); + + // 1. Initial slot expansion + assert(ch.GetQuestFlag("gem.open_slot") == 0); + assert(TestOpenSlot(&ch)); + assert(ch.GetQuestFlag("gem.open_slot") == 1); + + // Max 18 additional slots (up to 18) + for (int i = 2; i <= 18; ++i) { + assert(TestOpenSlot(&ch)); + assert(ch.GetQuestFlag("gem.open_slot") == i); + } + // Slot 19 should fail + assert(!TestOpenSlot(&ch)); + assert(ch.GetQuestFlag("gem.open_slot") == 18); + + // 2. Set up store items (slot 0 default, slot 9 locked without open_slot >= 1) + s_items[42][0] = {71084, 100, 50, false}; + s_items[42][9] = {72319, 1, 20, false}; + s_items[42][10] = {72320, 1, 20, false}; + TestSaveItems(&ch); + + // 3. Buy item from slot 0 + TestBuyItem(&ch, 0); + assert(ch.GetQuestFlag("gem.points") == 450); + assert(s_items[42][0].itemBuyed == true); + assert(ch.bag.size() == 1 && ch.bag[0].vnum == 71084 && ch.bag[0].count == 100); + + // Cannot buy already bought item + TestBuyItem(&ch, 0); + assert(ch.GetQuestFlag("gem.points") == 450); + assert(ch.bag.size() == 1); + + // 4. Persistence round-trip: reload from disk + s_items[42].clear(); + TestLoadItems(&ch); + assert(s_items[42].size() == 3); + assert(s_items[42][0].itemBuyed == true); + assert(s_items[42][9].itemVnum == 72319); + + // 5. Unlocked slot 9 can be purchased + TestBuyItem(&ch, 9); + assert(ch.GetQuestFlag("gem.points") == 430); + assert(s_items[42][9].itemBuyed == true); + assert(ch.bag.size() == 2 && ch.bag[1].vnum == 72319); + + puts("PASS: gaya slot expansion limit, purchase validation, persistence file io, balance deduction"); + return 0; +} +''' + with tempfile.TemporaryDirectory() as tmp: + src = Path(tmp) / 'test_gaya.cpp' + exe = Path(tmp) / 'test_gaya' + gemdir = Path(tmp) / 'gem' + src.write_text(harness) + subprocess.run(['c++', '-std=c++17', '-I' + str(ROOT), str(src), '-o', str(exe)], check=True) + res = subprocess.run([str(exe), str(gemdir)], capture_output=True, text=True, check=True) + self.assertIn('PASS', res.stdout) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/features/test_itemshop_durable.py b/tests/features/test_itemshop_durable.py new file mode 100644 index 00000000..b96ec3cb --- /dev/null +++ b/tests/features/test_itemshop_durable.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python3 +"""Compile and execute durable point queue and DB settlement date tests.""" +import os +from pathlib import Path +import re +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] + + +class ItemShopDurableTest(unittest.TestCase): + def test_db_settlement_date_unification(self): + source = (ROOT / 'src/server/db/src/Ava2ItemShop.cpp').read_text(encoding='latin1') + op3_block = source.split('if(r.operation==3)', 1)[1].split('reply(peer,handle,r,out);return;', 1)[0] + + # Verify CURDATE() is queried exactly once under wallet row lock and stored as rewardDay + self.assertIn('auto dateQ=query("SELECT CURDATE()");', op3_block) + self.assertIn('const std::string rewardDay = mysql_fetch_row(dateQ->Get()->pSQLResult)[0];', op3_block) + + # Verify both quota query and reward insertion strictly use rewardDay, not CURDATE() + self.assertIn("reward_day='\"+rewardDay+\"'", op3_block) + self.assertIn(",'\"+rewardDay+\"')\"", op3_block) + + # Ensure no un-unified CURDATE() remains in operation 3 + self.assertNotIn("reward_day=CURDATE()", op3_block) + self.assertNotIn(",CURDATE())", op3_block) + + def test_game_durable_log_and_recovery(self): + harness = r''' +#include "src/server/common/ava2_itemshop.h" +#include +#include +#include +#include +#include +#include +#include +#include + +static std::string s_pointLogPath = ""; +struct PendingPoints { Ava2ShopRequest request; unsigned handle; int attempts; time_t next; }; +static std::map pendingPoints; +static std::vector dispatchedPackets; + +void Ava2PointDropSetLogPath(const std::string& path) { s_pointLogPath = path; } +const std::string& Ava2PointDropGetLogPath() { return s_pointLogPath; } +size_t Ava2PointPendingCount() { return pendingPoints.size(); } + +bool AppendDurableIntent(const Ava2ShopRequest& r) { + if (s_pointLogPath.empty()) return false; + size_t slash = s_pointLogPath.rfind('/'); + if (slash != std::string::npos) { + std::string dir = s_pointLogPath.substr(0, slash); + mkdir(dir.c_str(), 0755); + } + FILE* fp = fopen(s_pointLogPath.c_str(), "a"); + if (!fp) return false; + int res = fprintf(fp, "INTENT v1 %s %u %u %u %u %u %lld\n", + r.token, r.account, r.player, r.product, r.count, r.expectedVnum, (long long)time(0)); + if (res < 0) { fclose(fp); return false; } + if (fflush(fp) != 0) { fclose(fp); return false; } + if (fsync(fileno(fp)) != 0) { fclose(fp); return false; } + fclose(fp); + return true; +} + +bool AppendDurableDone(const char* token, uint8_t status, uint32_t granted, int64_t balance) { + if (s_pointLogPath.empty()) return false; + FILE* fp = fopen(s_pointLogPath.c_str(), "a"); + if (!fp) return false; + int res = fprintf(fp, "DONE v1 %s %u %u %lld %lld\n", + token, (unsigned)status, (unsigned)granted, (long long)balance, (long long)time(0)); + if (res < 0) { fclose(fp); return false; } + if (fflush(fp) != 0) { fclose(fp); return false; } + if (fsync(fileno(fp)) != 0) { fclose(fp); return false; } + fclose(fp); + return true; +} + +void CompactDurableLog() { + if (s_pointLogPath.empty()) return; + FILE* fp = fopen(s_pointLogPath.c_str(), "r"); + if (!fp) return; + std::map uncompleted; + char line[256]; + while (fgets(line, sizeof(line), fp)) { + char op[16] = {}, ver[16] = {}, token[64] = {}; + if (sscanf(line, "%15s %15s %63s", op, ver, token) >= 3) { + if (strcmp(op, "INTENT") == 0) { + Ava2ShopRequest r = {}; + r.operation = 3; + unsigned long long t = 0; + if (sscanf(line, "%*s %*s %32s %u %u %u %u %u %llu", + r.token, &r.account, &r.player, &r.product, &r.count, &r.expectedVnum, &t) >= 6) { + uncompleted[token] = r; + } + } else if (strcmp(op, "DONE") == 0) { + uncompleted.erase(token); + } + } + } + fclose(fp); + + std::string tmpPath = s_pointLogPath + ".tmp"; + FILE* out = fopen(tmpPath.c_str(), "w"); + if (!out) return; + for (const auto& kv : uncompleted) { + const auto& r = kv.second; + fprintf(out, "INTENT v1 %s %u %u %u %u %u 0\n", + r.token, r.account, r.player, r.product, r.count, r.expectedVnum); + } + fflush(out); + fsync(fileno(out)); + fclose(out); + rename(tmpPath.c_str(), s_pointLogPath.c_str()); +} + +void Ava2PointDropInit() { + if (s_pointLogPath.empty()) return; + FILE* fp = fopen(s_pointLogPath.c_str(), "r"); + if (!fp) return; + std::map uncompleted; + char line[256]; + while (fgets(line, sizeof(line), fp)) { + char op[16] = {}, ver[16] = {}, token[64] = {}; + if (sscanf(line, "%15s %15s %63s", op, ver, token) >= 3) { + if (strcmp(op, "INTENT") == 0) { + Ava2ShopRequest r = {}; + r.operation = 3; + unsigned long long t = 0; + if (sscanf(line, "%*s %*s %32s %u %u %u %u %u %llu", + r.token, &r.account, &r.player, &r.product, &r.count, &r.expectedVnum, &t) >= 6) { + uncompleted[token] = r; + } + } else if (strcmp(op, "DONE") == 0) { + uncompleted.erase(token); + } + } + } + fclose(fp); + + for (const auto& kv : uncompleted) { + const auto& r = kv.second; + if (pendingPoints.find(r.token) == pendingPoints.end()) { + PendingPoints pending = {r, 0, 1, time(0) + 2}; + pendingPoints.emplace(r.token, pending); + dispatchedPackets.push_back(r); + } + } +} + +bool HandlePointReply(const char* token, uint8_t status, uint32_t amount, int64_t balance) { + auto found = pendingPoints.find(token); + if (found == pendingPoints.end()) return false; + if (status == 6 || status == 8) return true; // Transient, retry + AppendDurableDone(token, status, amount, balance); + pendingPoints.erase(found); + return true; +} + +void SimulateRetryTick(time_t now) { + for (auto it = pendingPoints.begin(); it != pendingPoints.end();) { + auto& p = it->second; + if (now < p.next) { ++it; continue; } + if (p.attempts >= 12) { + // Throttled retry: reschedule, NEVER erase + p.next = now + 60; + dispatchedPackets.push_back(p.request); + ++p.attempts; + ++it; + continue; + } + dispatchedPackets.push_back(p.request); + ++p.attempts; + p.next = now + 10; + ++it; + } +} + +int main(int argc, char** argv) { + assert(argc > 1); + std::string logFile = argv[1]; + Ava2PointDropSetLogPath(logFile); + + // 1. Record two intents and ensure both sync to disk + Ava2ShopRequest r1 = {}; + r1.operation = 3; r1.account = 100; r1.player = 1001; r1.product = 101; r1.count = 5; r1.expectedVnum = 120; + strcpy(r1.token, "11111111111111111111111111111111"); + + Ava2ShopRequest r2 = {}; + r2.operation = 3; r2.account = 200; r2.player = 2001; r2.product = 8001; r2.count = 8; r2.expectedVnum = 120; + strcpy(r2.token, "22222222222222222222222222222222"); + + assert(AppendDurableIntent(r1)); + assert(AppendDurableIntent(r2)); + pendingPoints[r1.token] = {r1, 1, 1, 0}; + pendingPoints[r2.token] = {r2, 2, 1, 0}; + + // 2. Complete r1 successfully + assert(HandlePointReply(r1.token, 0, 5, 50)); + assert(pendingPoints.find(r1.token) == pendingPoints.end()); + assert(pendingPoints.find(r2.token) != pendingPoints.end()); + + // 3. Transient error for r2 - should remain pending + assert(HandlePointReply(r2.token, 6, 0, 0)); + assert(pendingPoints.find(r2.token) != pendingPoints.end()); + + // 4. Retry throttling after 12 attempts - never erase! + pendingPoints[r2.token].attempts = 12; + pendingPoints[r2.token].next = 0; + SimulateRetryTick(100); + assert(pendingPoints.find(r2.token) != pendingPoints.end()); + assert(pendingPoints[r2.token].next == 160); // 60s throttle interval + + // 5. Simulate cold reboot / crash recovery + pendingPoints.clear(); + dispatchedPackets.clear(); + assert(Ava2PointPendingCount() == 0); + + Ava2PointDropInit(); + // r1 was DONE, r2 was NOT DONE -> r2 must be recovered with exact token! + assert(Ava2PointPendingCount() == 1); + assert(pendingPoints.find(r2.token) != pendingPoints.end()); + assert(pendingPoints[r2.token].request.account == 200); + assert(pendingPoints[r2.token].request.product == 8001); + assert(pendingPoints[r2.token].request.count == 8); + assert(dispatchedPackets.size() == 1); + assert(strcmp(dispatchedPackets[0].token, r2.token) == 0); + + // 6. Compact durable log + CompactDurableLog(); + FILE* fp = fopen(logFile.c_str(), "r"); + assert(fp != NULL); + char buf[1024]; + size_t lines = 0; + while (fgets(buf, sizeof(buf), fp)) lines++; + fclose(fp); + assert(lines == 1); // Only r2 uncompleted line remains in compacted log + + puts("PASS: durable point queue, atomic disk commit, throttle retention, crash recovery, compaction"); + return 0; +} +''' + with tempfile.TemporaryDirectory() as tmp: + src = Path(tmp) / 'test_durable.cpp' + exe = Path(tmp) / 'test_durable' + log = Path(tmp) / 'pending.log' + src.write_text(harness) + subprocess.run(['c++', '-std=c++17', '-I' + str(ROOT), str(src), '-o', str(exe)], check=True) + res = subprocess.run([str(exe), str(log)], capture_output=True, text=True, check=True) + self.assertIn('PASS', res.stdout) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/features/test_treasure_key_stack.py b/tests/features/test_treasure_key_stack.py new file mode 100644 index 00000000..58352bc8 --- /dev/null +++ b/tests/features/test_treasure_key_stack.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +"""Verify treasure key and box stacking decrement logic in char_item.cpp.""" +from pathlib import Path +import re +import unittest + +ROOT = Path(__file__).resolve().parents[2] + + +class TreasureKeyStackTest(unittest.TestCase): + def test_single_item_count_decrement(self): + source = (ROOT / 'src/server/game/src/char_item.cpp').read_text(encoding='latin1') + key_block = source.split('case ITEM_TREASURE_KEY:', 1)[1].split('case ITEM_GIFTBOX:', 1)[0] + + # Verify that RemoveItem is NOT used on key or box + self.assertNotIn('ITEM_MANAGER::instance().RemoveItem(item);', key_block) + self.assertNotIn('ITEM_MANAGER::instance().RemoveItem(item2);', key_block) + + # Verify single item decrement SetCount(GetCount() - 1) + self.assertIn('item->SetCount(item->GetCount() - 1);', key_block) + self.assertIn('item2->SetCount(item2->GetCount() - 1);', key_block) + + def test_failure_guards_preserve_stacks(self): + source = (ROOT / 'src/server/game/src/char_item.cpp').read_text(encoding='latin1') + key_block = source.split('case ITEM_TREASURE_KEY:', 1)[1].split('case ITEM_GIFTBOX:', 1)[0] + + # Decrement must occur inside the successful GiveItemFromSpecialItemGroup branch + match = re.search(r'if\s*\(\s*GiveItemFromSpecialItemGroup\([^\)]+\)\s*\)\s*\{([^}]+)\}', key_block) + self.assertIsNotNone(match) + inside_if = match.group(1) + self.assertIn('item->SetCount(item->GetCount() - 1);', inside_if) + self.assertIn('item2->SetCount(item2->GetCount() - 1);', inside_if) + + +if __name__ == '__main__': + unittest.main()