Compare commits
13
Commits
main
...
b5e06c9a43
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b5e06c9a43 | ||
|
|
6924dc9b49 | ||
|
|
aa0afefe86 | ||
|
|
e8ace59fcd | ||
|
|
5b7442ea37 | ||
|
|
c979b53762 | ||
|
|
a7152750fb | ||
|
|
d1c1572ddb | ||
|
|
792d4d50b3 | ||
|
|
0b995c480d | ||
|
|
85b831db91 | ||
|
|
d63781e5fd | ||
|
|
f8bb455d9f |
@@ -599,7 +599,17 @@
|
||||
"original_price": 39,
|
||||
"source_type": "ITEM_USE",
|
||||
"source_subtype": "USE_CHANGE_ATTRIBUTE",
|
||||
"status": "pending_implementation_and_live_acceptance"
|
||||
"status": "implemented_pending_live_acceptance",
|
||||
"evidence": [
|
||||
"metin2-server/tests/features/test_product_costume_runtime.py",
|
||||
"metin2-client/tests/wiki/test_costume_products.py"
|
||||
],
|
||||
"remaining_acceptance": [
|
||||
"matching game/client/resource staging",
|
||||
"actual item use and inventory consumption",
|
||||
"relogin and channel change",
|
||||
"Android device operation"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 74,
|
||||
@@ -607,7 +617,17 @@
|
||||
"original_price": 69,
|
||||
"source_type": "ITEM_USE",
|
||||
"source_subtype": "USE_CHANGE_ATTRIBUTE",
|
||||
"status": "pending_implementation_and_live_acceptance"
|
||||
"status": "implemented_pending_live_acceptance",
|
||||
"evidence": [
|
||||
"metin2-server/tests/features/test_product_costume_runtime.py",
|
||||
"metin2-client/tests/wiki/test_costume_products.py"
|
||||
],
|
||||
"remaining_acceptance": [
|
||||
"matching game/client/resource staging",
|
||||
"actual item use and inventory consumption",
|
||||
"relogin and channel change",
|
||||
"Android device operation"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 75,
|
||||
@@ -927,7 +947,17 @@
|
||||
"original_price": 9,
|
||||
"source_type": "ITEM_USE",
|
||||
"source_subtype": "USE_TIME_CHARGE_PER",
|
||||
"status": "pending_implementation_and_live_acceptance"
|
||||
"status": "implemented_pending_live_acceptance",
|
||||
"evidence": [
|
||||
"metin2-server/tests/features/test_dragonsoul_alchemy.py",
|
||||
"metin2-client/tools/server/ava2-items/tests/test_items.py"
|
||||
],
|
||||
"remaining_acceptance": [
|
||||
"matching game/client/resource staging",
|
||||
"actual item use and inventory consumption",
|
||||
"relogin and channel change",
|
||||
"Android device operation"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 145,
|
||||
@@ -935,7 +965,17 @@
|
||||
"original_price": 17,
|
||||
"source_type": "ITEM_USE",
|
||||
"source_subtype": "USE_TIME_CHARGE_FIX",
|
||||
"status": "pending_implementation_and_live_acceptance"
|
||||
"status": "implemented_pending_live_acceptance",
|
||||
"evidence": [
|
||||
"metin2-server/tests/features/test_dragonsoul_alchemy.py",
|
||||
"metin2-client/tools/server/ava2-items/tests/test_items.py"
|
||||
],
|
||||
"remaining_acceptance": [
|
||||
"matching game/client/resource staging",
|
||||
"actual item use and inventory consumption",
|
||||
"relogin and channel change",
|
||||
"Android device operation"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 146,
|
||||
@@ -1351,7 +1391,17 @@
|
||||
"original_price": 19,
|
||||
"source_type": "ITEM_USE",
|
||||
"source_subtype": "USE_SPECIAL",
|
||||
"status": "pending_implementation_and_live_acceptance"
|
||||
"status": "implemented_pending_live_acceptance",
|
||||
"evidence": [
|
||||
"metin2-server/tests/features/test_economy.py",
|
||||
"metin2-server/tests/features/test_gaya_runtime.py",
|
||||
"metin2-client/tools/server/ava2-items/tests/test_items.py"
|
||||
],
|
||||
"remaining_acceptance": [
|
||||
"actual item click and reconnect settlement",
|
||||
"actual catalogue refresh/slot increase and count decrement",
|
||||
"channel change and Android operation"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 234,
|
||||
@@ -1359,7 +1409,17 @@
|
||||
"original_price": 19,
|
||||
"source_type": "ITEM_USE",
|
||||
"source_subtype": "USE_SPECIAL",
|
||||
"status": "pending_implementation_and_live_acceptance"
|
||||
"status": "implemented_pending_live_acceptance",
|
||||
"evidence": [
|
||||
"metin2-server/tests/features/test_economy.py",
|
||||
"metin2-server/tests/features/test_gaya_runtime.py",
|
||||
"metin2-client/tools/server/ava2-items/tests/test_items.py"
|
||||
],
|
||||
"remaining_acceptance": [
|
||||
"actual item click and reconnect settlement",
|
||||
"actual catalogue refresh/slot increase and count decrement",
|
||||
"channel change and Android operation"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 235,
|
||||
@@ -1409,5 +1469,13 @@
|
||||
"source_subtype": "0",
|
||||
"status": "pending_implementation_and_live_acceptance"
|
||||
}
|
||||
]
|
||||
],
|
||||
"platform_evidence": {
|
||||
"android_resource_smoke": {
|
||||
"status": "PASS",
|
||||
"count": 168,
|
||||
"evidence": "metin2-client/audit/evidence/ava2-products-device-20261021/device-icons.json",
|
||||
"scope": "template/icon resource path load only; gameplay, actual purchase and item effects remain unverified"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -296,5 +296,63 @@
|
||||
"original_price": 60,
|
||||
"basis": "ported body/hair/mount-skin fixed enchants; game/src/port_costume_attr.cpp and make_items.ENCHANT_KEEP"
|
||||
}
|
||||
],
|
||||
"candidates_pending_acceptance": [
|
||||
{
|
||||
"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",
|
||||
"status": "pending_real_behavior_and_platform_acceptance"
|
||||
},
|
||||
{
|
||||
"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",
|
||||
"status": "pending_real_behavior_and_platform_acceptance"
|
||||
},
|
||||
{
|
||||
"id": 149,
|
||||
"vnum": 100500,
|
||||
"original_price": 4,
|
||||
"basis": "dragon soul strength refine material (holly bean); game/src/DragonSoul.cpp DSManager::DoRefineStrength",
|
||||
"status": "pending_real_behavior_and_platform_acceptance"
|
||||
},
|
||||
{
|
||||
"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",
|
||||
"status": "pending_real_behavior_and_platform_acceptance"
|
||||
},
|
||||
{
|
||||
"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",
|
||||
"status": "pending_real_behavior_and_platform_acceptance"
|
||||
},
|
||||
{
|
||||
"id": 240,
|
||||
"vnum": 77921,
|
||||
"original_price": 1,
|
||||
"basis": "copper treasure key for box 77918; game/src/char_item.cpp single-count decrement",
|
||||
"status": "pending_real_behavior_and_platform_acceptance"
|
||||
},
|
||||
{
|
||||
"id": 241,
|
||||
"vnum": 77922,
|
||||
"original_price": 2,
|
||||
"basis": "silver treasure key for box 77919; game/src/char_item.cpp single-count decrement",
|
||||
"status": "pending_real_behavior_and_platform_acceptance"
|
||||
},
|
||||
{
|
||||
"id": 242,
|
||||
"vnum": 77923,
|
||||
"original_price": 5,
|
||||
"basis": "gold treasure key for box 77920; game/src/char_item.cpp single-count decrement",
|
||||
"status": "pending_real_behavior_and_platform_acceptance"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -33,6 +33,21 @@ public:
|
||||
|
||||
/// 발렌타인 사랑의 팬던트
|
||||
static const bool IsLovePendant(DWORD vnum) { return 71145 == vnum; }
|
||||
|
||||
#if defined(ENABLE_ATTR_6TH_7TH) || defined(__BL_67_ATTR__)
|
||||
static DWORD Get67MaterialVnum(const int iLevelLimit)
|
||||
{
|
||||
if (iLevelLimit >= 0 && iLevelLimit <= 45)
|
||||
return 39070;
|
||||
if (iLevelLimit >= 46 && iLevelLimit <= 75)
|
||||
return 39071;
|
||||
if (iLevelLimit >= 76 && iLevelLimit <= 105)
|
||||
return 39072;
|
||||
if (iLevelLimit >= 106 && iLevelLimit <= 120)
|
||||
return 39073;
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
};
|
||||
|
||||
class CMobVnumHelper
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
#pragma once
|
||||
#include "cube_recipe.h"
|
||||
#include "economy.h"
|
||||
#include <array>
|
||||
#include <functional>
|
||||
|
||||
// Candidate DB-side batch contract. Not a client packet or permission to mutate
|
||||
// a live actor. A DB coordinator must first establish the matching durable fence.
|
||||
namespace PortCube {
|
||||
struct Item {
|
||||
PortEconomy::Reward value;
|
||||
uint16_t cell=0;
|
||||
bool usable=true;
|
||||
};
|
||||
struct Batch {
|
||||
uint32_t account=0,player=0;
|
||||
uint64_t epoch=0,gold=0;
|
||||
std::string owner,token;
|
||||
Recipe recipe;
|
||||
unsigned attempts=0;
|
||||
std::vector<Item> inventory;
|
||||
// Factory-created templates with reserved, never-reused IDs. No item rows
|
||||
// have been created yet; count=1 is replaced only by successful output.
|
||||
std::vector<PortEconomy::Reward> rewards;
|
||||
};
|
||||
inline bool Identity(const std::string& s) {
|
||||
if(s.size()!=32||s==std::string(32,'0'))return false;
|
||||
return std::all_of(s.begin(),s.end(),[](char c){return (c>='0'&&c<='9')||(c>='a'&&c<='f');});
|
||||
}
|
||||
inline bool Validate(const Batch& b) {
|
||||
Recipe recipe=b.recipe;
|
||||
if(!b.account||!b.player||!b.epoch||!Identity(b.owner)||!Identity(b.token)||
|
||||
b.gold>uint64_t(PortEconomy::GoldLimit)||!Normalize(recipe)||recipe.id>MaxRecipes||recipe.copy||
|
||||
!b.attempts||b.attempts>MaxAttempts||b.inventory.size()>225)return false;
|
||||
// Only canonical normalized recipes are accepted. No uninitialized copy
|
||||
// semantics, duplicate requirements or reordered NPCs enter the journal.
|
||||
if(recipe.npcs!=b.recipe.npcs||recipe.materials.size()!=b.recipe.materials.size()||
|
||||
!std::equal(recipe.materials.begin(),recipe.materials.end(),b.recipe.materials.begin(),
|
||||
[](const Material& a,const Material& c){return a.vnum==c.vnum&&a.count==c.count;}))return false;
|
||||
const uint64_t maximum=uint64_t(recipe.rewardCount)*b.attempts;
|
||||
const unsigned stacks=recipe.stackable?unsigned((maximum+1999)/2000):unsigned(maximum);
|
||||
if(b.rewards.size()!=stacks||stacks>100)return false;
|
||||
std::set<uint32_t> ids;int last=-1;
|
||||
for(const auto& i:b.inventory) {
|
||||
if(!i.value.id||!i.value.vnum||!i.value.count||i.value.count>2000||i.cell>=225||
|
||||
int(i.cell)<=last||!ids.insert(i.value.id).second)return false;
|
||||
last=i.cell;
|
||||
}
|
||||
for(const auto& r:b.rewards)if(!r.id||r.vnum!=recipe.reward||r.count!=1||!ids.insert(r.id).second)return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Explicit little-endian bounded codec, never sizeof(Batch) or padded structs.
|
||||
// It is deliberately separate from the legacy client/game protocol.
|
||||
struct Writer {
|
||||
std::string data;
|
||||
void n(uint64_t value,unsigned bytes){for(unsigned i=0;i<bytes;++i){data+=char(value&255);value>>=8;}}
|
||||
void s(const std::string& text){n(text.size(),2);data+=text;}
|
||||
void reward(const PortEconomy::Reward& r){
|
||||
n(r.id,4);n(r.vnum,4);n(r.count,4);
|
||||
for(auto x:r.sockets)n(uint32_t(x),4);
|
||||
for(unsigned i=0;i<7;++i){n(r.types[i],1);n(uint16_t(r.values[i]),2);}
|
||||
for(auto x:r.extra)n(x,1);
|
||||
}
|
||||
void items(const std::vector<Item>& rows){n(rows.size(),2);for(const auto& i:rows){reward(i.value);n(i.cell,2);n(i.usable,1);}}
|
||||
};
|
||||
struct Reader {
|
||||
const std::string& data;size_t at=0;bool ok=true;
|
||||
explicit Reader(const std::string& value):data(value){}
|
||||
uint64_t n(unsigned bytes){
|
||||
if(!ok||bytes>8||at>data.size()||bytes>data.size()-at){ok=false;return 0;}
|
||||
uint64_t value=0;for(unsigned i=0;i<bytes;++i)value|=uint64_t(uint8_t(data[at++]))<<(8*i);return value;
|
||||
}
|
||||
std::string s(unsigned maximum){const auto count=n(2);if(!ok||count>maximum||count>data.size()-at){ok=false;return {};}
|
||||
std::string value=data.substr(at,size_t(count));at+=size_t(count);return value;}
|
||||
PortEconomy::Reward reward(){
|
||||
PortEconomy::Reward r;r.id=uint32_t(n(4));r.vnum=uint32_t(n(4));r.count=uint32_t(n(4));
|
||||
for(auto& x:r.sockets){uint32_t bits=uint32_t(n(4));std::memcpy(&x,&bits,4);}
|
||||
for(unsigned i=0;i<7;++i){r.types[i]=uint8_t(n(1));uint16_t bits=uint16_t(n(2));std::memcpy(&r.values[i],&bits,2);}
|
||||
for(auto& x:r.extra)x=uint8_t(n(1));return r;
|
||||
}
|
||||
std::vector<Item> items(){
|
||||
const auto count=n(2);if(count>225){ok=false;return {};}
|
||||
std::vector<Item> rows;for(unsigned i=0;i<count&&ok;++i){Item item;item.value=reward();item.cell=uint16_t(n(2));auto usable=n(1);if(usable>1)ok=false;item.usable=usable!=0;rows.push_back(item);}return rows;
|
||||
}
|
||||
};
|
||||
inline std::string Encode(const Batch& b) {
|
||||
Writer w;w.n(1,4);w.n(b.account,4);w.n(b.player,4);w.n(b.epoch,8);w.n(b.gold,8);w.s(b.owner);w.s(b.token);
|
||||
const auto& r=b.recipe;w.n(r.id,4);w.n(r.reward,4);w.n(r.rewardCount,4);w.n(r.gold,4);w.n(r.percent,1);w.n(r.stackable,1);w.n(r.copy,1);w.s(r.category);
|
||||
w.n(r.npcs.size(),1);for(auto n:r.npcs)w.n(n,4);
|
||||
w.n(r.materials.size(),1);for(auto m:r.materials){w.n(m.vnum,4);w.n(m.count,4);}
|
||||
w.n(b.attempts,1);w.items(b.inventory);w.n(b.rewards.size(),1);for(const auto& item:b.rewards)w.reward(item);
|
||||
return w.data;
|
||||
}
|
||||
inline bool Decode(const std::string& data,Batch& out) {
|
||||
if(data.size()>40000)return false;
|
||||
Reader r(data);Batch b;if(r.n(4)!=1)return false;
|
||||
b.account=uint32_t(r.n(4));b.player=uint32_t(r.n(4));b.epoch=r.n(8);b.gold=r.n(8);b.owner=r.s(32);b.token=r.s(32);
|
||||
auto& recipe=b.recipe;recipe.id=uint32_t(r.n(4));recipe.reward=uint32_t(r.n(4));recipe.rewardCount=uint32_t(r.n(4));recipe.gold=uint32_t(r.n(4));recipe.percent=unsigned(r.n(1));
|
||||
auto stack=r.n(1),copy=r.n(1);if(stack>1||copy>1)return false;recipe.stackable=stack!=0;recipe.copy=copy!=0;recipe.category=r.s(24);
|
||||
auto count=r.n(1);if(count>128)return false;for(unsigned i=0;i<count&&r.ok;++i)recipe.npcs.push_back(uint32_t(r.n(4)));
|
||||
count=r.n(1);if(count>5)return false;for(unsigned i=0;i<count&&r.ok;++i){Material m;m.vnum=uint32_t(r.n(4));m.count=uint32_t(r.n(4));recipe.materials.push_back(m);}
|
||||
b.attempts=unsigned(r.n(1));b.inventory=r.items();count=r.n(1);if(count>100)return false;for(unsigned i=0;i<count&&r.ok;++i)b.rewards.push_back(r.reward());
|
||||
if(!r.ok||r.at!=data.size()||!Validate(b)||Encode(b)!=data)return false;out=std::move(b);return true;
|
||||
}
|
||||
struct Proto {unsigned size=0;bool stackable=false;};
|
||||
using Lookup=std::function<Proto(uint32_t)>;
|
||||
struct Settlement {
|
||||
std::string result="invalid";
|
||||
unsigned successes=0;
|
||||
uint64_t fee=0;
|
||||
std::vector<Take> takes;
|
||||
std::vector<Item> awards;
|
||||
};
|
||||
inline Settlement SettlePlan(const Batch& b,const std::string& rolls,const Lookup& lookup) {
|
||||
Settlement s;if(!Validate(b)||rolls.size()!=b.attempts)return s;
|
||||
for(unsigned char roll:rolls){if(roll<1||roll>100)return s;s.successes+=roll<=b.recipe.percent;}
|
||||
const auto reward=lookup(b.recipe.reward);
|
||||
if(reward.size<1||reward.size>3||reward.stackable!=b.recipe.stackable){s.result="item_proto";return s;}
|
||||
std::vector<Input> inputs;for(const auto& i:b.inventory)inputs.push_back({i.value.id,i.value.vnum,i.value.count,i.cell,i.usable});
|
||||
const auto p=Preview(b.recipe,b.attempts,inputs,int64_t(b.gold));
|
||||
if(!p.valid)return s;
|
||||
if(!p.materialsOK){s.result="materials_missing";return s;}
|
||||
if(!p.goldOK){s.result="gold_missing";return s;}
|
||||
auto inventory=b.inventory;
|
||||
auto occupy=[&](const std::vector<Item>& rows,std::array<bool,225>& used)->bool {
|
||||
for(const auto& i:rows) {
|
||||
if(!i.value.count)continue;const auto proto=lookup(i.value.vnum);
|
||||
if(proto.size<1||proto.size>3||(!proto.stackable&&i.value.count!=1)||(i.cell%45)/5+proto.size>9)return false;
|
||||
for(unsigned j=0;j<proto.size;++j){const unsigned at=i.cell+5*j;if(at>=225||used[at])return false;used[at]=true;}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
std::array<bool,225> used={};
|
||||
if(!occupy(inventory,used)){s.result="inventory_invalid";return s;}
|
||||
for(const auto& take:p.takes)for(auto& i:inventory)if(i.value.id==take.id)i.value.count-=take.count;
|
||||
used.fill(false);if(!occupy(inventory,used))return s;
|
||||
uint64_t remaining=uint64_t(b.recipe.rewardCount)*s.successes;unsigned next=0;
|
||||
while(remaining) {
|
||||
unsigned cell=225;
|
||||
for(unsigned at=0;at<225;++at) {
|
||||
if((at%45)/5+reward.size>9)continue;bool free=true;
|
||||
for(unsigned j=0;j<reward.size;++j)if(used[at+5*j])free=false;
|
||||
if(free){cell=at;break;}
|
||||
}
|
||||
if(cell==225){s.awards.clear();s.result="capacity_full";return s;}
|
||||
Item item;item.value=b.rewards[next++];item.value.count=uint32_t(std::min(remaining,uint64_t(reward.stackable?2000:1)));item.cell=uint16_t(cell);
|
||||
for(unsigned j=0;j<reward.size;++j)used[cell+5*j]=true;
|
||||
remaining-=item.value.count;s.awards.push_back(item);
|
||||
}
|
||||
s.result="ok";s.fee=p.gold;s.takes=p.takes;return s;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
#include "cube_handshake.h"
|
||||
namespace PortCube {
|
||||
class CraftFlow {
|
||||
public:
|
||||
enum Stage {Idle,WaitPrepare,WaitExecute,Complete,Held};
|
||||
private:
|
||||
Handshake identity;Stage stage=Idle;CraftReceipt receipt;
|
||||
public:
|
||||
Stage State()const{return stage;}
|
||||
const CraftReceipt& Receipt()const{return receipt;}
|
||||
bool MayRetry()const{return stage==WaitPrepare||stage==WaitExecute;}
|
||||
bool Start(const Handshake& bound,bool cleanFrozen,bool sourceAcknowledged) {
|
||||
auto f=bound;f.message=Message::Prepare;f.status=Status::None;f.body.clear();
|
||||
if(stage!=Idle||!cleanFrozen||!sourceAcknowledged||!ValidHandshake(f))return false;identity=std::move(f);stage=WaitPrepare;return true;
|
||||
}
|
||||
Handshake Request()const{auto f=identity;f.message=stage==WaitExecute?Message::Execute:Message::Prepare;return f;}
|
||||
void Invalidate(){if(stage!=Idle)stage=Held;}
|
||||
bool Answer(const Handshake& f,const Batch& b,const Lookup& lookup) {
|
||||
if(b.account!=identity.account||b.player!=identity.player||b.epoch!=identity.epoch||b.owner!=identity.owner||b.token!=identity.token)return false;
|
||||
if(!ValidHandshake(f)||f.message!=Message::CraftAnswer||!SameIdentity(identity,f)||f.cookie!=identity.cookie||!MayRetry()&&stage!=Complete)return false;
|
||||
if(f.status==Status::Held)return MayRetry();
|
||||
if(f.status==Status::Prepared){if(stage==WaitPrepare){stage=WaitExecute;return true;}return stage==WaitExecute;}
|
||||
if(f.status!=Status::Complete||stage==WaitPrepare)return false;
|
||||
CraftReceipt result;if(!DecodeCraftReceipt(f.body,result)||!ValidateCraftReceipt(b,result,lookup))return false;
|
||||
if(stage==Complete){if(EncodeCraftReceipt(receipt)==f.body)return true;stage=Held;return false;}
|
||||
receipt=std::move(result);stage=Complete;return true; // never authorizes local assets, saves, ACK or thaw
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
#include "cube_batch.h"
|
||||
|
||||
namespace PortCube {
|
||||
// Transport-independent correlation core. The runtime adapter must bind session
|
||||
// to the actual game peer/character generation and not accept it from a client.
|
||||
class Drain {
|
||||
std::string identity;
|
||||
uint64_t session=0,mainEpoch=0,asyncEpoch=0;
|
||||
unsigned pass=0;
|
||||
bool asyncDone=false,failed=false;
|
||||
public:
|
||||
bool Start(const Batch& batch,uint64_t ownerSession,uint64_t main,uint64_t async) {
|
||||
if(!identity.empty()||!Validate(batch)||!ownerSession)return false;
|
||||
identity=Encode(batch);session=ownerSession;mainEpoch=main;asyncEpoch=async;return true;
|
||||
}
|
||||
// Return 1 only for the FIRST main barrier: adapter must enqueue the second
|
||||
// main FIFO barrier and the async FIFO barrier after processing that callback.
|
||||
// Numbered passes prevent a duplicate first callback completing the drain.
|
||||
unsigned Main(const Batch& b,uint64_t sourceSession,unsigned number,bool error) {
|
||||
if(identity!=Encode(b)||sourceSession!=session||number!=pass+1||number>2)return 0;
|
||||
failed|=error;pass=number;return pass==1?1:2;
|
||||
}
|
||||
bool Async(const Batch& b,uint64_t sourceSession,bool error) {
|
||||
if(identity!=Encode(b)||sourceSession!=session||pass<1||asyncDone)return false;
|
||||
failed|=error;asyncDone=true;return true;
|
||||
}
|
||||
bool Matches(const Batch& b,uint64_t sourceSession)const{return !identity.empty()&&identity==Encode(b)&&sourceSession==session;}
|
||||
bool Complete()const{return pass==2&&asyncDone;}
|
||||
bool Clean(uint64_t main,uint64_t async)const{return Complete()&&!failed&&main==mainEpoch&&async==asyncEpoch;}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
#pragma once
|
||||
#include "cube_store.h"
|
||||
#include "cube_drain.h"
|
||||
#include "cube_gold_intent.h"
|
||||
#include "cube_owner_types.h"
|
||||
|
||||
namespace PortCube {
|
||||
// DB-side lifecycle, not an actor-freeze implementation. Only a trusted runtime
|
||||
// coordinator may call these methods after binding the session and all owners.
|
||||
template<class DB> class FenceStore {
|
||||
DB& db;Lookup lookup;
|
||||
using Rows=PortEconomy::Rows;
|
||||
static std::string N(uint64_t n){return std::to_string(n);}
|
||||
static std::string X(const std::string& s){return "X'"+PortEconomy::Hex(s.data(),s.size())+"'";}
|
||||
bool Q(const std::string& sql,Rows& rows){return db.Query(sql,rows)&&!db.warnings;}
|
||||
bool Run(const std::string& sql){Rows rows;return Q(sql,rows);}
|
||||
bool Change(const std::string& sql){return Run(sql)&&db.affected==1;}
|
||||
struct Guard {DB& db;~Guard(){db.Rollback();}};
|
||||
bool Lock(const Batch& b,Rows& rows) {
|
||||
if(!Run("INSERT INTO port_economy_account_lock(account) VALUES("+N(b.account)+") ON DUPLICATE KEY UPDATE account=VALUES(account)")||
|
||||
!Q("SELECT account FROM port_economy_account_lock WHERE account="+N(b.account)+" FOR UPDATE",rows)||rows.size()!=1)return false;
|
||||
return Q("SELECT account,epoch,owner,request,phase,body,image,drain_state FROM port_cube_fences WHERE pid="+N(b.player)+" FOR UPDATE",rows);
|
||||
}
|
||||
bool Same(const Batch& b,const Rows& rows)const {
|
||||
return rows.size()==1&&rows[0].size()==8&&rows[0][0]==N(b.account)&&rows[0][1]==N(b.epoch)&&rows[0][2]==b.owner&&rows[0][3]==b.token&&rows[0][5]==Encode(b);
|
||||
}
|
||||
static bool Signed(const std::string& s,int64_t low,int64_t high,int64_t& out) {
|
||||
if(s.empty())return false;const bool negative=s[0]=='-';uint64_t n=0;
|
||||
if(!PortEconomy::Number(negative?s.substr(1):s,n,uint64_t(negative?-low:high)))return false;
|
||||
out=negative?-int64_t(n):int64_t(n);return out>=low&&out<=high&&std::to_string(out)==s;
|
||||
}
|
||||
bool Image(const Batch& b,std::string& image) {
|
||||
Rows rows;uint64_t gold=0;
|
||||
if(!Q("SELECT gold FROM player WHERE id="+N(b.player)+" AND account_id="+N(b.account)+" FOR UPDATE",rows)||rows.size()!=1||rows[0].size()!=1||!PortEconomy::Number(rows[0][0],gold,PortEconomy::GoldLimit))return false;
|
||||
std::string columns="id,vnum,count,pos";for(unsigned i=0;i<3;++i)columns+=",socket"+N(i);
|
||||
for(unsigned i=0;i<7;++i)columns+=",attrtype"+N(i)+",attrvalue"+N(i);columns+=",port_extra";
|
||||
if(!Q("SELECT "+columns+" FROM item WHERE owner_id="+N(b.player)+" AND window='INVENTORY' AND pos<225 ORDER BY pos,id FOR UPDATE",rows)||rows.size()>225)return false;
|
||||
std::vector<Item> items;std::set<uint32_t> ids;std::array<bool,225> used={};int last=-1;
|
||||
for(const auto& row:rows) {
|
||||
if(row.size()!=22)return false;
|
||||
Item i;uint64_t n=0;int64_t signedValue=0;
|
||||
auto number=[&](unsigned field,uint64_t max)->bool {return PortEconomy::Number(row[field],n,max);};
|
||||
if(!number(0,UINT32_MAX)||!n)return false;i.value.id=uint32_t(n);
|
||||
if(!number(1,UINT32_MAX)||!n)return false;i.value.vnum=uint32_t(n);
|
||||
if(!number(2,2000)||!n)return false;i.value.count=uint32_t(n);
|
||||
if(!number(3,224))return false;i.cell=uint16_t(n);
|
||||
if(int(i.cell)<=last||!ids.insert(i.value.id).second)return false;last=i.cell;
|
||||
for(unsigned j=0;j<3;++j){if(!Signed(row[4+j],INT32_MIN,INT32_MAX,signedValue))return false;i.value.sockets[j]=int32_t(signedValue);}
|
||||
for(unsigned j=0;j<7;++j){if(!number(7+2*j,255))return false;i.value.types[j]=uint8_t(n);if(!Signed(row[8+2*j],INT16_MIN,INT16_MAX,signedValue))return false;i.value.values[j]=int16_t(signedValue);}
|
||||
if(row[21].size()!=69)return false;std::memcpy(i.value.extra,row[21].data(),69);
|
||||
const auto proto=lookup(i.value.vnum);if(proto.size<1||proto.size>3||(!proto.stackable&&i.value.count!=1)||(i.cell%45)/5+proto.size>9)return false;
|
||||
for(unsigned j=0;j<proto.size;++j){const unsigned cell=i.cell+5*j;if(cell>=225||used[cell])return false;used[cell]=true;}
|
||||
items.push_back(i);
|
||||
}
|
||||
Writer w;w.n(gold,8);w.items(items);image=std::move(w.data);return true;
|
||||
}
|
||||
public:
|
||||
enum Result { Retry, Refused, Done };
|
||||
FenceStore(DB& database,Lookup proto):db(database),lookup(std::move(proto)){}
|
||||
// cachedIds must include ALL owned dirty item IDs captured by the DB adapter
|
||||
// before eviction, not merely the normal-inventory recipe inputs.
|
||||
Result Begin(const Batch& b,const std::vector<uint32_t>& cachedIds,const std::function<bool(bool)>& ownership={}) {
|
||||
if(!Validate(b)||cachedIds.size()>4096)return Refused;
|
||||
BatchStore<DB> ready(db,lookup);if(!ready.Ready()||!db.Begin())return Retry;Guard guard{db};Rows rows;
|
||||
if(!Lock(b,rows))return Retry;
|
||||
if(Same(b,rows))return !ownership||ownership(true)?Done:Refused; // never invent missing ownership on replay
|
||||
if(!rows.empty()) {
|
||||
uint64_t previous=0;if(rows.size()!=1||rows[0].size()!=8||rows[0][4]!="RELEASED"||rows[0][3]==b.token||!PortEconomy::Number(rows[0][1],previous)||b.epoch<=previous)return Refused;
|
||||
}
|
||||
if(!Q("SELECT token FROM port_economy_pending WHERE pid="+N(b.player)+" FOR UPDATE",rows))return Retry;if(!rows.empty())return Refused;
|
||||
if(!Q("SELECT token FROM port_cube_requests WHERE token='"+b.token+"' FOR UPDATE",rows))return Retry;if(!rows.empty())return Refused;
|
||||
// The drain itself can survive a restart before Prepare. Reserve every
|
||||
// reward ID now, not only after RNG preparation, so boot cannot reuse it.
|
||||
for(const auto& reward:b.rewards) {
|
||||
if(!Q("SELECT id FROM item WHERE id="+N(reward.id)+" UNION ALL SELECT id FROM port_economy_custody WHERE id="+N(reward.id)+" UNION ALL SELECT id FROM port_economy_item_reservations WHERE id="+N(reward.id),rows))return Retry;
|
||||
if(!rows.empty())return Refused;
|
||||
if(!Change("INSERT INTO port_economy_item_reservations(id,request) VALUES("+N(reward.id)+",'"+b.token+"')"))return Retry;
|
||||
}
|
||||
std::set<uint32_t> ids;
|
||||
for(auto id:cachedIds){if(!id)return Refused;ids.insert(id);}
|
||||
for(const auto& i:b.inventory)ids.insert(i.value.id);for(const auto& i:b.rewards)ids.insert(i.id);
|
||||
if(!Q("SELECT id FROM item WHERE owner_id="+N(b.player)+" AND window NOT IN ('MALL','SAFEBOX') FOR UPDATE",rows))return Retry;
|
||||
if(rows.size()>4096)return Refused;
|
||||
for(const auto& row:rows){uint64_t id=0;if(row.size()!=1||!PortEconomy::Number(row[0],id,UINT32_MAX)||!id)return Retry;ids.insert(uint32_t(id));}
|
||||
const auto body=Encode(b);
|
||||
if(!Run("DELETE FROM port_cube_fences WHERE pid="+N(b.player)+" AND phase='RELEASED'")||
|
||||
!Change("INSERT INTO port_cube_fences(pid,account,epoch,owner,request,phase,body,image,drain_state) VALUES("+N(b.player)+","+N(b.account)+","+N(b.epoch)+",'"+b.owner+"','"+b.token+"','DRAINING',"+X(body)+",X'',0)"))return Retry;
|
||||
for(auto id:ids)if(!Change("INSERT INTO port_cube_item_fences(id,pid,epoch,request) VALUES("+N(id)+","+N(b.player)+","+N(b.epoch)+",'"+b.token+"')"))return Retry;
|
||||
if(ownership&&!ownership(false))return Refused;
|
||||
return db.Commit()?Done:Retry;
|
||||
}
|
||||
Result FinishDrain(const Batch& b,const Drain& drain,uint64_t session,uint64_t main,uint64_t async,bool stillOwner) {
|
||||
if(!Validate(b)||!drain.Matches(b,session)||!drain.Complete())return Refused;
|
||||
BatchStore<DB> ready(db,lookup);if(!ready.Ready()||!db.Begin())return Retry;Guard guard{db};Rows rows;
|
||||
if(!Lock(b,rows))return Retry;if(!Same(b,rows))return Refused;
|
||||
const char* phase=stillOwner&&drain.Clean(main,async)?"FROZEN":"ABORTED";
|
||||
if(rows[0][4]==phase&&rows[0][7]==(std::string(phase)=="FROZEN"?"1":"2"))return Done;
|
||||
if(rows[0][4]!="DRAINING")return Refused;
|
||||
if(!Change("UPDATE port_cube_fences SET phase='"+std::string(phase)+"',drain_state="+(phase==std::string("FROZEN")?"1":"2")+" WHERE pid="+N(b.player)+" AND phase='DRAINING'"))return Retry;
|
||||
return db.Commit()?Done:Retry;
|
||||
}
|
||||
Result AbortUnprepared(const Batch& b) {
|
||||
if(!Validate(b))return Refused;BatchStore<DB> ready(db,lookup);
|
||||
if(!ready.Ready()||!db.Begin())return Retry;Guard guard{db};Rows rows;
|
||||
if(!Lock(b,rows))return Retry;if(!Same(b,rows))return Refused;
|
||||
if(rows[0][4]=="ABORTED"&&rows[0][7]=="2")return Done;
|
||||
if(rows[0][4]!="FROZEN"||rows[0][7]!="1")return Refused;
|
||||
if(!Q("SELECT token FROM port_cube_requests WHERE token='"+b.token+"' FOR UPDATE",rows))return Retry;
|
||||
if(!rows.empty())return Refused; // an ambiguous prepare must be queried, not cancelled blindly
|
||||
if(!Change("UPDATE port_cube_fences SET phase='ABORTED',drain_state=2 WHERE pid="+N(b.player)+" AND phase='FROZEN'")||!db.Commit())return Retry;
|
||||
return Done;
|
||||
}
|
||||
Result Recover(uint32_t account,uint32_t player,Batch& batch,std::string& phase,std::string& image) {
|
||||
batch={};phase.clear();image.clear();if(!account||!player)return Refused;
|
||||
BatchStore<DB> ready(db,lookup);if(!ready.Ready()||!db.Begin())return Retry;Guard guard{db};Rows rows;
|
||||
if(!Q("SELECT account,epoch,owner,request,phase,body,image,drain_state FROM port_cube_fences WHERE pid="+N(player)+" AND account="+N(account)+" FOR UPDATE",rows))return Retry;
|
||||
if(rows.empty())return Refused;
|
||||
if(rows.size()!=1||rows[0].size()!=8||!Decode(rows[0][5],batch)||batch.account!=account||batch.player!=player||!Same(batch,rows)||rows[0][6].size()>40000)return Retry;
|
||||
const std::set<std::string> states={"DRAINING","FROZEN","ABORTED","RESYNC","RELEASED"};
|
||||
const auto& stage=rows[0][4];const auto& drained=rows[0][7];
|
||||
if(!states.count(stage)||(stage=="DRAINING"&&drained!="0")||(stage=="FROZEN"&&drained!="1")||(stage=="ABORTED"&&drained!="2")||((stage=="RESYNC"||stage=="RELEASED")&&drained!="1"&&drained!="2"))return Retry;
|
||||
phase=stage;image=rows[0][6];return Done;
|
||||
}
|
||||
Result Resync(const Batch& b,std::string& image,const std::function<bool(const std::string&)>& ownership={}) {
|
||||
image.clear();if(!Validate(b))return Refused;
|
||||
BatchStore<DB> ready(db,lookup);if(!ready.Ready()||!db.Begin())return Retry;Guard guard{db};Rows rows;
|
||||
if(!Lock(b,rows))return Retry;if(!Same(b,rows))return Refused;
|
||||
const auto phase=rows[0][4],drained=rows[0][7],saved=rows[0][6];
|
||||
if(!ownership){const int owner=OwnerReleaseStatus(db,b);if(owner<0)return Retry;if(!owner)return Refused;}
|
||||
if(phase!="ABORTED"&&phase!="FROZEN"&&phase!="RESYNC")return Refused;
|
||||
if(!Q("SELECT state FROM port_cube_requests WHERE token='"+b.token+"' AND account="+N(b.account)+" AND pid="+N(b.player)+" FOR UPDATE",rows))return Retry;
|
||||
if(drained!="1"&&drained!="2")return Refused;
|
||||
if((drained=="2"&&!rows.empty())||(drained=="1"&&(rows.size()!=1||rows[0].size()!=1||rows[0][0]!="DONE")))return Refused;
|
||||
{const int clear=GoldIntentsStatus(db,b);if(clear<0)return Retry;if(!clear)return Refused;}
|
||||
std::string current;if(!Image(b,current))return Retry;
|
||||
if(ownership&&!ownership(current))return Refused;
|
||||
if(ownership&&phase=="RESYNC"&&saved!=current)return Refused; // never replace an owner's previously issued image
|
||||
if(!Run("UPDATE port_cube_fences SET phase='RESYNC',image="+X(current)+" WHERE pid="+N(b.player))||!db.Commit())return Retry;
|
||||
image=std::move(current);return Done;
|
||||
}
|
||||
// ACK is the exact canonical image, not an FNV hash or a timeout. The game
|
||||
// adapter must verify it has applied that image to this still-frozen owner.
|
||||
Result Release(const Batch& b,const std::string& acknowledged,const std::function<bool(bool)>& ownership={}) {
|
||||
if(!Validate(b)||acknowledged.empty()||acknowledged.size()>40000)return Refused;
|
||||
BatchStore<DB> ready(db,lookup);if(!ready.Ready()||!db.Begin())return Retry;Guard guard{db};Rows rows;
|
||||
if(!Lock(b,rows))return Retry;if(!Same(b,rows)||rows[0][6]!=acknowledged)return Refused;
|
||||
if(!ownership){const int owner=OwnerReleaseStatus(db,b);if(owner<0)return Retry;if(!owner)return Refused;}
|
||||
if(rows[0][4]=="RELEASED")return !ownership||ownership(true)?Done:Refused;
|
||||
if(rows[0][4]!="RESYNC")return Refused;
|
||||
{const int clear=GoldIntentsStatus(db,b);if(clear<0)return Retry;if(!clear)return Refused;}
|
||||
std::string current;if(!Image(b,current))return Retry;if(current!=acknowledged)return Refused;
|
||||
// Trusted coordinator callback shares this account transaction. It must
|
||||
// validate current ownership and atomically archive/retire the lease.
|
||||
if(ownership&&!ownership(false))return Refused;
|
||||
if(!Run("DELETE FROM port_cube_item_fences WHERE pid="+N(b.player)+" AND epoch="+N(b.epoch)+" AND request='"+b.token+"'")||
|
||||
!Change("UPDATE port_cube_fences SET phase='RELEASED' WHERE pid="+N(b.player)+" AND phase='RESYNC'")||!db.Commit())return Retry;
|
||||
return Done;
|
||||
}
|
||||
// Resume preflight only. A historical Release replay does not reread current
|
||||
// assets; this check MUST lock and validate the current image anew, on the
|
||||
// same pinned connection/account transaction as the authority callback.
|
||||
Result CheckReleasedImage(const Batch& b,const std::string& expected,const std::function<bool()>& authority) {
|
||||
if(!Validate(b)||expected.empty()||expected.size()>40000||!authority)return Refused;
|
||||
BatchStore<DB> ready(db,lookup);if(!ready.Ready()||!db.Begin())return Retry;Guard guard{db};Rows rows;
|
||||
if(!Lock(b,rows))return Retry;
|
||||
if(!Same(b,rows)||rows[0][4]!="RELEASED"||rows[0][6]!=expected||rows[0][7]!="1")return Refused;
|
||||
{const int clear=GoldIntentsStatus(db,b);if(clear<0)return Retry;if(!clear)return Refused;}
|
||||
std::string current;if(!Image(b,current))return Retry;if(current!=expected||!authority())return Refused;
|
||||
return db.Commit()?Done:Retry;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
#pragma once
|
||||
#include "cube_store.h"
|
||||
#include "cube_gold_source.h"
|
||||
namespace PortCube {
|
||||
// Positive reward intents ONLY. Not a generic PointChange replacement, item
|
||||
// snapshot, permission to mint currency, or proof a source event is legitimate.
|
||||
constexpr unsigned GoldIntentLimit=1024,GoldIntentBytes=129;
|
||||
static_assert(GoldIntentLimit==GoldSourceLimit,"source manifest covers every intent sequence");
|
||||
struct GoldIntent {
|
||||
uint32_t account=0,player=0,sequence=0;
|
||||
uint64_t epoch=0,amount=0;
|
||||
uint8_t source=0; // trusted producer registry: 1 combat, 2 quest, 3 delivery
|
||||
std::string owner,request,event;
|
||||
};
|
||||
inline bool ValidGoldIntent(const GoldIntent& i) {
|
||||
return i.account&&i.player&&i.epoch&&i.sequence&&i.sequence<=GoldIntentLimit&&
|
||||
i.amount&&i.amount<=uint64_t(PortEconomy::GoldLimit)&&i.source>=1&&i.source<=3&&
|
||||
Identity(i.owner)&&Identity(i.request)&&Identity(i.event);
|
||||
}
|
||||
inline bool Matches(const GoldIntent& i,const Batch& b) {
|
||||
return i.account==b.account&&i.player==b.player&&i.epoch==b.epoch&&i.owner==b.owner&&i.request==b.token;
|
||||
}
|
||||
inline std::string EncodeGoldIntent(const GoldIntent& i) {
|
||||
if(!ValidGoldIntent(i))return {};
|
||||
Writer w;w.n(1,4);w.n(i.account,4);w.n(i.player,4);w.n(i.epoch,8);w.n(i.sequence,4);w.n(i.amount,8);w.n(i.source,1);
|
||||
w.data+=i.owner;w.data+=i.request;w.data+=i.event;return w.data;
|
||||
}
|
||||
inline bool DecodeGoldIntent(const std::string& bytes,GoldIntent& i) {
|
||||
i={};if(bytes.size()!=GoldIntentBytes)return false;Reader r(bytes);if(r.n(4)!=1)return false;
|
||||
GoldIntent out;out.account=uint32_t(r.n(4));out.player=uint32_t(r.n(4));out.epoch=r.n(8);out.sequence=uint32_t(r.n(4));out.amount=r.n(8);out.source=uint8_t(r.n(1));
|
||||
out.owner=bytes.substr(r.at,32);out.request=bytes.substr(r.at+32,32);out.event=bytes.substr(r.at+64,32);
|
||||
if(!r.ok||!ValidGoldIntent(out)||EncodeGoldIntent(out)!=bytes)return false;i=std::move(out);return true;
|
||||
}
|
||||
template<class DB> int GoldSchema(DB& db) {
|
||||
PortEconomy::Rows rows;
|
||||
const std::string names="('port_cube_gold_version','port_cube_gold_intents','port_cube_gold_sources')";
|
||||
if(!db.Query("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME IN "+names,rows)||db.warnings||rows.size()!=1||rows[0].size()!=1)return -1;
|
||||
if(rows[0][0]=="0")return 0;
|
||||
if(rows[0][0]!="3"||!db.Query("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND ENGINE='InnoDB' AND TABLE_NAME IN "+names,rows)||db.warnings||rows.size()!=1||rows[0].size()!=1||rows[0][0]!="3")return -1;
|
||||
if(!db.Query("SELECT version FROM port_cube_gold_version WHERE id=1",rows)||db.warnings||rows.size()!=1||rows[0].size()!=1||rows[0][0]!="2")return -1;
|
||||
return 1;
|
||||
}
|
||||
struct GoldRecord {GoldIntent intent;bool applied=false;uint64_t before=0,after=0;};
|
||||
// Caller holds the account lock. No inferred deltas from a stale game snapshot.
|
||||
template<class DB> bool GoldRecords(DB& db,const Batch& b,std::vector<GoldRecord>& records) {
|
||||
records.clear();PortEconomy::Rows rows;
|
||||
if(!db.Query("SELECT event,seq,account,pid,body,state,before_gold,after_gold FROM port_cube_gold_intents WHERE request='"+b.token+"' ORDER BY seq FOR UPDATE",rows)||db.warnings||rows.size()>GoldIntentLimit)return false;
|
||||
bool pending=false;std::set<std::string> ids;uint64_t previous=0;
|
||||
for(const auto& row:rows) {
|
||||
GoldRecord record;if(row.size()!=8||!DecodeGoldIntent(row[4],record.intent)||!Matches(record.intent,b))return false;
|
||||
const auto& i=record.intent;
|
||||
if(i.sequence!=records.size()+1||row[0]!=i.event||row[1]!=std::to_string(i.sequence)||row[2]!=std::to_string(i.account)||row[3]!=std::to_string(i.player)||!ids.insert(i.event).second)return false;
|
||||
if(!PortEconomy::Number(row[6],record.before,PortEconomy::GoldLimit)||!PortEconomy::Number(row[7],record.after,PortEconomy::GoldLimit))return false;
|
||||
record.applied=row[5]=="APPLIED";
|
||||
if(record.applied) {
|
||||
if(pending||record.before>uint64_t(PortEconomy::GoldLimit)-i.amount||record.after!=record.before+i.amount||(!records.empty()&&record.before!=previous))return false;
|
||||
previous=record.after;
|
||||
} else {if(row[5]!="QUEUED"||record.before||record.after)return false;pending=true;}
|
||||
records.push_back(std::move(record));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
template<class DB> int GoldCreditBase(DB& db,const Batch& b,uint64_t& base) {
|
||||
PortEconomy::Rows rows;typename BatchStore<DB>::Receipt receipt;
|
||||
if(!db.Query("SELECT body,rolls,state,result,successes,fee,awards FROM port_cube_requests WHERE token='"+b.token+"' AND account="+std::to_string(b.account)+" AND pid="+std::to_string(b.player)+" FOR UPDATE",rows)||db.warnings)return -1;
|
||||
if(rows.size()!=1||!BatchStore<DB>::DoneReceipt(b,rows[0],receipt)||receipt.fee>b.gold)return 0;
|
||||
base=b.gold-receipt.fee;return 1;
|
||||
}
|
||||
template<class DB> int GoldIntentsStatus(DB& db,const Batch& b) {
|
||||
const int schema=GoldSchema(db);if(schema==0)return 1;if(schema<0)return -1;
|
||||
std::vector<GoldRecord> records;if(!GoldRecords(db,b,records))return -1;
|
||||
// Even zero credits need an explicit closed-source proof. SQL emptiness
|
||||
// cannot exclude a local durable intent whose delivery has not arrived.
|
||||
PortEconomy::Rows seals;
|
||||
if(!db.Query("SELECT account,pid,epoch,owner,session,cookie,handle,manifest FROM port_cube_gold_sources WHERE request='"+b.token+"' FOR UPDATE",seals)||db.warnings)return -1;
|
||||
if(seals.empty())return 0;
|
||||
if(seals.size()!=1||seals[0].size()!=8)return -1;
|
||||
const auto& row=seals[0];GoldSourceSeal seal;static_cast<GoldSourceBinding&>(seal)=GoldSourceFor(b,0,0,0);
|
||||
uint64_t cookie=0,handle=0;
|
||||
if(row[0]!=std::to_string(b.account)||row[1]!=std::to_string(b.player)||row[2]!=std::to_string(b.epoch)||row[3]!=b.owner||
|
||||
!PortEconomy::Number(row[4],seal.session)||!PortEconomy::Number(row[5],cookie,UINT32_MAX)||!PortEconomy::Number(row[6],handle,UINT32_MAX))return -1;
|
||||
seal.cookie=uint32_t(cookie);seal.handle=uint32_t(handle);
|
||||
if(EncodeGoldSourceBinding(seal).empty()||!DecodeGoldManifest(row[7],seal.events)||seal.events.size()!=records.size())return -1;
|
||||
for(size_t n=0;n<records.size();++n)if(records[n].intent.event!=seal.events[n])return -1;
|
||||
for(const auto& record:records)if(!record.applied)return 0;
|
||||
if(!records.empty()) {
|
||||
uint64_t base=0,current=0;PortEconomy::Rows rows;
|
||||
const int ready=GoldCreditBase(db,b,base);if(ready<0)return -1;if(!ready||records.front().before!=base)return 0;
|
||||
if(!db.Query("SELECT gold FROM player WHERE id="+std::to_string(b.player)+" AND account_id="+std::to_string(b.account)+" FOR UPDATE",rows)||db.warnings)return -1;
|
||||
if(rows.size()!=1||rows[0].size()!=1||!PortEconomy::Number(rows[0][0],current,PortEconomy::GoldLimit)||current!=records.back().after)return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
#pragma once
|
||||
#include "cube_gold_intent.h"
|
||||
#include <cerrno>
|
||||
#include <fcntl.h>
|
||||
#include <sys/file.h>
|
||||
#include <sys/stat.h>
|
||||
#include <tuple>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace PortCube {
|
||||
// Core-private, bounded append-only journal. ACK means DB has the immutable
|
||||
// intent, NOT that currency is applied or the actor may thaw. Keep ACK history
|
||||
// so a restarted writer cannot reuse a sequence. No automatic compaction yet.
|
||||
struct GoldDelivery {
|
||||
GoldIntent intent;
|
||||
uint64_t session=0;
|
||||
uint32_t cookie=0,handle=0,ground=0,vnum=0,map=0;
|
||||
};
|
||||
constexpr size_t GoldDeliveryBytes=GoldIntentBytes+28;
|
||||
inline std::string EncodeGoldDelivery(const GoldDelivery& d) {
|
||||
const auto body=EncodeGoldIntent(d.intent);
|
||||
if(body.empty()||d.intent.source!=1||!d.session||!d.cookie||!d.handle||!d.ground||!d.vnum||!d.map)return {};
|
||||
Writer w;w.data=body;w.n(d.session,8);w.n(d.cookie,4);w.n(d.handle,4);w.n(d.ground,4);w.n(d.vnum,4);w.n(d.map,4);return w.data;
|
||||
}
|
||||
inline bool DecodeGoldDelivery(const std::string& body,GoldDelivery& d) {
|
||||
d={};if(body.size()!=GoldDeliveryBytes)return false;GoldDelivery out;
|
||||
if(!DecodeGoldIntent(body.substr(0,GoldIntentBytes),out.intent))return false;
|
||||
Reader r(body);r.at=GoldIntentBytes;out.session=r.n(8);out.cookie=uint32_t(r.n(4));out.handle=uint32_t(r.n(4));
|
||||
out.ground=uint32_t(r.n(4));out.vnum=uint32_t(r.n(4));out.map=uint32_t(r.n(4));
|
||||
if(!r.ok||r.at!=body.size()||EncodeGoldDelivery(out)!=body)return false;d=std::move(out);return true;
|
||||
}
|
||||
inline GoldSourceBinding GoldSourceFor(const GoldDelivery& d) {
|
||||
GoldSourceBinding s;s.account=d.intent.account;s.player=d.intent.player;s.epoch=d.intent.epoch;s.owner=d.intent.owner;s.request=d.intent.request;
|
||||
s.session=d.session;s.cookie=d.cookie;s.handle=d.handle;return s;
|
||||
}
|
||||
class GoldOutbox {
|
||||
struct Record {GoldDelivery delivery;bool acknowledged=false;};
|
||||
struct Closing {GoldSourceBinding binding;unsigned count=0;bool acknowledged=false;};
|
||||
int fd=-1,lock=-1,directory=-1;bool healthy=false;size_t bytes=0;
|
||||
std::string error;std::map<std::string,Record> records;
|
||||
std::map<std::string,Closing> sources;
|
||||
static uint32_t Hash(const std::string& body){uint32_t h=2166136261u;for(unsigned char c:body){h^=c;h*=16777619u;}return h;}
|
||||
bool Fail(const char* reason){healthy=false;error=reason;return false;}
|
||||
static bool PrivateFile(int f){struct stat s={};return fstat(f,&s)==0&&S_ISREG(s.st_mode)&&s.st_nlink==1&&s.st_uid==geteuid()&&!(s.st_mode&0022);}
|
||||
static bool WriteAll(int f,const std::string& body) {
|
||||
size_t at=0;while(at<body.size()){const auto n=write(f,body.data()+at,body.size()-at);if(n<0&&errno==EINTR)continue;if(n<=0)return false;at+=size_t(n);}return true;
|
||||
}
|
||||
static std::string ClosingBody(const Closing& c) {
|
||||
const auto binding=EncodeGoldSourceBinding(c.binding);if(binding.empty()||c.count>GoldSourceLimit)return {};
|
||||
Writer w;w.data=binding;w.n(c.count,4);w.data.resize(GoldDeliveryBytes,'\0');return w.data;
|
||||
}
|
||||
static bool DecodeClosing(const std::string& body,Closing& c) {
|
||||
c={};if(body.size()!=GoldDeliveryBytes)return false;Closing out;
|
||||
if(!DecodeGoldSourceBinding(body.substr(0,GoldSourceBindingBytes),out.binding))return false;
|
||||
Reader r(body);r.at=GoldSourceBindingBytes;out.count=unsigned(r.n(4));if(!r.ok||ClosingBody(out)!=body)return false;c=std::move(out);return true;
|
||||
}
|
||||
bool SourceImage(const GoldSourceBinding& binding,bool requireAck,GoldSourceSeal& seal)const {
|
||||
seal={};if(EncodeGoldSourceBinding(binding).empty())return false;static_cast<GoldSourceBinding&>(seal)=binding;
|
||||
std::vector<std::pair<unsigned,std::string>> ordered;
|
||||
for(const auto& entry:records)if(entry.second.delivery.intent.request==binding.request) {
|
||||
const auto& r=entry.second;
|
||||
if((requireAck&&!r.acknowledged)||EncodeGoldSourceBinding(GoldSourceFor(r.delivery))!=EncodeGoldSourceBinding(binding))return false;
|
||||
ordered.emplace_back(r.delivery.intent.sequence,r.delivery.intent.event);
|
||||
}
|
||||
std::sort(ordered.begin(),ordered.end());for(const auto& e:ordered){if(e.first!=seal.events.size()+1)return false;seal.events.push_back(e.second);}
|
||||
return !EncodeGoldManifest(seal.events).empty();
|
||||
}
|
||||
bool AppendBody(unsigned op,const std::string& body) {
|
||||
Writer w;w.data="CGO1";w.n(op,1);w.data+=body;w.n(Hash(w.data),4);const auto& frame=w.data;
|
||||
if(!healthy||frame.size()!=FrameBytes||bytes>MaxBytes-frame.size())return Fail("gold outbox unavailable/full; retain hold and journal");
|
||||
if(!WriteAll(fd,frame)||fsync(fd)!=0)return Fail("gold outbox write/sync uncertain; quarantine source and retain journal");
|
||||
bytes+=frame.size();return true;
|
||||
}
|
||||
bool Append(unsigned op,const GoldDelivery& d){return AppendBody(op,EncodeGoldDelivery(d));}
|
||||
bool Admit(const GoldDelivery& d)const {
|
||||
if(EncodeGoldDelivery(d).empty()||records.size()>=MaxRecords||sources.count(d.intent.request))return false;
|
||||
unsigned sequence=1;
|
||||
for(const auto& entry:records)if(entry.second.delivery.intent.request==d.intent.request) {
|
||||
const auto& i=entry.second.delivery.intent;
|
||||
if(i.account!=d.intent.account||i.player!=d.intent.player||i.epoch!=d.intent.epoch||i.owner!=d.intent.owner)return false;
|
||||
if(EncodeGoldSourceBinding(GoldSourceFor(entry.second.delivery))!=EncodeGoldSourceBinding(GoldSourceFor(d)))return false;
|
||||
++sequence;
|
||||
}
|
||||
return d.intent.sequence==sequence;
|
||||
}
|
||||
public:
|
||||
static constexpr size_t MaxRecords=8192,MaxBytes=16*1024*1024,FrameBytes=4+1+GoldDeliveryBytes+4;
|
||||
GoldOutbox()=default;GoldOutbox(const GoldOutbox&)=delete;GoldOutbox& operator=(const GoldOutbox&)=delete;
|
||||
~GoldOutbox(){if(fd>=0)close(fd);if(lock>=0)close(lock);if(directory>=0)close(directory);}
|
||||
bool Ready()const{return healthy;}
|
||||
const std::string& Error()const{return error;}
|
||||
bool Open(const std::string& path) {
|
||||
if(fd>=0||lock>=0||directory>=0)return Fail("gold outbox already opened");
|
||||
const auto slash=path.rfind('/');const std::string dir=slash==std::string::npos?".":slash==0?"/":path.substr(0,slash);
|
||||
const std::string name=slash==std::string::npos?path:path.substr(slash+1);
|
||||
if(name.empty()||name=="."||name=="..")return Fail("invalid gold outbox path");
|
||||
if(mkdir(dir.c_str(),0700)!=0&&errno!=EEXIST)return Fail("cannot create gold outbox directory");
|
||||
directory=open(dir.c_str(),O_RDONLY|O_DIRECTORY|O_NOFOLLOW);
|
||||
if(directory<0)return Fail("cannot open gold outbox directory");
|
||||
lock=openat(directory,(name+".lock").c_str(),O_RDWR|O_CREAT|O_NOFOLLOW,0600);
|
||||
if(lock<0||!PrivateFile(lock)||flock(lock,LOCK_EX|LOCK_NB)!=0)return Fail("gold outbox already owned/unsafe lock");
|
||||
fd=openat(directory,name.c_str(),O_RDWR|O_CREAT|O_APPEND|O_NOFOLLOW,0600);
|
||||
if(fd<0||!PrivateFile(fd)||flock(fd,LOCK_EX|LOCK_NB)!=0)return Fail("unsafe/owned gold outbox file");
|
||||
struct stat info={};if(fstat(fd,&info)!=0||info.st_size<0||uint64_t(info.st_size)>MaxBytes)return Fail("gold outbox size invalid");
|
||||
bytes=size_t(info.st_size);
|
||||
if(fsync(fd)!=0||fsync(lock)!=0||fsync(directory)!=0)return Fail("cannot persist gold outbox directory entries");
|
||||
if(bytes%FrameBytes)return Fail("torn gold outbox; retain bytes for repair");
|
||||
for(size_t at=0;at<bytes;at+=FrameBytes) {
|
||||
std::string frame(FrameBytes,'\0');size_t got=0;
|
||||
while(got<frame.size()){const auto n=pread(fd,&frame[got],frame.size()-got,off_t(at+got));if(n<0&&errno==EINTR)continue;if(n<=0)return Fail("cannot read gold outbox");got+=size_t(n);}
|
||||
Reader checksum(frame);checksum.at=FrameBytes-4;
|
||||
if(frame.substr(0,4)!="CGO1"||checksum.n(4)!=Hash(frame.substr(0,FrameBytes-4)))return Fail("corrupt gold outbox; retain bytes for repair");
|
||||
const unsigned op=uint8_t(frame[4]);const auto body=frame.substr(5,GoldDeliveryBytes);
|
||||
if(op==3||op==4) {
|
||||
Closing c;GoldSourceSeal seal;
|
||||
if(!DecodeClosing(body,c)||!SourceImage(c.binding,op==4,seal)||seal.events.size()!=c.count)return Fail("corrupt source close proof");
|
||||
auto it=sources.find(c.binding.request);
|
||||
if(op==3) {
|
||||
if(it!=sources.end()||sources.size()>=MaxRecords)return Fail("duplicate/overfull source close");
|
||||
sources.emplace(c.binding.request,c);
|
||||
} else {
|
||||
if(it==sources.end()||it->second.acknowledged||ClosingBody(it->second)!=body)return Fail("unknown/conflicting source close ACK");
|
||||
it->second.acknowledged=true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
GoldDelivery d;if(!DecodeGoldDelivery(body,d))return Fail("corrupt gold delivery body");auto it=records.find(d.intent.event);
|
||||
if(op==1) {
|
||||
if(it!=records.end()||!Admit(d))return Fail("conflicting/out-of-order gold outbox claim");
|
||||
records.emplace(d.intent.event,Record{d,false});
|
||||
} else if(op==2) {
|
||||
if(it==records.end()||it->second.acknowledged||EncodeGoldDelivery(it->second.delivery)!=EncodeGoldDelivery(d))return Fail("unknown/conflicting gold outbox ACK");
|
||||
it->second.acknowledged=true;
|
||||
} else return Fail("unknown gold outbox operation");
|
||||
}
|
||||
healthy=true;return true;
|
||||
}
|
||||
unsigned Next(const std::string& request)const {unsigned n=1;for(const auto& r:records)if(r.second.delivery.intent.request==request)++n;return n;}
|
||||
uint64_t Total(const std::string& request)const {
|
||||
uint64_t total=0;for(const auto& r:records)if(r.second.delivery.intent.request==request) {
|
||||
if(total>uint64_t(PortEconomy::GoldLimit)-r.second.delivery.intent.amount)return uint64_t(PortEconomy::GoldLimit);
|
||||
total+=r.second.delivery.intent.amount;
|
||||
}return total;
|
||||
}
|
||||
const GoldDelivery* Find(const std::string& event)const {auto it=records.find(event);return it==records.end()?nullptr:&it->second.delivery;}
|
||||
bool Claim(const GoldDelivery& d) {
|
||||
if(!healthy||EncodeGoldDelivery(d).empty())return false;auto it=records.find(d.intent.event);
|
||||
if(it!=records.end())return EncodeGoldDelivery(it->second.delivery)==EncodeGoldDelivery(d);
|
||||
if(!Admit(d)){error="gold outbox capacity/sequence/identity refused before writing";return false;}
|
||||
if(!Append(1,d))return false;records.emplace(d.intent.event,Record{d,false});return true;
|
||||
}
|
||||
bool Acknowledge(const GoldDelivery& d) {
|
||||
auto it=records.find(d.intent.event);
|
||||
if(!healthy||it==records.end()||EncodeGoldDelivery(it->second.delivery)!=EncodeGoldDelivery(d))return false;
|
||||
if(it->second.acknowledged)return true;
|
||||
if(!Append(2,d))return false;it->second.acknowledged=true;return true;
|
||||
}
|
||||
bool IsClosing(const std::string& request)const{return sources.count(request)!=0;}
|
||||
bool CloseSource(const GoldSourceBinding& binding) {
|
||||
if(!healthy)return false;GoldSourceSeal seal;if(!SourceImage(binding,false,seal))return false;
|
||||
auto it=sources.find(binding.request);Closing c{binding,unsigned(seal.events.size()),false};
|
||||
if(it!=sources.end())return ClosingBody(it->second)==ClosingBody(c);
|
||||
if(sources.size()>=MaxRecords)return false;
|
||||
// Stop new claims DURABLY before waiting for existing delivery ACKs.
|
||||
if(!AppendBody(3,ClosingBody(c)))return false;sources.emplace(binding.request,std::move(c));return true;
|
||||
}
|
||||
bool AcknowledgeSource(const GoldSourceSeal& seal) {
|
||||
if(!healthy)return false;auto it=sources.find(seal.request);GoldSourceSeal expected;
|
||||
if(it==sources.end()||EncodeGoldSourceBinding(seal)!=EncodeGoldSourceBinding(it->second.binding)||!SourceImage(seal,true,expected)||
|
||||
seal.events!=expected.events||seal.events.size()!=it->second.count)return false;
|
||||
if(it->second.acknowledged)return true;
|
||||
if(!AppendBody(4,ClosingBody(it->second)))return false;it->second.acknowledged=true;return true;
|
||||
}
|
||||
bool SourceAcknowledged(const GoldSourceBinding& binding)const {
|
||||
auto it=sources.find(binding.request);return healthy&&it!=sources.end()&&it->second.acknowledged&&EncodeGoldSourceBinding(binding)==EncodeGoldSourceBinding(it->second.binding);
|
||||
}
|
||||
std::vector<GoldSourceSeal> PendingSources()const {
|
||||
std::vector<GoldSourceSeal> out;if(!healthy)return out;
|
||||
for(const auto& entry:sources)if(!entry.second.acknowledged) {
|
||||
GoldSourceSeal seal;if(SourceImage(entry.second.binding,true,seal)&&seal.events.size()==entry.second.count)out.push_back(std::move(seal));
|
||||
}return out;
|
||||
}
|
||||
std::vector<GoldDelivery> Pending()const {
|
||||
std::vector<GoldDelivery> out;if(!healthy)return out;
|
||||
for(const auto& r:records)if(!r.second.acknowledged)out.push_back(r.second.delivery);
|
||||
std::sort(out.begin(),out.end(),[](const auto& a,const auto& b){return std::tie(a.intent.account,a.intent.player,a.intent.request,a.intent.sequence)<std::tie(b.intent.account,b.intent.player,b.intent.request,b.intent.sequence);});return out;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
#pragma once
|
||||
#include "cube_batch.h"
|
||||
namespace PortCube {
|
||||
constexpr unsigned GoldSourceLimit=1024,GoldSourceBindingBytes=96;
|
||||
struct GoldSourceBinding {
|
||||
uint32_t account=0,player=0,cookie=0,handle=0;
|
||||
uint64_t epoch=0,session=0;
|
||||
std::string owner,request;
|
||||
};
|
||||
struct GoldSourceSeal : GoldSourceBinding {std::vector<std::string> events;};
|
||||
inline std::string EncodeGoldSourceBinding(const GoldSourceBinding& s) {
|
||||
if(!s.account||!s.player||!s.epoch||!s.session||!s.cookie||!s.handle||!Identity(s.owner)||!Identity(s.request))return {};
|
||||
Writer w;w.n(s.account,4);w.n(s.player,4);w.n(s.epoch,8);w.data+=s.owner;w.data+=s.request;w.n(s.session,8);w.n(s.cookie,4);w.n(s.handle,4);return w.data;
|
||||
}
|
||||
inline bool DecodeGoldSourceBinding(const std::string& body,GoldSourceBinding& s) {
|
||||
s={};if(body.size()!=GoldSourceBindingBytes)return false;Reader r(body);GoldSourceBinding out;
|
||||
out.account=uint32_t(r.n(4));out.player=uint32_t(r.n(4));out.epoch=r.n(8);out.owner=body.substr(r.at,32);out.request=body.substr(r.at+32,32);r.at+=64;
|
||||
out.session=r.n(8);out.cookie=uint32_t(r.n(4));out.handle=uint32_t(r.n(4));
|
||||
if(!r.ok||r.at!=body.size()||EncodeGoldSourceBinding(out)!=body)return false;s=std::move(out);return true;
|
||||
}
|
||||
inline bool Matches(const GoldSourceBinding& s,const Batch& b) {
|
||||
return s.account==b.account&&s.player==b.player&&s.epoch==b.epoch&&s.owner==b.owner&&s.request==b.token;
|
||||
}
|
||||
inline std::string EncodeGoldManifest(const std::vector<std::string>& events) {
|
||||
if(events.size()>GoldSourceLimit)return {};std::set<std::string> seen;Writer w;w.n(events.size(),4);
|
||||
for(const auto& e:events){if(!Identity(e)||!seen.insert(e).second)return {};w.data+=e;}return w.data;
|
||||
}
|
||||
inline bool DecodeGoldManifest(const std::string& body,std::vector<std::string>& events) {
|
||||
events.clear();if(body.size()<4||body.size()>4+32*GoldSourceLimit)return false;Reader r(body);const auto count=r.n(4);
|
||||
if(count>GoldSourceLimit||body.size()!=4+32*count)return false;
|
||||
std::vector<std::string> out;for(size_t n=0;n<count;++n)out.push_back(body.substr(4+n*32,32));
|
||||
if(EncodeGoldManifest(out)!=body)return false;events=std::move(out);return true;
|
||||
}
|
||||
inline GoldSourceBinding GoldSourceFor(const Batch& b,uint64_t session,uint32_t cookie,uint32_t handle) {
|
||||
GoldSourceBinding s;s.account=b.account;s.player=b.player;s.epoch=b.epoch;s.owner=b.owner;s.request=b.token;s.session=session;s.cookie=cookie;s.handle=handle;return s;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
#pragma once
|
||||
#include "cube_gold_intent.h"
|
||||
namespace PortCube {
|
||||
// Candidate deferred positive-credit backend; actual ingress remains disabled.
|
||||
// Sources must durably identify an event BEFORE acknowledging delivery;
|
||||
// do not divert an already-performed PointChange here or double-credit memory.
|
||||
template<class DB> class GoldIntentStore {
|
||||
DB& db;Lookup lookup;using Rows=PortEconomy::Rows;
|
||||
static std::string N(uint64_t n){return std::to_string(n);}
|
||||
bool Q(const std::string& sql,Rows& rows){return db.Query(sql,rows)&&!db.warnings;}
|
||||
bool Run(const std::string& sql){Rows rows;return Q(sql,rows);}
|
||||
bool Change(const std::string& sql){return Run(sql)&&db.affected==1;}
|
||||
struct Guard {DB& db;~Guard(){db.Rollback();}};
|
||||
bool Account(uint32_t account) {
|
||||
Rows rows;return Run("INSERT INTO port_economy_account_lock(account) VALUES("+N(account)+") ON DUPLICATE KEY UPDATE account=VALUES(account)")&&
|
||||
Q("SELECT account FROM port_economy_account_lock WHERE account="+N(account)+" FOR UPDATE",rows)&&rows.size()==1;
|
||||
}
|
||||
bool Fence(uint32_t account,uint32_t player,Rows& rows) {
|
||||
return Q("SELECT account,epoch,owner,request,phase,body,drain_state FROM port_cube_fences WHERE pid="+N(player)+" AND account="+N(account)+" FOR UPDATE",rows);
|
||||
}
|
||||
static bool Same(const Batch& b,const Rows& rows) {
|
||||
return rows.size()==1&&rows[0].size()==7&&rows[0][0]==N(b.account)&&rows[0][1]==N(b.epoch)&&rows[0][2]==b.owner&&rows[0][3]==b.token&&rows[0][5]==Encode(b);
|
||||
}
|
||||
public:
|
||||
enum Result {Retry,Refused,Stored,Applied,Blocked};
|
||||
struct Receipt {uint64_t before=0,after=0;};
|
||||
GoldIntentStore(DB& database,Lookup proto):db(database),lookup(std::move(proto)){}
|
||||
bool Ready(){BatchStore<DB> base(db,lookup);return base.Ready()&&GoldSchema(db)==1;}
|
||||
Result Enqueue(const Batch& b,const GoldIntent& i) {
|
||||
if(!Validate(b)||!ValidGoldIntent(i)||!Matches(i,b))return Refused;
|
||||
if(!Ready()||!db.Begin())return Retry;Guard guard{db};Rows rows;
|
||||
if(!Account(b.account))return Retry;
|
||||
const auto body=EncodeGoldIntent(i);
|
||||
if(!Q("SELECT body,state,before_gold,after_gold FROM port_cube_gold_intents WHERE event='"+i.event+"' FOR UPDATE",rows))return Retry;
|
||||
if(!rows.empty()) {
|
||||
if(rows.size()!=1||rows[0].size()!=4||rows[0][0]!=body)return Refused;
|
||||
uint64_t before=0,after=0;
|
||||
if(!PortEconomy::Number(rows[0][2],before,PortEconomy::GoldLimit)||!PortEconomy::Number(rows[0][3],after,PortEconomy::GoldLimit))return Blocked;
|
||||
if(rows[0][1]=="QUEUED")return !before&&!after?Stored:Blocked;
|
||||
return rows[0][1]=="APPLIED"&&before<=uint64_t(PortEconomy::GoldLimit)-i.amount&&after==before+i.amount?Applied:Blocked;
|
||||
}
|
||||
if(!Fence(b.account,b.player,rows))return Retry;
|
||||
if(!Same(b,rows))return Blocked;
|
||||
const auto phase=rows[0][4];
|
||||
if(phase!="DRAINING"&&phase!="FROZEN"&&phase!="ABORTED")return Blocked;
|
||||
if(!Q("SELECT request FROM port_cube_gold_sources WHERE request='"+b.token+"' FOR UPDATE",rows))return Retry;
|
||||
if(!rows.empty())return Blocked; // exact historical event replay above is still allowed
|
||||
std::vector<GoldRecord> records;if(!GoldRecords(db,b,records))return Blocked;
|
||||
if(i.sequence!=records.size()+1)return Refused;
|
||||
if(!Change("INSERT INTO port_cube_gold_intents(event,request,seq,account,pid,body,state,before_gold,after_gold) VALUES('"+i.event+"','"+i.request+"',"+N(i.sequence)+","+N(i.account)+","+N(i.player)+",X'"+PortEconomy::Hex(body.data(),body.size())+"','QUEUED',0,0)"))return Retry;
|
||||
return db.Commit()?Stored:Retry;
|
||||
}
|
||||
Result CloseSource(const Batch& b,const GoldSourceSeal& seal) {
|
||||
const auto manifest=EncodeGoldManifest(seal.events);
|
||||
if(!Validate(b)||!Matches(seal,b)||EncodeGoldSourceBinding(seal).empty()||manifest.empty())return Refused;
|
||||
if(!Ready()||!db.Begin())return Retry;Guard guard{db};Rows rows;
|
||||
if(!Account(b.account))return Retry;
|
||||
const std::vector<std::string> expected={N(b.account),N(b.player),N(b.epoch),b.owner,N(seal.session),N(seal.cookie),N(seal.handle),manifest};
|
||||
if(!Q("SELECT account,pid,epoch,owner,session,cookie,handle,manifest FROM port_cube_gold_sources WHERE request='"+b.token+"' FOR UPDATE",rows))return Retry;
|
||||
if(!rows.empty())return rows.size()==1&&rows[0]==expected?Stored:Refused;
|
||||
if(!Fence(b.account,b.player,rows))return Retry;
|
||||
if(!Same(b,rows)||!((rows[0][4]=="FROZEN"&&rows[0][6]=="1")||(rows[0][4]=="ABORTED"&&rows[0][6]=="2")))return Blocked;
|
||||
std::vector<GoldRecord> records;if(!GoldRecords(db,b,records))return Blocked;
|
||||
if(records.size()!=seal.events.size())return Blocked;
|
||||
for(size_t n=0;n<records.size();++n)if(records[n].intent.event!=seal.events[n])return Refused;
|
||||
if(!Change("INSERT INTO port_cube_gold_sources(request,account,pid,epoch,owner,session,cookie,handle,manifest) VALUES('"+b.token+"',"+N(b.account)+","+N(b.player)+","+N(b.epoch)+",'"+b.owner+"',"+N(seal.session)+","+N(seal.cookie)+","+N(seal.handle)+",X'"+PortEconomy::Hex(manifest.data(),manifest.size())+"')"))return Retry;
|
||||
return db.Commit()?Stored:Retry;
|
||||
}
|
||||
// Recover accepted intents after process restart without caller-supplied
|
||||
// amounts or replacing persisted data. Pure read: does not credit anything.
|
||||
Result Pending(const Batch& b,std::vector<GoldIntent>& pending) {
|
||||
pending.clear();if(!Validate(b))return Refused;
|
||||
if(!Ready()||!db.Begin())return Retry;Guard guard{db};
|
||||
if(!Account(b.account))return Retry;
|
||||
std::vector<GoldRecord> records;if(!GoldRecords(db,b,records))return Blocked;
|
||||
for(const auto& record:records)if(!record.applied)pending.push_back(record.intent);
|
||||
return Stored;
|
||||
}
|
||||
// Only identity comes from recovery. The persisted event/body and the DONE
|
||||
// Cube receipt determine the amount and expected base. Never auto-settle a
|
||||
// PREPARED craft, overwrite a stale wallet or apply on an aborted drain.
|
||||
Result Apply(const std::string& event,uint32_t account,uint32_t player,Receipt& receipt,
|
||||
const std::function<bool(const GoldIntent&)>& authorize={}) {
|
||||
receipt={};if(!Identity(event)||!account||!player)return Refused;
|
||||
if(!Ready()||!db.Begin())return Retry;Guard guard{db};Rows rows;
|
||||
if(!Account(account)||!Q("SELECT body,state,before_gold,after_gold FROM port_cube_gold_intents WHERE event='"+event+"' AND account="+N(account)+" AND pid="+N(player)+" FOR UPDATE",rows))return Retry;
|
||||
if(rows.empty())return Refused;
|
||||
GoldIntent intent;
|
||||
if(rows.size()!=1||rows[0].size()!=4||!DecodeGoldIntent(rows[0][0],intent)||intent.event!=event||intent.account!=account||intent.player!=player)return Blocked;
|
||||
if(authorize&&!authorize(intent))return Blocked; // same account transaction/pinned connection, including historical replay
|
||||
const auto saved=rows[0];uint64_t before=0,after=0;
|
||||
if(!PortEconomy::Number(saved[2],before,PortEconomy::GoldLimit)||!PortEconomy::Number(saved[3],after,PortEconomy::GoldLimit))return Blocked;
|
||||
if(saved[1]=="APPLIED") {
|
||||
if(before>uint64_t(PortEconomy::GoldLimit)-intent.amount||after!=before+intent.amount)return Blocked;
|
||||
receipt={before,after};return Applied; // historical replay, even after newer epochs
|
||||
}
|
||||
if(saved[1]!="QUEUED"||before||after)return Blocked;
|
||||
if(!Fence(account,player,rows))return Retry;
|
||||
Batch b;if(rows.size()!=1||rows[0].size()!=7||!Decode(rows[0][5],b)||!Same(b,rows)||!Matches(intent,b)||rows[0][4]!="FROZEN"||rows[0][6]!="1")return Blocked;
|
||||
std::vector<GoldRecord> records;if(!GoldRecords(db,b,records))return Blocked;
|
||||
uint64_t expected=0;const int base=GoldCreditBase(db,b,expected);if(base<0)return Retry;if(!base)return Blocked;
|
||||
unsigned next=1;
|
||||
for(const auto& record:records) {
|
||||
if(!record.applied)break;
|
||||
if(record.before!=expected)return Blocked;expected=record.after;++next;
|
||||
}
|
||||
if(intent.sequence!=next||next>records.size()||records[next-1].intent.event!=event)return Blocked;
|
||||
if(expected>uint64_t(PortEconomy::GoldLimit)-intent.amount)return Blocked;
|
||||
if(!Q("SELECT gold FROM player WHERE id="+N(player)+" AND account_id="+N(account)+" FOR UPDATE",rows))return Retry;
|
||||
uint64_t current=0;if(rows.size()!=1||rows[0].size()!=1||!PortEconomy::Number(rows[0][0],current,PortEconomy::GoldLimit)||current!=expected)return Blocked;
|
||||
const auto target=expected+intent.amount;
|
||||
if(!Change("UPDATE player SET gold=gold+"+N(intent.amount)+" WHERE id="+N(player)+" AND account_id="+N(account)+" AND gold="+N(expected))||
|
||||
!Change("UPDATE port_cube_gold_intents SET state='APPLIED',before_gold="+N(expected)+",after_gold="+N(target)+" WHERE event='"+event+"' AND state='QUEUED'")||!db.Commit())return Retry;
|
||||
receipt={expected,target};return Applied;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
#pragma once
|
||||
#include "cube_batch.h"
|
||||
#include "cube_mutation.h"
|
||||
#include "cube_gold_intent.h"
|
||||
#include "cube_owner_types.h"
|
||||
#include "cube_image.h"
|
||||
#include "cube_receipt.h"
|
||||
|
||||
namespace PortCube {
|
||||
// Internal game/DB only. Neither this header nor the catalogue advertises a
|
||||
// crafting capability. Keep BOTH gates closed until the mutation audit and the
|
||||
// settlement/resync/thaw path are complete. There is no command to toggle them.
|
||||
constexpr uint8_t HandshakeHeader=78;
|
||||
constexpr bool HandshakeEnabled=false,ActorMutationAuditComplete=false;
|
||||
enum class Message : uint8_t { Arm=1,Submit=2,Poll=3,Cancel=4,Answer=5,Invalidate=6,GoldEnqueue=7,GoldAck=8,GoldClose=9,GoldCloseAck=10,RecoveryClaim=11,RecoveryAnswer=12,RecoveryImageRequest=13,RecoveryImageAnswer=14,Prepare=15,Execute=16,CraftAnswer=17,LiveImageRequest=18,LiveImageAnswer=19,LiveImageAck=20,LiveImageAckAnswer=21,LiveReleaseRequest=22,LiveReleaseAnswer=23,LiveResumeCheckRequest=24,LiveResumeCheckAnswer=25 };
|
||||
enum class Status : uint8_t { None=0,Denied=1,Armed=2,Draining=3,Frozen=4,Aborted=5,Held=6,Cancelled=7,GoldStored=8,GoldApplied=9,GoldClosed=10,RecoveryGranted=11,RecoveryClear=12,RecoveryImageReady=13,Prepared=14,Complete=15,LiveImageReady=16,LiveImageAcknowledged=17,LiveReleased=18,LiveResumeChecked=19 };
|
||||
struct Handshake {
|
||||
Message message=Message::Arm;Status status=Status::None;
|
||||
uint32_t account=0,player=0,cookie=0;
|
||||
uint64_t session=0,epoch=0;
|
||||
std::string owner,token,body;
|
||||
};
|
||||
constexpr unsigned HandshakeFixed=102,HandshakeMaximum=HandshakeFixed+40000;
|
||||
inline bool SameIdentity(const Handshake& a,const Handshake& b) {
|
||||
return a.account==b.account&&a.player==b.player&&a.session==b.session&&a.epoch==b.epoch&&a.owner==b.owner&&a.token==b.token;
|
||||
}
|
||||
inline bool ValidHandshake(const Handshake& f) {
|
||||
if(f.message==Message::RecoveryImageRequest||f.message==Message::RecoveryImageAnswer) {
|
||||
OwnerGrant g;std::string image;
|
||||
if(f.message==Message::RecoveryImageAnswer&&f.status==Status::RecoveryImageReady){if(!DecodeRecoveryImage(f.body,g,image))return false;}
|
||||
else if(!DecodeOwnerGrant(f.body,g)||!(f.message==Message::RecoveryImageRequest?f.status==Status::None:f.status==Status::Held))return false;
|
||||
const auto& b=g.binding;return b.account==f.account&&b.player==f.player&&b.session==f.session&&b.cookie==f.cookie&&b.epoch==f.epoch&&b.owner==f.owner&&b.request==f.token;
|
||||
}
|
||||
if(f.message==Message::RecoveryClaim||f.message==Message::RecoveryAnswer) {
|
||||
if(!f.account||!f.player||!f.session)return false;
|
||||
if(f.message==Message::RecoveryAnswer&&f.status==Status::RecoveryGranted) {
|
||||
OwnerGrant g;return DecodeOwnerGrant(f.body,g)&&g.binding.account==f.account&&g.binding.player==f.player&&g.binding.session==f.session&&g.binding.epoch==f.epoch&&g.binding.owner==f.owner&&g.binding.request==f.token&&g.binding.cookie==f.cookie;
|
||||
}
|
||||
return !f.epoch&&!f.cookie&&f.owner==std::string(32,'0')&&f.token==std::string(32,'0')&&f.body.empty()&&
|
||||
(f.message==Message::RecoveryClaim?f.status==Status::None:(f.status==Status::Held||f.status==Status::RecoveryClear));
|
||||
}
|
||||
if(!f.account||!f.player||!f.session||!f.epoch||!Identity(f.owner)||!Identity(f.token)||f.body.size()>40000)return false;
|
||||
if(f.message==Message::LiveResumeCheckRequest||f.message==Message::LiveResumeCheckAnswer) {
|
||||
InventoryImage image;if(!f.cookie)return false;
|
||||
if(f.message==Message::LiveResumeCheckAnswer&&f.status==Status::Held)return f.body.empty();
|
||||
return f.status==(f.message==Message::LiveResumeCheckRequest?Status::None:Status::LiveResumeChecked)&&DecodeInventoryImage(f.body,image);
|
||||
}
|
||||
if(f.message==Message::LiveReleaseRequest||f.message==Message::LiveReleaseAnswer) {
|
||||
InventoryImage image;if(!f.cookie)return false;
|
||||
if(f.message==Message::LiveReleaseAnswer&&f.status==Status::Held)return f.body.empty();
|
||||
return f.status==(f.message==Message::LiveReleaseRequest?Status::None:Status::LiveReleased)&&DecodeInventoryImage(f.body,image);
|
||||
}
|
||||
if(f.message==Message::LiveImageAck||f.message==Message::LiveImageAckAnswer) {
|
||||
InventoryImage image;if(!f.cookie)return false;
|
||||
if(f.message==Message::LiveImageAckAnswer&&f.status==Status::Held)return f.body.empty();
|
||||
return f.status==(f.message==Message::LiveImageAck?Status::None:Status::LiveImageAcknowledged)&&DecodeInventoryImage(f.body,image);
|
||||
}
|
||||
if(f.message==Message::LiveImageRequest)return f.status==Status::None&&f.cookie&&f.body.empty();
|
||||
if(f.message==Message::LiveImageAnswer){InventoryImage image;return f.cookie&&(f.status==Status::Held?f.body.empty():f.status==Status::LiveImageReady&&DecodeInventoryImage(f.body,image));}
|
||||
if(f.message==Message::Prepare||f.message==Message::Execute)return f.status==Status::None&&f.cookie&&f.body.empty();
|
||||
if(f.message==Message::CraftAnswer) {
|
||||
if(!f.cookie)return false;if(f.status==Status::Held||f.status==Status::Prepared)return f.body.empty();
|
||||
CraftReceipt receipt;return f.status==Status::Complete&&DecodeCraftReceipt(f.body,receipt);
|
||||
}
|
||||
if(f.message==Message::GoldClose||f.message==Message::GoldCloseAck) {
|
||||
std::vector<std::string> events;if(!f.cookie||!DecodeGoldManifest(f.body,events))return false;
|
||||
return f.message==Message::GoldClose?f.status==Status::None:f.status==Status::GoldClosed;
|
||||
}
|
||||
if(f.message==Message::GoldEnqueue||f.message==Message::GoldAck) {
|
||||
GoldIntent i;if(!f.cookie||!DecodeGoldIntent(f.body,i)||i.source!=1||i.account!=f.account||i.player!=f.player||i.epoch!=f.epoch||i.owner!=f.owner||i.request!=f.token)return false;
|
||||
return f.message==Message::GoldEnqueue?f.status==Status::None:(f.status==Status::GoldStored||f.status==Status::GoldApplied);
|
||||
}
|
||||
if(f.message==Message::Answer) {
|
||||
if(!f.body.empty()||f.status<Status::Denied||f.status>Status::Cancelled)return false;
|
||||
return (f.status!=Status::Armed&&f.status!=Status::Draining&&f.status!=Status::Frozen&&f.status!=Status::Aborted)||f.cookie;
|
||||
}
|
||||
if(f.status!=Status::None)return false;
|
||||
if(f.message==Message::Arm) {
|
||||
Batch b;if(f.cookie||!Decode(f.body,b))return false;
|
||||
return b.account==f.account&&b.player==f.player&&b.epoch==f.epoch&&b.owner==f.owner&&b.token==f.token;
|
||||
}
|
||||
return (f.message==Message::Submit||f.message==Message::Poll||f.message==Message::Cancel||f.message==Message::Invalidate)&&f.cookie&&f.body.empty();
|
||||
}
|
||||
inline bool IsDbHandshakeReply(Message m){return m==Message::Answer||m==Message::GoldAck||m==Message::GoldCloseAck||m==Message::RecoveryAnswer||m==Message::RecoveryImageAnswer||m==Message::CraftAnswer||m==Message::LiveImageAnswer||m==Message::LiveImageAckAnswer||m==Message::LiveReleaseAnswer||m==Message::LiveResumeCheckAnswer;}
|
||||
inline std::string EncodeHandshake(const Handshake& f) {
|
||||
if(!ValidHandshake(f))return {};
|
||||
Writer w;w.n(HandshakeFixed+f.body.size(),4);w.n(1,1);w.n(unsigned(f.message),1);w.n(unsigned(f.status),1);w.n(0,1);
|
||||
w.n(f.account,4);w.n(f.player,4);w.n(f.cookie,4);w.n(f.session,8);w.n(f.epoch,8);
|
||||
w.data+=f.owner;w.data+=f.token;w.n(f.body.size(),2);w.data+=f.body;return w.data;
|
||||
}
|
||||
// Safe before dereferencing any frame payload, including DB's unaligned 9-byte
|
||||
// outer packet prefix. No struct cast, native long, padding or host byte order.
|
||||
inline bool DecodeHandshake(const char* data,size_t length,Handshake& f) {
|
||||
f={};if(!data||length<HandshakeFixed||length>HandshakeMaximum)return false;
|
||||
const std::string bytes(data,length);Reader r(bytes);
|
||||
if(r.n(4)!=length||r.n(1)!=1)return false;
|
||||
Handshake out;out.message=Message(r.n(1));out.status=Status(r.n(1));if(r.n(1)!=0)return false;
|
||||
out.account=uint32_t(r.n(4));out.player=uint32_t(r.n(4));out.cookie=uint32_t(r.n(4));out.session=r.n(8);out.epoch=r.n(8);
|
||||
if(!r.ok||r.at+64>bytes.size())return false;
|
||||
out.owner=bytes.substr(r.at,32);out.token=bytes.substr(r.at+32,32);r.at+=64;
|
||||
out.body=r.s(40000);
|
||||
if(!r.ok||r.at!=bytes.size()||!ValidHandshake(out))return false;f=std::move(out);return true;
|
||||
}
|
||||
inline Handshake ArmFrame(const Batch& b,uint64_t session) {
|
||||
Handshake f;f.account=b.account;f.player=b.player;f.session=session;f.epoch=b.epoch;f.owner=b.owner;f.token=b.token;f.body=Encode(b);return f;
|
||||
}
|
||||
|
||||
// Transport-independent preparation state machine. This does NOT pause events
|
||||
// or mutate assets. The game adapter must retain a real freeze throughout every
|
||||
// non-Idle state. No timeout or negative/unknown reply is permission to thaw.
|
||||
class ActorHandshake {
|
||||
public:
|
||||
enum Stage { Idle,WaitArm,WaitDrain,Held,WaitCancel };
|
||||
private:
|
||||
Stage stage=Idle;Handshake arm;uint64_t deadline=0;bool submitted=false;uint32_t mutations=0;
|
||||
public:
|
||||
Stage State()const{return stage;}
|
||||
bool BlocksActions()const{return stage!=Idle;}
|
||||
bool Submitted()const{return submitted;}
|
||||
uint32_t Invalidated()const{return mutations;}
|
||||
void Invalidate(uint32_t reason) {
|
||||
if(stage==Idle||!reason)return;
|
||||
mutations|=reason;
|
||||
// Before cookie arrival keep accepting that Arm ACK only to cancel it.
|
||||
// After Submit, nothing can pretend this was a never-submitted batch.
|
||||
if(submitted)stage=Held;
|
||||
}
|
||||
const Handshake& IdentityFrame()const{return arm;}
|
||||
bool Start(const Batch& b,uint64_t session,uint64_t now,bool auditedFreeze) {
|
||||
if(stage!=Idle||!auditedFreeze)return false;
|
||||
auto f=ArmFrame(b,session);if(!ValidHandshake(f))return false;
|
||||
arm=std::move(f);stage=WaitArm;deadline=now;submitted=false;mutations=0;return true;
|
||||
}
|
||||
Handshake Request(Message message)const {
|
||||
Handshake f=arm;f.body.clear();f.message=message;f.status=Status::None;return f;
|
||||
}
|
||||
bool Armed(const Handshake& answer,uint64_t now) {
|
||||
if(stage!=WaitArm||!ValidHandshake(answer)||answer.message!=Message::Answer||answer.status!=Status::Armed||!SameIdentity(arm,answer)||(arm.cookie&&arm.cookie!=answer.cookie))return false;
|
||||
arm.cookie=answer.cookie;deadline=now;return true;
|
||||
}
|
||||
bool Submit(bool snapshotUnchanged,uint64_t now) {
|
||||
if(stage!=WaitArm||!arm.cookie||!snapshotUnchanged||mutations)return false;
|
||||
// Mark BEFORE enqueue: a lost/disconnected send cannot be cancelled or
|
||||
// timed out as if the DB could not have seen it.
|
||||
submitted=true;stage=WaitDrain;deadline=now;return true;
|
||||
}
|
||||
bool Cancel() {
|
||||
if(stage!=WaitArm||!arm.cookie||submitted)return false;stage=WaitCancel;return true;
|
||||
}
|
||||
bool Answer(const Handshake& answer) {
|
||||
if(stage==Idle||!ValidHandshake(answer)||answer.message!=Message::Answer||!SameIdentity(arm,answer)||answer.cookie!=arm.cookie||!arm.cookie)return false;
|
||||
if(stage==WaitCancel&&answer.status==Status::Cancelled&&!submitted){stage=Idle;arm={};return true;}
|
||||
if(answer.status==Status::Held||answer.status==Status::Aborted||answer.status==Status::Frozen){stage=Held;return true;}
|
||||
return false; // Denied/unknown/late Armed never authorize thaw
|
||||
}
|
||||
bool TimedOut(uint64_t now,uint64_t interval=10) {
|
||||
if(stage==Idle||now<deadline||now-deadline<interval)return false;
|
||||
stage=Held;return true;
|
||||
}
|
||||
void LostTransport(){if(stage!=Idle)stage=Held;}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
#include "cube_owner_types.h"
|
||||
namespace PortCube {
|
||||
// Existing fence image: gold8 + count2 + at most225*(reward114+cell2+usable1).
|
||||
constexpr unsigned InventoryImageMaximum=26335,RecoveryImageMaximum=OwnerGrantBytes+2+InventoryImageMaximum;
|
||||
struct InventoryImage {uint64_t gold=0;std::vector<Item> items;};
|
||||
inline std::string EncodeInventoryImage(const InventoryImage& i){Writer w;w.n(i.gold,8);w.items(i.items);return w.data;}
|
||||
inline bool DecodeInventoryImage(const std::string& bytes,InventoryImage& out,const Lookup& lookup={}) {
|
||||
out={};if(bytes.size()<10||bytes.size()>InventoryImageMaximum)return false;
|
||||
Reader r(bytes);InventoryImage image;image.gold=r.n(8);image.items=r.items();
|
||||
if(!r.ok||r.at!=bytes.size()||image.gold>uint64_t(PortEconomy::GoldLimit))return false;
|
||||
int last=-1;std::set<uint32_t> ids;std::array<bool,225> used={};
|
||||
for(const auto& item:image.items) {
|
||||
const auto& v=item.value;
|
||||
if(!v.id||!v.vnum||!v.count||v.count>2000||!item.usable||item.cell>=225||int(item.cell)<=last||!ids.insert(v.id).second)return false;last=item.cell;
|
||||
if(lookup) {
|
||||
const auto p=lookup(v.vnum);
|
||||
if(p.size<1||p.size>3||(!p.stackable&&v.count!=1)||(item.cell%45)/5+p.size>9)return false;
|
||||
for(unsigned n=0;n<p.size;++n){const auto at=item.cell+5*n;if(at>=225||used[at])return false;used[at]=true;}
|
||||
}
|
||||
}
|
||||
if(EncodeInventoryImage(image)!=bytes)return false;out=std::move(image);return true;
|
||||
}
|
||||
inline std::string EncodeRecoveryImage(const OwnerGrant& grant,const std::string& image) {
|
||||
InventoryImage decoded;const auto body=EncodeOwnerGrant(grant);
|
||||
if(body.empty()||!DecodeInventoryImage(image,decoded))return {};Writer w;w.data=body;w.s(image);return w.data;
|
||||
}
|
||||
inline bool DecodeRecoveryImage(const std::string& bytes,OwnerGrant& grant,std::string& image) {
|
||||
grant={};image.clear();if(bytes.size()<OwnerGrantBytes+12||bytes.size()>RecoveryImageMaximum)return false;
|
||||
OwnerGrant g;if(!DecodeOwnerGrant(bytes.substr(0,OwnerGrantBytes),g))return false;
|
||||
Reader r(bytes);r.at=OwnerGrantBytes;auto data=r.s(InventoryImageMaximum);InventoryImage decoded;
|
||||
if(!r.ok||r.at!=bytes.size()||!DecodeInventoryImage(data,decoded))return false;
|
||||
grant=std::move(g);image=std::move(data);return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
#pragma once
|
||||
#include "cube_fence.h"
|
||||
#include "cube_owner.h"
|
||||
namespace PortCube {
|
||||
// Optional additive schema. An ACK records an exact applied image; it does not
|
||||
// release a lease, an item fence, or an actor. Never install tables at startup.
|
||||
template<class DB> bool ImageAckSchema(DB& db) {
|
||||
PortEconomy::Rows rows;
|
||||
const std::string names="('port_cube_image_ack_version','port_cube_image_acks')";
|
||||
auto q=[&](const std::string& sql){return db.Query(sql,rows)&&!db.warnings&&rows.size()==1&&rows[0].size()==1;};
|
||||
return q("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME IN "+names)&&rows[0][0]=="2"&&
|
||||
q("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND ENGINE='InnoDB' AND TABLE_NAME IN "+names)&&rows[0][0]=="2"&&
|
||||
q("SELECT version FROM port_cube_image_ack_version WHERE id=1")&&rows[0][0]=="1";
|
||||
}
|
||||
template<class DB> class ImageAckStore {
|
||||
DB& db;Lookup lookup;
|
||||
static std::string X(const std::string& s){return "X'"+PortEconomy::Hex(s.data(),s.size())+"'";}
|
||||
public:
|
||||
enum Result {Retry,Refused,Stored};
|
||||
ImageAckStore(DB& d,Lookup p):db(d),lookup(std::move(p)){}
|
||||
Result AcknowledgeLive(const Batch& b,const OwnerGrant& grant,const std::string& image) {
|
||||
InventoryImage decoded;
|
||||
if(!Validate(b)||!Valid(grant)||!Matches(grant.binding,b)||!DecodeInventoryImage(image,decoded,lookup))return Refused;
|
||||
if(!ImageAckSchema(db))return Retry;
|
||||
OwnerStore<DB> owner(db,lookup);FenceStore<DB> fence(db,lookup);std::string current;
|
||||
// Resync holds the account, fence and current SQL inventory on the same
|
||||
// pinned transaction. Callback writes roll back with its COMMIT failure.
|
||||
const auto result=fence.Resync(b,current,[&](const std::string& actual)->bool {
|
||||
if(actual!=image||!owner.LiveImageWithin(b,grant,image))return false;
|
||||
PortEconomy::Rows rows;
|
||||
auto q=[&](const std::string& sql){return db.Query(sql,rows)&&!db.warnings;};
|
||||
// ACK cannot create the initial issued image or acknowledge a
|
||||
// changed saved image, even when the current SQL happens to match.
|
||||
if(!q("SELECT phase,image FROM port_cube_fences WHERE pid="+std::to_string(b.player)+" FOR UPDATE")||
|
||||
rows.size()!=1||rows[0]!=std::vector<std::string>{"RESYNC",image})return false;
|
||||
const auto body=Encode(b),binding=EncodeOwnerGrant(grant);
|
||||
if(!q("SELECT body,owner_grant,image FROM port_cube_image_acks WHERE request='"+b.token+"' FOR UPDATE"))return false;
|
||||
if(!rows.empty())return rows.size()==1&&rows[0]==std::vector<std::string>{body,binding,image};
|
||||
return q("INSERT INTO port_cube_image_acks(request,body,owner_grant,image) VALUES('"+b.token+"',"+X(body)+","+X(binding)+","+X(image)+")")&&db.affected==1;
|
||||
});
|
||||
return result==FenceStore<DB>::Done?Stored:result==FenceStore<DB>::Retry?Retry:Refused;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
#include <utility>
|
||||
|
||||
namespace PortCube {
|
||||
// Legacy game allocation uses an exclusive upper bound. DB range collision
|
||||
// checks are inclusive, so even touching ranges are rejected for handoff.
|
||||
struct ItemIDRange { uint32_t minimum=0, maximum=0, usable=0; };
|
||||
struct ItemIDPlan {
|
||||
std::vector<uint32_t> ids;
|
||||
uint32_t next=0;
|
||||
bool spare=false;
|
||||
};
|
||||
inline bool ValidItemIDRange(const ItemIDRange& r) {
|
||||
return r.minimum && r.minimum<=r.usable && r.usable<r.maximum;
|
||||
}
|
||||
inline bool PlanItemIDs(const ItemIDRange& active,uint32_t next,
|
||||
const ItemIDRange& spare,unsigned count,ItemIDPlan& out) {
|
||||
// No partial output, wraparound, allocation of the sentinel maximum, or
|
||||
// speculative switch when all IDs already fit in the active range.
|
||||
if(!count||count>100||!ValidItemIDRange(active)||
|
||||
next<active.usable||next>active.maximum)return false;
|
||||
const uint64_t available=uint64_t(active.maximum)-next;
|
||||
const bool switchRange=count>available;
|
||||
if(switchRange && (!ValidItemIDRange(spare)||
|
||||
!(active.maximum<spare.minimum||spare.maximum<active.minimum)||
|
||||
uint64_t(count)-available>uint64_t(spare.maximum)-spare.usable))return false;
|
||||
ItemIDPlan plan;plan.ids.reserve(count);
|
||||
uint32_t cursor=next;
|
||||
for(unsigned i=0;i<count;++i) {
|
||||
if(!plan.spare&&cursor==active.maximum){plan.spare=true;cursor=spare.usable;}
|
||||
plan.ids.push_back(cursor++);
|
||||
}
|
||||
plan.next=cursor;out=std::move(plan);return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
#pragma once
|
||||
#include "cube_craft.h"
|
||||
namespace PortCube {
|
||||
inline bool CraftImage(const Batch& b,const CraftReceipt& receipt,uint64_t credits,const Lookup& lookup,std::string& out) {
|
||||
if(receipt.result!="ok"||!ValidateCraftReceipt(b,receipt,lookup)||receipt.fee>b.gold||
|
||||
credits>uint64_t(PortEconomy::GoldLimit)-(b.gold-receipt.fee))return false;
|
||||
std::string rolls(b.attempts,char(100));for(unsigned i=0;i<receipt.successes;++i)rolls[i]=1;
|
||||
const auto plan=SettlePlan(b,rolls,lookup);if(plan.result!="ok")return false;
|
||||
InventoryImage image;image.gold=b.gold-receipt.fee+credits;image.items=b.inventory;
|
||||
for(auto& item:image.items){item.usable=true;for(const auto& take:plan.takes)if(take.id==item.value.id){if(take.count>item.value.count)return false;item.value.count-=take.count;}}
|
||||
image.items.erase(std::remove_if(image.items.begin(),image.items.end(),[](const Item& i){return !i.value.count;}),image.items.end());
|
||||
image.items.insert(image.items.end(),receipt.awards.begin(),receipt.awards.end());
|
||||
std::sort(image.items.begin(),image.items.end(),[](const Item& a,const Item& c){return a.cell<c.cell;});
|
||||
const auto bytes=EncodeInventoryImage(image);InventoryImage decoded;if(!DecodeInventoryImage(bytes,decoded,lookup))return false;out=bytes;return true;
|
||||
}
|
||||
// Transport state only: adapter must apply/read back and remain held throughout.
|
||||
class LiveImageFlow {
|
||||
public: enum Stage {Idle,Waiting,Ready,Held,Applied,AckWaiting,Acknowledged};
|
||||
private: Stage stage=Idle;Handshake identity;std::string expected;
|
||||
public:
|
||||
Stage State()const{return stage;}bool MayRetry()const{return stage==Waiting;}
|
||||
const std::string& Image()const{return expected;}
|
||||
void Invalidate(){stage=Held;}
|
||||
bool Start(const Handshake& bound,const Batch& b,const CraftReceipt& receipt,uint64_t credits,const Lookup& lookup,bool sealed) {
|
||||
auto f=bound;f.message=Message::LiveImageRequest;f.status=Status::None;f.body.clear();
|
||||
if(stage!=Idle||!sealed||!ValidHandshake(f)||f.account!=b.account||f.player!=b.player||f.epoch!=b.epoch||f.owner!=b.owner||f.token!=b.token||!CraftImage(b,receipt,credits,lookup,expected))return false;
|
||||
identity=std::move(f);stage=Waiting;return true;
|
||||
}
|
||||
Handshake Request()const{return identity;}
|
||||
bool MarkApplied(const std::string& readback) {
|
||||
if(stage!=Ready||readback!=expected){stage=Held;return false;}stage=Applied;return true;
|
||||
}
|
||||
bool BeginAcknowledge(const std::string& readback) {
|
||||
if(stage!=Applied||readback!=expected){stage=Held;return false;}stage=AckWaiting;return true;
|
||||
}
|
||||
bool MayAcknowledge()const{return stage==AckWaiting;}
|
||||
Handshake Acknowledgement()const {
|
||||
auto f=identity;f.message=Message::LiveImageAck;f.body=expected;return f;
|
||||
}
|
||||
bool Answer(const Handshake& f) {
|
||||
if(!ValidHandshake(f)||!SameIdentity(f,identity)||f.cookie!=identity.cookie)return false;
|
||||
if(f.message==Message::LiveImageAckAnswer) {
|
||||
if(stage!=AckWaiting&&stage!=Acknowledged)return false;
|
||||
if(f.status==Status::Held)return stage==AckWaiting;
|
||||
if(f.status!=Status::LiveImageAcknowledged)return false;
|
||||
if(f.body!=expected){stage=Held;return false;}stage=Acknowledged;return true;
|
||||
}
|
||||
if((stage!=Waiting&&stage!=Ready&&stage!=Applied&&stage!=AckWaiting&&stage!=Acknowledged)||f.message!=Message::LiveImageAnswer)return false;
|
||||
if(f.status==Status::Held)return stage==Waiting;
|
||||
if(f.status!=Status::LiveImageReady)return false;
|
||||
if(f.body!=expected){stage=Held;return false;}if(stage==Waiting)stage=Ready;return true;
|
||||
}
|
||||
};
|
||||
// Terminal SQL transport only. A Released result retains both actor and DB
|
||||
// memory holds; it is NOT a resume grant or permission to enable item saves.
|
||||
class LiveReleaseFlow {
|
||||
public: enum Stage {Idle,Waiting,Released,Held};
|
||||
private: Stage stage=Idle;Handshake request;
|
||||
public:
|
||||
Stage State()const{return stage;}
|
||||
bool MayRetry()const{return stage==Waiting;}
|
||||
void Invalidate(){stage=Held;}
|
||||
bool Start(const LiveImageFlow& image,bool locallyReady) {
|
||||
if(stage!=Idle||!locallyReady||image.State()!=LiveImageFlow::Acknowledged)return false;
|
||||
auto f=image.Acknowledgement();f.message=Message::LiveReleaseRequest;
|
||||
if(!ValidHandshake(f))return false;
|
||||
request=std::move(f);stage=Waiting;return true;
|
||||
}
|
||||
Handshake Request()const{return request;}
|
||||
bool Answer(const Handshake& f) {
|
||||
if((stage!=Waiting&&stage!=Released)||!ValidHandshake(f)||f.message!=Message::LiveReleaseAnswer||
|
||||
!SameIdentity(f,request)||f.cookie!=request.cookie)return false;
|
||||
if(f.status==Status::Held)return stage==Waiting;
|
||||
if(f.status!=Status::LiveReleased)return false;
|
||||
if(f.body!=request.body){stage=Held;return false;}
|
||||
stage=Released;return true;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
namespace PortCube {
|
||||
// Preparation admission is conservative, not a change to expiry/reward rules.
|
||||
// No bit grants permission to pause arbitrary timers or drop a mutation.
|
||||
enum Hazard : uint32_t { ItemClock=1,ItemBusy=2,QuestTimer=4,QuestRunning=8,
|
||||
Switcher=16,Party=32,Combat=64,LifeCycle=128,MissingState=256 };
|
||||
enum Mutation : uint32_t { ItemWrite=1,GoldWrite=2,QuestWrite=4,ContextChanged=8,LifecycleWrite=16 };
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
#pragma once
|
||||
#include "cube_owner_types.h"
|
||||
#include "cube_gold_store.h"
|
||||
#include "cube_image.h"
|
||||
#include <cerrno>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
namespace PortCube {
|
||||
inline std::string OwnerBootNonce() {
|
||||
unsigned char bytes[16];const int fd=open("/dev/urandom",O_RDONLY);if(fd<0)return {};size_t at=0;
|
||||
while(at<sizeof(bytes)){auto n=read(fd,bytes+at,sizeof(bytes)-at);if(n<0&&errno==EINTR)continue;if(n<=0){close(fd);return {};}at+=size_t(n);}close(fd);
|
||||
const auto s=PortEconomy::Hex(bytes,sizeof(bytes));return Identity(s)?s:std::string{};
|
||||
}
|
||||
// DB-main/direct-session authority. A connection-scoped MySQL advisory lock
|
||||
// fences competing brokers; each new boot OR SQL connection advances generation.
|
||||
// There is no wall-clock expiry, auto-adoption, currency write or thaw here.
|
||||
template<class DB> class OwnerStore {
|
||||
DB& db;Lookup lookup;using Rows=PortEconomy::Rows;
|
||||
static std::string N(uint64_t n){return std::to_string(n);}
|
||||
bool Q(const std::string& s,Rows& r){return db.Query(s,r)&&!db.warnings;}
|
||||
bool Run(const std::string& s){Rows r;return Q(s,r);}
|
||||
bool Change(const std::string& s){return Run(s)&&db.affected==1;}
|
||||
struct Guard {DB& db;~Guard(){db.Rollback();}};
|
||||
bool Account(uint32_t id){Rows r;return Run("INSERT INTO port_economy_account_lock(account) VALUES("+N(id)+") ON DUPLICATE KEY UPDATE account=VALUES(account)")&&Q("SELECT account FROM port_economy_account_lock WHERE account="+N(id)+" FOR UPDATE",r)&&r.size()==1;}
|
||||
bool Session(uint64_t& connection,uint64_t& holder) {
|
||||
Rows r;holder=0;
|
||||
if(!Q("SELECT CONNECTION_ID(),IS_USED_LOCK(CONCAT('m2_cube:',DATABASE()))",r)||r.size()!=1||r[0].size()!=2||!PortEconomy::Number(r[0][0],connection)||!connection)return false;
|
||||
return r[0][1].empty()||PortEconomy::Number(r[0][1],holder);
|
||||
}
|
||||
bool LeaderRow(const OwnerLeader& l) {
|
||||
uint64_t connection=0,holder=0;Rows r;
|
||||
return Valid(l)&&Session(connection,holder)&&connection==l.connection&&holder==connection&&
|
||||
Q("SELECT generation,boot,connection_id FROM port_cube_owner_broker WHERE id=1 FOR UPDATE",r)&&r.size()==1&&r[0]==std::vector<std::string>{N(l.generation),l.boot,N(l.connection)};
|
||||
}
|
||||
bool LeaseRows(const Batch& b,Rows& r){return Q("SELECT account,pid,body,revision,generation,boot,connection_id,peer,binding,original_peer,original_binding,phase,revoked_generation,reason FROM port_cube_owner_leases WHERE request='"+b.token+"' FOR UPDATE",r);}
|
||||
static bool DecodeLease(const Batch& b,const Rows& rows,OwnerGrant& active,GoldSourceBinding& original,uint32_t& originalPeer,std::string& phase,uint64_t& revoked) {
|
||||
active={};original={};originalPeer=0;revoked=0;
|
||||
if(rows.size()!=1||rows[0].size()!=14)return false;const auto& r=rows[0];uint64_t peer=0,oldPeer=0,reason=0;
|
||||
if(r[0]!=N(b.account)||r[1]!=N(b.player)||r[2]!=Encode(b)||!PortEconomy::Number(r[3],active.revision)||!PortEconomy::Number(r[4],active.leader.generation)||
|
||||
!PortEconomy::Number(r[6],active.leader.connection)||!PortEconomy::Number(r[7],peer,UINT32_MAX)||!PortEconomy::Number(r[9],oldPeer,UINT32_MAX)||
|
||||
!DecodeGoldSourceBinding(r[8],active.binding)||!DecodeGoldSourceBinding(r[10],original)||!Matches(active.binding,b)||!Matches(original,b)||
|
||||
!PortEconomy::Number(r[12],revoked)||!PortEconomy::Number(r[13],reason,3))return false;
|
||||
active.peer=uint32_t(peer);active.leader.boot=r[5];originalPeer=uint32_t(oldPeer);phase=r[11];
|
||||
return Valid(active)&&originalPeer&&(phase=="LIVE"||phase=="REVOKED"||phase=="ADOPTED")&&((phase=="REVOKED")==bool(revoked))&&((phase=="REVOKED")==bool(reason));
|
||||
}
|
||||
static bool Same(const OwnerGrant& a,const OwnerGrant& b){return SameOwnerGrant(a,b);}
|
||||
public:
|
||||
enum Result {Retry,Refused,Busy,Acquired,Revoked,Adopted};
|
||||
OwnerStore(DB& d,Lookup p):db(d),lookup(std::move(p)){}
|
||||
bool Ready(){GoldIntentStore<DB> gold(db,lookup);return gold.Ready()&&OwnerSchema(db)==1;}
|
||||
Result Acquire(std::string boot,OwnerLeader& leader) {
|
||||
leader={};if(!Identity(boot))return Refused;if(!Ready())return Retry;
|
||||
uint64_t connection=0,holder=0;if(!Session(connection,holder))return Retry;
|
||||
Rows rows;
|
||||
if(holder!=connection) {
|
||||
if(!Q("SELECT GET_LOCK(CONCAT('m2_cube:',DATABASE()),0)",rows)||rows.size()!=1||rows[0].size()!=1)return Retry;
|
||||
if(rows[0][0]!="1")return Busy;
|
||||
}
|
||||
if(!db.Begin())return Retry;Guard guard{db};
|
||||
if(!Q("SELECT generation,boot,connection_id FROM port_cube_owner_broker WHERE id=1 FOR UPDATE",rows)||rows.size()!=1||rows[0].size()!=3)return Retry;
|
||||
uint64_t generation=0,oldConnection=0;
|
||||
if(!PortEconomy::Number(rows[0][0],generation)||!PortEconomy::Number(rows[0][2],oldConnection))return Refused;
|
||||
if(generation&&(!Identity(rows[0][1])||!oldConnection))return Refused;
|
||||
if(!generation&&(rows[0][1]!=std::string(32,'0')||oldConnection))return Refused;
|
||||
if(generation&&rows[0][1]==boot&&oldConnection==connection){leader={boot,generation,connection};return Acquired;}
|
||||
if(generation==UINT64_MAX)return Refused;
|
||||
if(!Change("UPDATE port_cube_owner_broker SET generation="+N(generation+1)+",boot='"+boot+"',connection_id="+N(connection)+" WHERE id=1 AND generation="+N(generation))||!db.Commit())return Retry;
|
||||
leader={boot,generation+1,connection};return Acquired;
|
||||
}
|
||||
bool Current(const OwnerLeader& l){if(!Ready()||!db.Begin())return false;Guard g{db};return LeaderRow(l);}
|
||||
// Called INSIDE FenceStore::Begin's account transaction, after item locks.
|
||||
// Replay can only validate an existing identical row, never invent one.
|
||||
bool BindWithin(const Batch& b,const OwnerGrant& grant,bool replay) {
|
||||
if(!Validate(b)||!Valid(grant)||grant.revision!=1||!Matches(grant.binding,b)||!LeaderRow(grant.leader))return false;
|
||||
Rows rows;if(!LeaseRows(b,rows))return false;
|
||||
if(!rows.empty()) {
|
||||
OwnerGrant existing;GoldSourceBinding original;uint32_t peer=0;std::string phase;uint64_t revoked=0;
|
||||
return DecodeLease(b,rows,existing,original,peer,phase,revoked)&&phase=="LIVE"&&Same(existing,grant)&&peer==grant.peer&&EncodeGoldSourceBinding(original)==EncodeGoldSourceBinding(grant.binding);
|
||||
}
|
||||
if(replay)return false;
|
||||
if(!Q("SELECT request FROM port_cube_owner_leases WHERE account="+N(b.account)+" OR pid="+N(b.player)+" FOR UPDATE",rows)||!rows.empty())return false;
|
||||
const auto body=Encode(b),binding=EncodeGoldSourceBinding(grant.binding);
|
||||
return Change("INSERT INTO port_cube_owner_leases(request,account,pid,body,revision,generation,boot,connection_id,peer,binding,original_peer,original_binding,phase,revoked_generation,reason) VALUES('"+b.token+"',"+N(b.account)+","+N(b.player)+",X'"+PortEconomy::Hex(body.data(),body.size())+"',1,"+N(grant.leader.generation)+",'"+grant.leader.boot+"',"+N(grant.leader.connection)+","+N(grant.peer)+",X'"+PortEconomy::Hex(binding.data(),binding.size())+"',"+N(grant.peer)+",X'"+PortEconomy::Hex(binding.data(),binding.size())+"','LIVE',0,0)");
|
||||
}
|
||||
bool Check(const Batch& b,const OwnerGrant& grant) {
|
||||
if(!Ready()||!db.Begin())return false;Guard guard{db};if(!Account(b.account)||!LeaderRow(grant.leader))return false;
|
||||
Rows rows;OwnerGrant active;GoldSourceBinding original;uint32_t peer=0;std::string phase;uint64_t revoked=0;
|
||||
return LeaseRows(b,rows)&&DecodeLease(b,rows,active,original,peer,phase,revoked)&&phase!="REVOKED"&&Same(active,grant);
|
||||
}
|
||||
// Called inside Prepare/Execute after the account lock, never via a separate
|
||||
// reconnectable preflight. The original live source must be sealed first.
|
||||
bool CraftWithin(const Batch& b,const OwnerGrant& grant) {
|
||||
if(!Validate(b)||!Valid(grant)||!Matches(grant.binding,b)||!Ready()||!LeaderRow(grant.leader))return false;
|
||||
Rows rows;OwnerGrant active;GoldSourceBinding original;uint32_t peer=0;std::string phase;uint64_t revoked=0;
|
||||
if(!LeaseRows(b,rows)||!DecodeLease(b,rows,active,original,peer,phase,revoked)||phase!="LIVE"||!Same(active,grant)||peer!=grant.peer||EncodeGoldSourceBinding(original)!=EncodeGoldSourceBinding(grant.binding))return false;
|
||||
if(!Q("SELECT account,epoch,owner,request,phase,body,drain_state FROM port_cube_fences WHERE pid="+N(b.player)+" FOR UPDATE",rows)||rows.size()!=1||rows[0]!=std::vector<std::string>{N(b.account),N(b.epoch),b.owner,b.token,"FROZEN",Encode(b),"1"})return false;
|
||||
std::vector<GoldRecord> records;if(!GoldRecords(db,b,records))return false;
|
||||
std::vector<std::string> events;for(const auto& record:records)events.push_back(record.intent.event);
|
||||
const std::vector<std::string> proof={N(b.account),N(b.player),N(b.epoch),b.owner,N(original.session),N(original.cookie),N(original.handle),EncodeGoldManifest(events)};
|
||||
return Q("SELECT account,pid,epoch,owner,session,cookie,handle,manifest FROM port_cube_gold_sources WHERE request='"+b.token+"' FOR UPDATE",rows)&&rows.size()==1&&rows[0]==proof;
|
||||
}
|
||||
// Inside Fence.Resync's account transaction on the SAME pinned connection.
|
||||
// A grant alone is insufficient: recheck original source, verified receipt,
|
||||
// current wallet (including zero-credit batches), and all surviving ID locks.
|
||||
private:
|
||||
bool OwnedImageWithin(const Batch& b,const OwnerGrant& grant,const std::string& image,bool live,bool released=false) {
|
||||
if(!Validate(b)||!Valid(grant)||!Matches(grant.binding,b)||!Ready()||!LeaderRow(grant.leader))return false;
|
||||
Rows rows;OwnerGrant active;GoldSourceBinding original;uint32_t peer=0;std::string phase;uint64_t revoked=0;
|
||||
if(released) {
|
||||
if(!ReleasedWithin(b,grant))return false;
|
||||
original=grant.binding;peer=grant.peer;
|
||||
} else {
|
||||
if(!LeaseRows(b,rows)||!DecodeLease(b,rows,active,original,peer,phase,revoked)||phase!=(live?"LIVE":"ADOPTED")||!Same(active,grant))return false;
|
||||
if(live&&(peer!=grant.peer||EncodeGoldSourceBinding(original)!=EncodeGoldSourceBinding(grant.binding)))return false;
|
||||
}
|
||||
std::vector<GoldRecord> records;if(!GoldRecords(db,b,records))return false;
|
||||
std::vector<std::string> events;for(const auto& record:records){if(!record.applied)return false;events.push_back(record.intent.event);}
|
||||
const std::vector<std::string> proof={N(b.account),N(b.player),N(b.epoch),b.owner,N(original.session),N(original.cookie),N(original.handle),EncodeGoldManifest(events)};
|
||||
if(!Q("SELECT account,pid,epoch,owner,session,cookie,handle,manifest FROM port_cube_gold_sources WHERE request='"+b.token+"' FOR UPDATE",rows)||rows.size()!=1||rows[0]!=proof)return false;
|
||||
typename BatchStore<DB>::Receipt receipt;
|
||||
if(!Q("SELECT body,rolls,state,result,successes,fee,awards FROM port_cube_requests WHERE token='"+b.token+"' AND account="+N(b.account)+" AND pid="+N(b.player)+" FOR UPDATE",rows)||rows.size()!=1||!BatchStore<DB>::DoneReceipt(b,rows[0],receipt)||receipt.result!="ok")return false;
|
||||
const auto plan=SettlePlan(b,rows[0][1],lookup);Writer planned,awarded;planned.items(plan.awards);awarded.items(receipt.awards);
|
||||
if(plan.result!="ok"||plan.fee!=receipt.fee||plan.successes!=receipt.successes||planned.data!=awarded.data)return false;
|
||||
uint64_t gold=b.gold-receipt.fee;
|
||||
for(const auto& record:records){if(record.before!=gold)return false;gold=record.after;}
|
||||
if(!Q("SELECT gold FROM player WHERE id="+N(b.player)+" AND account_id="+N(b.account)+" FOR UPDATE",rows)||rows.size()!=1||rows[0]!=std::vector<std::string>{N(gold)})return false;
|
||||
if(!Q("SELECT id,pid,epoch,request FROM port_cube_item_fences WHERE pid="+N(b.player)+" FOR UPDATE",rows)||rows.size()>8517)return false;
|
||||
if(released&&!rows.empty())return false;
|
||||
std::set<uint32_t> locks;
|
||||
for(const auto& row:rows){uint64_t id=0;if(row.size()!=4||!PortEconomy::Number(row[0],id,UINT32_MAX)||!id||row[1]!=N(b.player)||row[2]!=N(b.epoch)||row[3]!=b.token||!locks.insert(uint32_t(id)).second)return false;}
|
||||
for(const auto& item:b.inventory)if(!released&&!locks.count(item.value.id))return false;
|
||||
std::set<uint32_t> reserved;for(const auto& reward:b.rewards){if(!released&&!locks.count(reward.id))return false;reserved.insert(reward.id);}
|
||||
if(!Q("SELECT id,request FROM port_economy_item_reservations WHERE request='"+b.token+"' FOR UPDATE",rows)||rows.size()!=reserved.size())return false;
|
||||
for(const auto& row:rows){uint64_t id=0;if(row.size()!=2||!PortEconomy::Number(row[0],id,UINT32_MAX)||row[1]!=b.token||!reserved.erase(uint32_t(id)))return false;}
|
||||
if(!reserved.empty()||!Q("SELECT id FROM item WHERE owner_id="+N(b.player)+" AND window NOT IN ('MALL','SAFEBOX') FOR UPDATE",rows)||rows.size()>4096)return false;
|
||||
for(const auto& row:rows){uint64_t id=0;if(row.size()!=1||!PortEconomy::Number(row[0],id,UINT32_MAX)||!id||(!released&&!locks.count(uint32_t(id))))return false;}
|
||||
InventoryImage expected;expected.gold=gold;expected.items=b.inventory;
|
||||
for(auto& item:expected.items){item.usable=true;for(const auto& take:plan.takes)if(take.id==item.value.id){if(take.count>item.value.count)return false;item.value.count-=take.count;}}
|
||||
expected.items.erase(std::remove_if(expected.items.begin(),expected.items.end(),[](const Item& item){return !item.value.count;}),expected.items.end());
|
||||
expected.items.insert(expected.items.end(),receipt.awards.begin(),receipt.awards.end());std::sort(expected.items.begin(),expected.items.end(),[](const Item& a,const Item& c){return a.cell<c.cell;});
|
||||
InventoryImage decoded;return DecodeInventoryImage(image,decoded,lookup)&&EncodeInventoryImage(expected)==image;
|
||||
}
|
||||
public:
|
||||
bool ImageWithin(const Batch& b,const OwnerGrant& grant,const std::string& image){return OwnedImageWithin(b,grant,image,false);}
|
||||
bool LiveImageWithin(const Batch& b,const OwnerGrant& grant,const std::string& image){return OwnedImageWithin(b,grant,image,true);}
|
||||
// Caller holds a released fence/account transaction and checks exact
|
||||
// terminal history. No lease resurrection, save permission or asset writes.
|
||||
bool ReleasedImageWithin(const Batch& b,const OwnerGrant& grant,const std::string& image){return OwnedImageWithin(b,grant,image,true,true);}
|
||||
// Historical terminal reply only, inside the caller's account transaction.
|
||||
// Exact durable receipt is checked by that caller; never clear a newer hold.
|
||||
bool ReleasedWithin(const Batch& b,const OwnerGrant& grant) {
|
||||
if(!Validate(b)||!Valid(grant)||!Matches(grant.binding,b)||!Ready()||!LeaderRow(grant.leader))return false;
|
||||
Rows rows;return Q("SELECT request FROM port_cube_owner_leases WHERE account="+N(b.account)+" OR pid="+N(b.player)+" OR request='"+b.token+"' FOR UPDATE",rows)&&rows.empty();
|
||||
}
|
||||
bool Inspect(const Batch& b,const OwnerLeader& l,OwnerGrant& active,std::string& phase,uint64_t& revoked) {
|
||||
active={};phase.clear();revoked=0;
|
||||
if(!Validate(b)||!Ready()||!db.Begin())return false;Guard guard{db};
|
||||
if(!Account(b.account)||!LeaderRow(l))return false;
|
||||
Rows rows;GoldSourceBinding original;uint32_t peer=0;
|
||||
return LeaseRows(b,rows)&&DecodeLease(b,rows,active,original,peer,phase,revoked);
|
||||
}
|
||||
// reason 1/2 is a trusted DB peer-gone/account-owner-ended callback, not a
|
||||
// packet/client boolean. reason 3 requires a strictly newer broker generation.
|
||||
Result Revoke(const Batch& b,const OwnerLeader& l,unsigned reason,const OwnerGrant* lost,OwnerGrant& revokedGrant) {
|
||||
revokedGrant={};if(!Validate(b)||!Valid(l)||reason<1||reason>3||(reason!=3&&(!lost||!Valid(*lost))))return Refused;
|
||||
if(!Ready()||!db.Begin())return Retry;Guard guard{db};if(!Account(b.account)||!LeaderRow(l))return Retry;
|
||||
Rows rows;OwnerGrant active;GoldSourceBinding original;uint32_t peer=0;std::string phase;uint64_t revoked=0;
|
||||
if(!LeaseRows(b,rows)||!DecodeLease(b,rows,active,original,peer,phase,revoked))return Refused;
|
||||
if(reason==3){if(active.leader.generation>=l.generation)return Refused;}
|
||||
else {auto expected=*lost;if(phase=="REVOKED"&&lost->revision!=UINT64_MAX&&active.revision==lost->revision+1)expected.revision=active.revision;
|
||||
if(!Same(active,expected)||active.leader.boot!=l.boot||active.leader.generation!=l.generation||active.leader.connection!=l.connection)return Refused;}
|
||||
if(phase=="REVOKED"&&revoked==l.generation){revokedGrant=active;return Revoked;}
|
||||
if(active.revision==UINT64_MAX)return Refused;
|
||||
if(!Change("UPDATE port_cube_owner_leases SET phase='REVOKED',revision="+N(active.revision+1)+",revoked_generation="+N(l.generation)+",reason="+N(reason)+" WHERE request='"+b.token+"' AND revision="+N(active.revision))||!db.Commit())return Retry;
|
||||
active.revision++;revokedGrant=active;return Revoked;
|
||||
}
|
||||
Result Adopt(const Batch& b,const OwnerLeader& l,uint64_t revokedRevision,uint32_t peer,const GoldSourceBinding& target,OwnerGrant& grant) {
|
||||
grant={};if(!Validate(b)||!Valid(l)||!revokedRevision||revokedRevision==UINT64_MAX||!peer||!Matches(target,b)||EncodeGoldSourceBinding(target).empty())return Refused;
|
||||
if(!Ready()||!db.Begin())return Retry;Guard guard{db};if(!Account(b.account)||!LeaderRow(l))return Retry;
|
||||
Rows rows;OwnerGrant active;GoldSourceBinding original;uint32_t originalPeer=0;std::string phase;uint64_t revoked=0;
|
||||
if(!LeaseRows(b,rows)||!DecodeLease(b,rows,active,original,originalPeer,phase,revoked))return Refused;
|
||||
OwnerGrant expected{l,target,peer,revokedRevision+1};
|
||||
if(phase=="ADOPTED") {if(!Same(active,expected))return Refused;grant=active;return Adopted;}
|
||||
if(phase!="REVOKED"||revoked!=l.generation||active.revision!=revokedRevision)return Refused;
|
||||
if(target.session==original.session||target.session==active.binding.session)return Refused;
|
||||
if(!Q("SELECT account,epoch,owner,request,phase,body,drain_state FROM port_cube_fences WHERE pid="+N(b.player)+" FOR UPDATE",rows)||rows.size()!=1||rows[0].size()!=7)return Refused;
|
||||
const auto fence=rows[0];
|
||||
if(fence[0]!=N(b.account)||fence[1]!=N(b.epoch)||fence[2]!=b.owner||fence[3]!=b.token||fence[5]!=Encode(b)||fence[6]!="1"||(fence[4]!="FROZEN"&&fence[4]!="RESYNC"))return Refused;
|
||||
std::vector<GoldRecord> records;if(!GoldRecords(db,b,records))return Refused;
|
||||
std::vector<std::string> events;for(const auto& r:records)events.push_back(r.intent.event);
|
||||
const std::vector<std::string> proof={N(b.account),N(b.player),N(b.epoch),b.owner,N(original.session),N(original.cookie),N(original.handle),EncodeGoldManifest(events)};
|
||||
if(!Q("SELECT account,pid,epoch,owner,session,cookie,handle,manifest FROM port_cube_gold_sources WHERE request='"+b.token+"' FOR UPDATE",rows)||rows.size()!=1||rows[0]!=proof)return Refused;
|
||||
uint64_t expectedGold=0;if(GoldCreditBase(db,b,expectedGold)!=1)return Refused;
|
||||
bool pending=false;uint64_t future=expectedGold;
|
||||
for(const auto& r:records)if(r.applied){if(pending||r.before!=expectedGold)return Refused;expectedGold=future=r.after;}else{pending=true;if(future>uint64_t(PortEconomy::GoldLimit)-r.intent.amount)return Refused;future+=r.intent.amount;}
|
||||
if(fence[4]=="RESYNC"&&pending)return Refused;
|
||||
if(!Q("SELECT gold FROM player WHERE id="+N(b.player)+" AND account_id="+N(b.account)+" FOR UPDATE",rows)||rows.size()!=1||rows[0].size()!=1||rows[0][0]!=N(expectedGold))return Refused;
|
||||
const auto binding=EncodeGoldSourceBinding(target);
|
||||
if(!Change("UPDATE port_cube_owner_leases SET phase='ADOPTED',revision="+N(expected.revision)+",generation="+N(l.generation)+",boot='"+l.boot+"',connection_id="+N(l.connection)+",peer="+N(peer)+",binding=X'"+PortEconomy::Hex(binding.data(),binding.size())+"',revoked_generation=0,reason=0 WHERE request='"+b.token+"' AND revision="+N(revokedRevision)+" AND phase='REVOKED'")||!db.Commit())return Retry;
|
||||
grant=std::move(expected);return Adopted; // still held; no image/currency/load/thaw side effect
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
#include "cube_gold_source.h"
|
||||
#include "economy_store.h"
|
||||
namespace PortCube {
|
||||
struct OwnerLeader {std::string boot;uint64_t generation=0,connection=0;};
|
||||
inline bool Valid(const OwnerLeader& l){return Identity(l.boot)&&l.generation&&l.connection;}
|
||||
struct OwnerGrant {OwnerLeader leader;GoldSourceBinding binding;uint32_t peer=0;uint64_t revision=0;};
|
||||
inline bool Valid(const OwnerGrant& g){return Valid(g.leader)&&g.peer&&g.revision&&!EncodeGoldSourceBinding(g.binding).empty();}
|
||||
inline bool SameOwnerGrant(const OwnerGrant& a,const OwnerGrant& b){return a.leader.boot==b.leader.boot&&a.leader.generation==b.leader.generation&&a.leader.connection==b.leader.connection&&a.peer==b.peer&&a.revision==b.revision&&EncodeGoldSourceBinding(a.binding)==EncodeGoldSourceBinding(b.binding);}
|
||||
constexpr unsigned OwnerGrantBytes=160;
|
||||
inline std::string EncodeOwnerGrant(const OwnerGrant& g) {
|
||||
if(!Valid(g))return {};Writer w;w.data="CRG1";w.data+=g.leader.boot;w.n(g.leader.generation,8);w.n(g.leader.connection,8);w.n(g.peer,4);w.n(g.revision,8);w.data+=EncodeGoldSourceBinding(g.binding);return w.data;
|
||||
}
|
||||
inline bool DecodeOwnerGrant(const std::string& body,OwnerGrant& grant) {
|
||||
grant={};if(body.size()!=OwnerGrantBytes||body.substr(0,4)!="CRG1")return false;
|
||||
Reader r(body);OwnerGrant g;r.at=4;g.leader.boot=body.substr(r.at,32);r.at+=32;
|
||||
g.leader.generation=r.n(8);g.leader.connection=r.n(8);g.peer=uint32_t(r.n(4));g.revision=r.n(8);
|
||||
if(!r.ok||!DecodeGoldSourceBinding(body.substr(r.at),g.binding)||EncodeOwnerGrant(g)!=body)return false;grant=std::move(g);return true;
|
||||
}
|
||||
template<class DB> int OwnerSchema(DB& db) {
|
||||
PortEconomy::Rows rows;const std::string names="('port_cube_owner_version','port_cube_owner_broker','port_cube_owner_leases')";
|
||||
auto query=[&](const std::string& s){return db.Query(s,rows)&&!db.warnings&&rows.size()==1&&rows[0].size()==1;};
|
||||
if(!query("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME IN "+names))return -1;
|
||||
if(rows[0][0]=="0")return 0;
|
||||
if(rows[0][0]!="3"||!query("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND ENGINE='InnoDB' AND TABLE_NAME IN "+names)||rows[0][0]!="3")return -1;
|
||||
if(!query("SELECT version FROM port_cube_owner_version WHERE id=1")||rows[0][0]!="1")return -1;return 1;
|
||||
}
|
||||
// No legacy/old-owner image ACK can remove item fences for a registered owner.
|
||||
// The adopted-owner image/thaw protocol is a separate required implementation.
|
||||
template<class DB> int OwnerReleaseStatus(DB& db,const Batch& b) {
|
||||
const int schema=OwnerSchema(db);if(schema<0)return -1;if(!schema)return 1;PortEconomy::Rows rows;
|
||||
if(!db.Query("SELECT request FROM port_cube_owner_leases WHERE request='"+b.token+"' OR pid="+std::to_string(b.player)+" FOR UPDATE",rows)||db.warnings)return -1;
|
||||
return rows.empty()?1:0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
#pragma once
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// PORT: GC93 bounded LE presentation only. Never a craft request or thaw ACK.
|
||||
namespace PortCubeView {
|
||||
constexpr unsigned Slots=225,Quickslots=36,Maximum=32768;
|
||||
constexpr int64_t GoldLimit=2000000000000000LL;
|
||||
struct Quickslot {uint8_t type=0;uint16_t cell=0;};
|
||||
inline bool operator==(const Quickslot& a,const Quickslot& b){return a.type==b.type&&a.cell==b.cell;}
|
||||
struct Item {
|
||||
uint16_t cell=0,count=0;uint32_t id=0,vnum=0,flags=0,anti=0;
|
||||
int32_t sockets[3]={};uint8_t types[7]={};int16_t values[7]={};uint8_t extra[69]={};
|
||||
};
|
||||
struct Frame {uint64_t epoch=0,gold=0;std::vector<Item> items;std::array<Quickslot,Quickslots> quickslots={};};
|
||||
inline bool Valid(const Frame& f) {
|
||||
if(!f.epoch||f.gold>uint64_t(GoldLimit)||f.items.size()>Slots)return false;
|
||||
int last=-1;std::set<uint32_t> ids;
|
||||
for(const auto& i:f.items)if(i.cell>=Slots||int(i.cell)<=last||!i.id||!i.vnum||!i.count||i.count>2000||!ids.insert(i.id).second)return false;else last=i.cell;
|
||||
for(const auto& q:f.quickslots)if(q.type>3||(!q.type&&q.cell))return false;
|
||||
return true;
|
||||
}
|
||||
struct Writer {std::string bytes;void n(uint64_t v,unsigned width){for(unsigned j=0;j<width;++j)bytes+=char(v>>(8*j));}};
|
||||
struct Reader {const std::string& bytes;size_t at=0;bool ok=true;uint64_t n(unsigned width){if(at+width>bytes.size()){ok=false;return 0;}uint64_t v=0;for(unsigned j=0;j<width;++j)v|=uint64_t(uint8_t(bytes[at++]))<<(8*j);return v;}};
|
||||
inline std::string Encode(const Frame& f) {
|
||||
if(!Valid(f))return {};Writer w;w.n(11,1);w.bytes+="CCP1";w.n(f.epoch,8);w.n(f.gold,8);w.n(f.items.size(),2);w.n(Quickslots,1);
|
||||
for(const auto& q:f.quickslots){w.n(q.type,1);w.n(q.cell,2);}
|
||||
for(const auto& i:f.items) {
|
||||
w.n(i.cell,2);w.n(i.count,2);w.n(i.id,4);w.n(i.vnum,4);w.n(i.flags,4);w.n(i.anti,4);
|
||||
for(auto v:i.sockets)w.n(uint32_t(v),4);
|
||||
for(unsigned j=0;j<7;++j){w.n(i.types[j],1);w.n(uint16_t(i.values[j]),2);}
|
||||
w.bytes.append(reinterpret_cast<const char*>(i.extra),69);
|
||||
}
|
||||
return w.bytes.size()+5<=Maximum?w.bytes:std::string{};
|
||||
}
|
||||
inline bool Decode(const std::string& bytes,Frame& out) {
|
||||
out={};if(bytes.size()<132||bytes.size()+5>Maximum||uint8_t(bytes[0])!=11||bytes.substr(1,4)!="CCP1")return false;
|
||||
Reader r{bytes};r.at=5;Frame f;f.epoch=r.n(8);f.gold=r.n(8);const auto count=r.n(2);
|
||||
if(count>Slots||r.n(1)!=Quickslots||bytes.size()!=132+122*count)return false;
|
||||
for(auto& q:f.quickslots){q.type=uint8_t(r.n(1));q.cell=uint16_t(r.n(2));}
|
||||
for(unsigned j=0;j<count;++j) {
|
||||
Item i;i.cell=uint16_t(r.n(2));i.count=uint16_t(r.n(2));i.id=uint32_t(r.n(4));i.vnum=uint32_t(r.n(4));i.flags=uint32_t(r.n(4));i.anti=uint32_t(r.n(4));
|
||||
for(auto& v:i.sockets){uint32_t bits=uint32_t(r.n(4));std::memcpy(&v,&bits,4);}
|
||||
for(unsigned k=0;k<7;++k){i.types[k]=uint8_t(r.n(1));uint16_t bits=uint16_t(r.n(2));std::memcpy(&i.values[k],&bits,2);}
|
||||
for(auto& v:i.extra)v=uint8_t(r.n(1));f.items.push_back(i);
|
||||
}
|
||||
if(!r.ok||r.at!=bytes.size()||!Valid(f)||Encode(f)!=bytes)return false;out=std::move(f);return true;
|
||||
}
|
||||
// Snapshot old bindings ONCE before installing any new items. Never bind a
|
||||
// consumed item's shortcut to a new reward merely reusing the same cell.
|
||||
inline bool Rebind(const std::vector<Item>& before,const Frame& after,const std::array<Quickslot,Quickslots>& original,std::array<Quickslot,Quickslots>& result) {
|
||||
if(!Valid(after))return false;std::set<uint16_t> cells;std::set<uint32_t> ids;
|
||||
for(const auto& i:before)if(i.cell>=Slots||!i.id||!cells.insert(i.cell).second||!ids.insert(i.id).second)return false;
|
||||
auto plan=original;
|
||||
for(auto& q:plan) {
|
||||
if(q.type>3||(!q.type&&q.cell))return false;if(q.type!=1||q.cell>=Slots)continue;
|
||||
const auto old=std::find_if(before.begin(),before.end(),[&](const Item& i){return i.cell==q.cell;});
|
||||
const auto next=old==before.end()?after.items.end():std::find_if(after.items.begin(),after.items.end(),[&](const Item& i){return i.id==old->id;});
|
||||
if(next==after.items.end())q={};else q.cell=next->cell;
|
||||
}
|
||||
result=plan;return true;
|
||||
}
|
||||
inline std::string Packet(const Frame& f){const auto body=Encode(f);if(body.empty())return {};Writer w;w.n(93,1);w.n(body.size()+5,4);return w.bytes+body;}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
#include <cerrno>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
namespace PortCube {
|
||||
class CraftEntropy {
|
||||
int fd=-1;
|
||||
public:
|
||||
CraftEntropy():fd(open("/dev/urandom",O_RDONLY|O_CLOEXEC)){}
|
||||
CraftEntropy(const CraftEntropy&)=delete;CraftEntropy& operator=(const CraftEntropy&)=delete;
|
||||
~CraftEntropy(){if(fd>=0)close(fd);}
|
||||
unsigned Draw() {
|
||||
if(fd<0)return 0;
|
||||
for(unsigned attempts=0;attempts<1024;++attempts) {
|
||||
unsigned char byte=0;ssize_t n;do{n=read(fd,&byte,1);}while(n<0&&errno==EINTR);
|
||||
if(n!=1)return 0;if(byte<200)return unsigned(byte)%100+1; // unbiased two samples per outcome
|
||||
}
|
||||
return 0; // no deterministic fallback or unbounded source failure loop
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
#include "cube_batch.h"
|
||||
namespace PortCube {
|
||||
struct CraftReceipt {std::string result;unsigned successes=0;uint64_t fee=0;std::vector<Item> awards;};
|
||||
inline unsigned CraftCode(const std::string& name) {
|
||||
const std::vector<std::string> names={"ok","gold_changed","inventory_changed","materials_missing","gold_missing","capacity_full","item_proto","inventory_invalid"};
|
||||
const auto found=std::find(names.begin(),names.end(),name);return found==names.end()?0:unsigned(found-names.begin())+1;
|
||||
}
|
||||
inline std::string EncodeCraftReceipt(const CraftReceipt& receipt) {
|
||||
const auto code=CraftCode(receipt.result);
|
||||
if(!code||receipt.successes>100||receipt.fee>uint64_t(PortEconomy::GoldLimit)||receipt.awards.size()>100||
|
||||
(code!=1&&(receipt.successes||receipt.fee||!receipt.awards.empty())))return {};
|
||||
std::set<uint32_t> ids;std::set<uint16_t> cells;
|
||||
for(const auto& item:receipt.awards)if(!item.value.id||!item.value.vnum||!item.value.count||item.value.count>2000||!item.usable||item.cell>=225||!ids.insert(item.value.id).second||!cells.insert(item.cell).second)return {};
|
||||
Writer w;w.data="CCR1";w.n(code,1);w.n(receipt.successes,1);w.n(receipt.fee,8);w.items(receipt.awards);return w.data;
|
||||
}
|
||||
inline bool DecodeCraftReceipt(const std::string& bytes,CraftReceipt& out) {
|
||||
out={};if(bytes.size()<16||bytes.size()>11716||bytes.substr(0,4)!="CCR1")return false;Reader r(bytes);r.at=4;
|
||||
const auto code=r.n(1);const std::vector<std::string> names={"ok","gold_changed","inventory_changed","materials_missing","gold_missing","capacity_full","item_proto","inventory_invalid"};
|
||||
if(!code||code>names.size())return false;CraftReceipt receipt;receipt.result=names[size_t(code)-1];receipt.successes=unsigned(r.n(1));receipt.fee=r.n(8);receipt.awards=r.items();
|
||||
if(!r.ok||r.at!=bytes.size()||EncodeCraftReceipt(receipt)!=bytes)return false;out=std::move(receipt);return true;
|
||||
}
|
||||
inline bool ValidateCraftReceipt(const Batch& b,const CraftReceipt& receipt,const Lookup& lookup) {
|
||||
if(!Validate(b)||EncodeCraftReceipt(receipt).empty())return false;if(receipt.result!="ok")return true;
|
||||
if(receipt.successes>b.attempts||(!b.recipe.percent&&receipt.successes)||(b.recipe.percent==100&&receipt.successes!=b.attempts))return false;
|
||||
std::string rolls(b.attempts,char(100));for(unsigned n=0;n<receipt.successes;++n)rolls[n]=char(1);
|
||||
const auto plan=SettlePlan(b,rolls,lookup);Writer actual,expected;actual.items(receipt.awards);expected.items(plan.awards);
|
||||
return plan.result=="ok"&&plan.successes==receipt.successes&&plan.fee==receipt.fee&&actual.data==expected.data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
#pragma once
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <iomanip>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// PORT: read-only normalization and consumption planning. No inventory mutation,
|
||||
// RNG, durable receipt, or implicit permission to craft lives in this layer.
|
||||
namespace PortCube {
|
||||
constexpr unsigned MaxAttempts=100,MaxRecipes=4096;
|
||||
struct Material {uint32_t vnum=0,count=0;};
|
||||
struct Recipe {
|
||||
uint32_t id=0,reward=0,rewardCount=0,gold=0;
|
||||
unsigned percent=0;bool stackable=false,copy=false;
|
||||
std::string category="WORLDARD";
|
||||
std::vector<uint32_t> npcs;
|
||||
std::vector<Material> materials;
|
||||
};
|
||||
inline bool Normalize(Recipe& r) {
|
||||
if(!r.id||!r.reward||!r.rewardCount||r.rewardCount>2000||(!r.stackable&&r.rewardCount!=1)||
|
||||
r.percent>100||r.npcs.empty()||r.npcs.size()>128||r.materials.empty()||r.materials.size()>5||
|
||||
r.category.empty()||r.category.size()>24)return false;
|
||||
for(char c:r.category)if(!((c>='a'&&c<='z')||(c>='A'&&c<='Z')||(c>='0'&&c<='9')||c=='_'))return false;
|
||||
for(auto npc:r.npcs)if(!npc||npc>65535)return false;
|
||||
std::sort(r.npcs.begin(),r.npcs.end());r.npcs.erase(std::unique(r.npcs.begin(),r.npcs.end()),r.npcs.end());
|
||||
std::vector<Material> merged;
|
||||
for(auto m:r.materials) {
|
||||
if(!m.vnum||!m.count||m.count>2000)return false;
|
||||
auto it=std::find_if(merged.begin(),merged.end(),[&](const Material& a){return a.vnum==m.vnum;});
|
||||
if(it==merged.end())merged.push_back(m);
|
||||
else {if(it->count>2000-m.count)return false;it->count+=m.count;}
|
||||
}
|
||||
r.materials=merged;return true;
|
||||
}
|
||||
inline std::string Fingerprint(const std::string& text) {
|
||||
uint64_t hash=14695981039346656037ULL;
|
||||
for(unsigned char c:text){hash^=c;hash*=1099511628211ULL;}
|
||||
std::ostringstream s;s<<std::hex<<std::setw(16)<<std::setfill('0')<<hash;return s.str();
|
||||
}
|
||||
inline std::string Revision(const Recipe& r) {
|
||||
std::ostringstream s;s<<r.id<<':'<<r.reward<<':'<<r.rewardCount<<':'<<r.gold<<':'<<r.percent<<':'<<r.stackable<<':'<<r.copy<<':'<<r.category;
|
||||
for(auto n:r.npcs)s<<":n"<<n;
|
||||
for(auto m:r.materials)s<<":m"<<m.vnum<<','<<m.count;
|
||||
return Fingerprint(s.str()); // staleness fingerprint, not a cryptographic authorization token
|
||||
}
|
||||
struct Input {uint32_t id=0,vnum=0,count=0;uint16_t cell=0;bool usable=true;};
|
||||
struct Take {uint32_t id=0,vnum=0,count=0,before=0;uint16_t cell=0;};
|
||||
struct Plan {
|
||||
bool valid=false,materialsOK=false,goldOK=false;
|
||||
uint64_t gold=0,rewardMaximum=0;
|
||||
std::vector<uint64_t> needed,available;
|
||||
std::vector<Take> takes;
|
||||
};
|
||||
inline Plan Preview(Recipe recipe,unsigned attempts,std::vector<Input> inputs,int64_t gold) {
|
||||
Plan p;if(!Normalize(recipe)||!attempts||attempts>MaxAttempts||gold<0||inputs.size()>225)return p;
|
||||
std::set<uint32_t> ids;std::set<uint16_t> cells;
|
||||
for(auto i:inputs)if(!i.id||!i.vnum||!i.count||i.count>2000||i.cell>=225||!ids.insert(i.id).second||!cells.insert(i.cell).second)return p;
|
||||
std::sort(inputs.begin(),inputs.end(),[](const Input& a,const Input& b){return a.cell<b.cell;});
|
||||
p.gold=uint64_t(recipe.gold)*attempts;p.rewardMaximum=uint64_t(recipe.rewardCount)*attempts;
|
||||
p.goldOK=uint64_t(gold)>=p.gold;p.materialsOK=true;
|
||||
for(auto m:recipe.materials) {
|
||||
const uint64_t need=uint64_t(m.count)*attempts;uint64_t available=0,left=need;
|
||||
for(auto i:inputs)if(i.usable&&i.vnum==m.vnum) {
|
||||
available+=i.count;const auto count=static_cast<uint32_t>(std::min(left,uint64_t(i.count)));
|
||||
if(count)p.takes.push_back({i.id,i.vnum,count,i.count,i.cell});left-=count;
|
||||
}
|
||||
p.needed.push_back(need);p.available.push_back(available);p.materialsOK&=available>=need;
|
||||
}
|
||||
p.valid=true;return p;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
#pragma once
|
||||
#include "cube_handshake.h"
|
||||
namespace PortCube {
|
||||
inline Handshake RecoveryRequest(uint32_t account,uint32_t player,uint64_t session) {
|
||||
Handshake f;f.message=Message::RecoveryClaim;f.account=account;f.player=player;f.session=session;f.owner=f.token=std::string(32,'0');return f;
|
||||
}
|
||||
// This pre-load coordinator never grants actor action permission. Clear only
|
||||
// authorizes a normal load request, whose DB guards must still run again.
|
||||
class RecoveryFlow {
|
||||
public:
|
||||
enum Stage {Idle,Waiting,Held,Granted,Clear,Loading,ImageReady};
|
||||
private:
|
||||
Handshake request;OwnerGrant grant;Stage stage=Idle;bool lost=false;std::string image;
|
||||
public:
|
||||
Stage State()const{return stage;}
|
||||
const OwnerGrant& Grant()const{return grant;}
|
||||
const Handshake& Request()const{return request;}
|
||||
const std::string& Image()const{return image;}
|
||||
bool MayRequestImage()const{return !lost&&stage==Granted;}
|
||||
Handshake ImageRequest()const {
|
||||
Handshake f=request;f.message=Message::RecoveryImageRequest;const auto& b=grant.binding;
|
||||
f.cookie=b.cookie;f.epoch=b.epoch;f.owner=b.owner;f.token=b.request;f.body=EncodeOwnerGrant(grant);return f;
|
||||
}
|
||||
bool Start(uint32_t account,uint32_t player,uint64_t session) {
|
||||
auto f=RecoveryRequest(account,player,session);if(stage!=Idle||!ValidHandshake(f))return false;request=std::move(f);stage=Waiting;return true;
|
||||
}
|
||||
bool MayRetry()const{return !lost&&(stage==Waiting||stage==Held);}
|
||||
void LostTransport(){if(stage!=Idle){lost=true;stage=Held;image.clear();}}
|
||||
bool Answer(uint32_t handle,const Handshake& f) {
|
||||
if(lost||stage==Idle||stage==Loading||!ValidHandshake(f)||f.account!=request.account||f.player!=request.player||f.session!=request.session)return false;
|
||||
if(f.message==Message::RecoveryImageAnswer) {
|
||||
if(stage!=Granted&&stage!=ImageReady)return false;
|
||||
OwnerGrant g;std::string data;
|
||||
if(f.status==Status::Held){return stage==Granted&&DecodeOwnerGrant(f.body,g)&&g.binding.handle==handle&&SameOwnerGrant(g,grant);}
|
||||
if(!DecodeRecoveryImage(f.body,g,data)||g.binding.handle!=handle||!SameOwnerGrant(g,grant))return false;
|
||||
if(stage==ImageReady){if(data==image)return true;LostTransport();return false;}
|
||||
image=std::move(data);stage=ImageReady;return true;
|
||||
}
|
||||
if(f.message!=Message::RecoveryAnswer)return false;
|
||||
if(f.status==Status::RecoveryGranted) {
|
||||
OwnerGrant g;if(!DecodeOwnerGrant(f.body,g)||g.binding.handle!=handle)return false;
|
||||
if(stage==Granted||stage==ImageReady)return SameOwnerGrant(g,grant);
|
||||
if(stage==Clear)return false;grant=std::move(g);stage=Granted;return true;
|
||||
}
|
||||
if(stage==Granted||stage==Clear||stage==ImageReady)return false;
|
||||
stage=f.status==Status::RecoveryClear?Clear:Held;return true;
|
||||
}
|
||||
bool TakeClear(){if(lost||stage!=Clear)return false;stage=Loading;return true;}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
#pragma once
|
||||
#include "cube_image_ack.h"
|
||||
namespace PortCube {
|
||||
template<class DB> bool ReleaseSchema(DB& db) {
|
||||
PortEconomy::Rows rows;const std::string names="('port_cube_release_version','port_cube_releases')";
|
||||
auto q=[&](const std::string& sql){return db.Query(sql,rows)&&!db.warnings&&rows.size()==1&&rows[0].size()==1;};
|
||||
return q("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME IN "+names)&&rows[0][0]=="2"&&
|
||||
q("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND ENGINE='InnoDB' AND TABLE_NAME IN "+names)&&rows[0][0]=="2"&&
|
||||
q("SELECT version FROM port_cube_release_version WHERE id=1")&&rows[0][0]=="1";
|
||||
}
|
||||
// Terminal SQL decision, NOT actor readiness or permission to thaw. The runtime
|
||||
// keeps its save/load gate until an independently verified resume handoff.
|
||||
template<class DB> class ReleaseStore {
|
||||
DB& db;Lookup lookup;
|
||||
static std::string X(const std::string& s){return "X'"+PortEconomy::Hex(s.data(),s.size())+"'";}
|
||||
public:
|
||||
enum Result {Retry,Refused,Released};
|
||||
ReleaseStore(DB& d,Lookup p):db(d),lookup(std::move(p)){}
|
||||
enum CheckResult {CheckRetry,CheckRefused,Checked};
|
||||
CheckResult CheckResumeLive(const Batch& b,const OwnerGrant& grant,const std::string& image) {
|
||||
InventoryImage decoded;
|
||||
if(!Validate(b)||!Valid(grant)||!Matches(grant.binding,b)||!DecodeInventoryImage(image,decoded,lookup))return CheckRefused;
|
||||
if(!ImageAckSchema(db)||!ReleaseSchema(db))return CheckRetry;
|
||||
OwnerStore<DB> owner(db,lookup);FenceStore<DB> fence(db,lookup);
|
||||
const auto result=fence.CheckReleasedImage(b,image,[&]()->bool{
|
||||
PortEconomy::Rows rows;const std::vector<std::string> exact={Encode(b),EncodeOwnerGrant(grant),image};
|
||||
auto q=[&](const std::string& sql){return db.Query(sql,rows)&&!db.warnings;};
|
||||
if(!q("SELECT body,owner_grant,image FROM port_cube_image_acks WHERE request='"+b.token+"' FOR UPDATE")||rows.size()!=1||rows[0]!=exact)return false;
|
||||
if(!q("SELECT body,owner_grant,image FROM port_cube_releases WHERE request='"+b.token+"' FOR UPDATE")||rows.size()!=1||rows[0]!=exact)return false;
|
||||
if(!q("SELECT id FROM port_cube_item_fences WHERE pid="+std::to_string(b.player)+" OR request='"+b.token+"' FOR UPDATE")||!rows.empty())return false;
|
||||
return owner.ReleasedImageWithin(b,grant,image);
|
||||
});
|
||||
return result==FenceStore<DB>::Done?Checked:result==FenceStore<DB>::Retry?CheckRetry:CheckRefused;
|
||||
}
|
||||
Result ReleaseLive(const Batch& b,const OwnerGrant& grant,const std::string& image) {
|
||||
InventoryImage decoded;
|
||||
if(!Validate(b)||!Valid(grant)||!Matches(grant.binding,b)||!DecodeInventoryImage(image,decoded,lookup))return Refused;
|
||||
if(!ImageAckSchema(db)||!ReleaseSchema(db))return Retry;
|
||||
OwnerStore<DB> owner(db,lookup);FenceStore<DB> fence(db,lookup);
|
||||
const auto result=fence.Release(b,image,[&](bool replay)->bool {
|
||||
PortEconomy::Rows rows;auto q=[&](const std::string& sql){return db.Query(sql,rows)&&!db.warnings;};
|
||||
const std::vector<std::string> exact={Encode(b),EncodeOwnerGrant(grant),image};
|
||||
if(!q("SELECT body,owner_grant,image FROM port_cube_image_acks WHERE request='"+b.token+"' FOR UPDATE")||rows.size()!=1||rows[0]!=exact)return false;
|
||||
if(replay&&!owner.ReleasedWithin(b,grant))return false;
|
||||
if(!replay&&!owner.LiveImageWithin(b,grant,image))return false;
|
||||
if(!replay&&(!q("SELECT id FROM port_cube_item_fences WHERE request='"+b.token+"' AND pid<>"+std::to_string(b.player)+" FOR UPDATE")||!rows.empty()))return false;
|
||||
if(!q("SELECT body,owner_grant,image FROM port_cube_releases WHERE request='"+b.token+"' FOR UPDATE"))return false;
|
||||
if(replay) {
|
||||
if(rows.size()!=1||rows[0]!=exact)return false;
|
||||
// A terminal replay cannot bless a partially removed fence.
|
||||
return q("SELECT id FROM port_cube_item_fences WHERE pid="+std::to_string(b.player)+" OR request='"+b.token+"' FOR UPDATE")&&rows.empty();
|
||||
}
|
||||
if(!rows.empty())return false; // terminal history with LIVE lease is inconsistent
|
||||
if(!q("INSERT INTO port_cube_releases(request,body,owner_grant,image) VALUES('"+b.token+"',"+X(exact[0])+","+X(exact[1])+","+X(image)+")")||db.affected!=1)return false;
|
||||
return q("DELETE FROM port_cube_owner_leases WHERE request='"+b.token+"' AND phase='LIVE' AND revision="+std::to_string(grant.revision))&&db.affected==1;
|
||||
});
|
||||
return result==FenceStore<DB>::Done?Released:result==FenceStore<DB>::Retry?Retry:Refused;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
#pragma once
|
||||
#include "cube_batch.h"
|
||||
#include "economy_store.h"
|
||||
|
||||
namespace PortCube {
|
||||
// Candidate DB transaction engine. Nothing calls it from the live game yet.
|
||||
// Shared economy ID tombstones ensure prepared factory IDs cannot be recycled
|
||||
// by the existing DB restart high-water algorithm, even after a rejected batch.
|
||||
template<class DB> class BatchStore {
|
||||
DB& db;Lookup lookup;
|
||||
using Rows=PortEconomy::Rows;
|
||||
static std::string N(uint64_t value){return std::to_string(value);}
|
||||
// Silent truncation is an error even on a non-strict MySQL connection.
|
||||
bool Q(const std::string& sql,Rows& rows){return db.Query(sql,rows)&&db.warnings==0;}
|
||||
bool Run(const std::string& sql){Rows rows;return Q(sql,rows);}
|
||||
bool Change(const std::string& sql){return Run(sql)&&db.affected==1;}
|
||||
bool One(const std::string& sql,Rows& rows){return Q(sql,rows)&&rows.size()==1;}
|
||||
struct Guard {DB& db;~Guard(){db.Rollback();}};
|
||||
bool LockAccount(uint32_t account){Rows rows;return Run("INSERT INTO port_economy_account_lock(account) VALUES("+N(account)+") ON DUPLICATE KEY UPDATE account=VALUES(account)")&&One("SELECT account FROM port_economy_account_lock WHERE account="+N(account)+" FOR UPDATE",rows);}
|
||||
int Fence(const Batch& b) {
|
||||
Rows rows;
|
||||
if(!Q("SELECT epoch,owner,request,phase,body,drain_state FROM port_cube_fences WHERE pid="+N(b.player)+" AND account="+N(b.account)+" FOR UPDATE",rows))return -1;
|
||||
if(rows.size()!=1||rows[0].size()!=6||rows[0][0]!=N(b.epoch)||rows[0][1]!=b.owner||rows[0][2]!=b.token||rows[0][3]!="FROZEN"||rows[0][4]!=Encode(b)||rows[0][5]!="1")return 0;
|
||||
if(!Q("SELECT id,epoch,request FROM port_cube_item_fences WHERE pid="+N(b.player)+" FOR UPDATE",rows))return -1;
|
||||
std::set<uint32_t> locked;
|
||||
for(const auto& row:rows){uint64_t id=0;if(row.size()!=3||!PortEconomy::Number(row[0],id,UINT32_MAX)||!id||row[1]!=N(b.epoch)||row[2]!=b.token||!locked.insert(uint32_t(id)).second)return 0;}
|
||||
for(const auto& item:b.inventory)if(!locked.count(item.value.id))return 0;
|
||||
for(const auto& item:b.rewards)if(!locked.count(item.id))return 0;
|
||||
if(!Q("SELECT token FROM port_economy_pending WHERE pid="+N(b.player)+" FOR UPDATE",rows))return -1;
|
||||
return rows.empty()?1:0;
|
||||
}
|
||||
static std::string Columns() {
|
||||
std::string s="id,vnum,count,pos";
|
||||
for(unsigned i=0;i<3;++i)s+=",socket"+N(i);
|
||||
for(unsigned i=0;i<7;++i)s+=",attrtype"+N(i)+",attrvalue"+N(i);
|
||||
return s+",port_extra";
|
||||
}
|
||||
static std::vector<std::string> ItemRow(const Item& i) {
|
||||
const auto& item=i.value;std::vector<std::string> row={N(item.id),N(item.vnum),N(item.count),N(i.cell)};
|
||||
for(auto socket:item.sockets)row.push_back(std::to_string(socket));
|
||||
for(unsigned n=0;n<7;++n){row.push_back(N(item.types[n]));row.push_back(std::to_string(item.values[n]));}
|
||||
row.emplace_back(reinterpret_cast<const char*>(item.extra),sizeof(item.extra));return row;
|
||||
}
|
||||
bool Inventory(const Batch& b,bool& matches) {
|
||||
Rows rows;if(!Q("SELECT "+Columns()+" FROM item WHERE owner_id="+N(b.player)+" AND window='INVENTORY' AND pos<225 ORDER BY pos,id FOR UPDATE",rows))return false;
|
||||
matches=rows.size()==b.inventory.size();
|
||||
for(unsigned i=0;matches&&i<rows.size();++i)matches=rows[i]==ItemRow(b.inventory[i]);
|
||||
return true;
|
||||
}
|
||||
bool Insert(uint32_t player,const Item& i) {
|
||||
const auto row=ItemRow(i);std::string values;
|
||||
for(unsigned n=0;n+1<row.size();++n){if(n)values+=',';values+=row[n];}
|
||||
values+=",X'"+PortEconomy::Hex(row.back().data(),row.back().size())+"'";
|
||||
return Change("INSERT INTO item("+Columns()+",owner_id,window) VALUES("+values+","+N(player)+",'INVENTORY')");
|
||||
}
|
||||
public:
|
||||
enum Result { Retry, Rejected, Prepared, Complete, Blocked };
|
||||
struct Receipt {std::string result;unsigned successes=0;uint64_t fee=0;std::vector<Item> awards;};
|
||||
BatchStore(DB& database,Lookup proto):db(database),lookup(std::move(proto)){}
|
||||
// Read-only validation shared with deferred-credit recovery. Never execute
|
||||
// PREPARED just to inspect a receipt; callers must hold the account lock.
|
||||
static bool DoneReceipt(const Batch& b,const std::vector<std::string>& saved,Receipt& receipt) {
|
||||
receipt={};if(!Validate(b)||saved.size()!=7||saved[0]!=Encode(b)||saved[2]!="DONE")return false;
|
||||
uint64_t successes=0,fee=0;Reader r(saved[6]);auto awards=r.items();
|
||||
if(!PortEconomy::Number(saved[4],successes,b.attempts)||!PortEconomy::Number(saved[5],fee,PortEconomy::GoldLimit)||!r.ok||r.at!=saved[6].size())return false;
|
||||
const std::set<std::string> results={"ok","gold_changed","inventory_changed","materials_missing","gold_missing","capacity_full","item_proto","inventory_invalid"};
|
||||
if(!results.count(saved[3])||saved[1].size()!=b.attempts)return false;
|
||||
unsigned rolled=0;for(unsigned char roll:saved[1]){if(roll<1||roll>100)return false;rolled+=roll<=b.recipe.percent;}
|
||||
if(saved[3]!="ok") {if(successes||fee||!awards.empty())return false;}
|
||||
else {
|
||||
if(successes!=rolled||fee!=uint64_t(b.recipe.gold)*b.attempts||fee>b.gold)return false;
|
||||
uint64_t remaining=successes*b.recipe.rewardCount;std::set<unsigned> cells;
|
||||
if(awards.size()>b.rewards.size())return false;
|
||||
for(unsigned n=0;n<awards.size();++n) {
|
||||
if(!remaining||awards[n].cell>=225||!awards[n].usable||!cells.insert(awards[n].cell).second)return false;
|
||||
auto expected=b.rewards[n];expected.count=uint32_t(std::min(remaining,uint64_t(b.recipe.stackable?2000:1)));
|
||||
Writer actual,image;actual.reward(awards[n].value);image.reward(expected);
|
||||
if(actual.data!=image.data)return false;remaining-=expected.count;
|
||||
}
|
||||
if(remaining)return false;
|
||||
}
|
||||
receipt={saved[3],unsigned(successes),fee,std::move(awards)};return true;
|
||||
}
|
||||
bool Ready() {
|
||||
Rows rows;
|
||||
if(!One("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND ENGINE='InnoDB' AND TABLE_NAME IN ('player','item','port_cube_version','port_cube_requests','port_cube_fences','port_cube_item_fences','port_economy_account_lock','port_economy_item_reservations','port_economy_custody','port_economy_pending','port_economy_version')",rows)||rows[0][0]!="11"||
|
||||
!One("SELECT version FROM port_cube_version WHERE id=1",rows)||rows[0][0]!="2"||
|
||||
!One("SELECT version FROM port_economy_version WHERE id=1",rows)||rows[0][0]!="1")return false;
|
||||
// Do not silently discard a future item column. All item state must be
|
||||
// covered by both the snapshot comparison and the reward factory image.
|
||||
if(!Q("SHOW COLUMNS FROM item",rows))return false;
|
||||
std::set<std::string> expected={"id","owner_id","window","pos","count","vnum","port_extra"};
|
||||
for(unsigned i=0;i<3;++i)expected.insert("socket"+N(i));
|
||||
for(unsigned i=0;i<7;++i){expected.insert("attrtype"+N(i));expected.insert("attrvalue"+N(i));}
|
||||
for(const auto& row:rows) {
|
||||
if(row.empty()||!expected.erase(row[0]))return false;
|
||||
if(row[0]=="port_extra"&&(row.size()<3||(row[1]!="varbinary(69)"&&row[1]!="binary(69)")||row[2]!="NO"))return false;
|
||||
}
|
||||
return expected.empty();
|
||||
}
|
||||
// Draw callback is DB-side trusted RNG, called ONLY for a newly accepted
|
||||
// identity. Every draw is durable before any asset mutation is attempted.
|
||||
Result Prepare(const Batch& b,const std::function<unsigned()>& draw,const std::function<bool()>& authorize={}) {
|
||||
if(!Validate(b))return Rejected;
|
||||
if(!Ready()||!db.Begin())return Retry;
|
||||
Guard guard{db};
|
||||
Rows rows;const auto body=Encode(b);
|
||||
auto stop=[](Result result){return result;};
|
||||
if(!LockAccount(b.account))return stop(Retry);
|
||||
if(authorize&&!authorize())return stop(Blocked);
|
||||
if(!Q("SELECT body,state FROM port_cube_requests WHERE token='"+b.token+"' FOR UPDATE",rows))return stop(Retry);
|
||||
if(!rows.empty()) {
|
||||
if(rows.size()!=1||rows[0].size()!=2||rows[0][0]!=body||(rows[0][1]!="PREPARED"&&rows[0][1]!="DONE"))return stop(Rejected);
|
||||
// Even DONE requests replay without drawing or touching assets.
|
||||
return stop(Prepared);
|
||||
}
|
||||
const int fence=Fence(b);if(fence<=0)return stop(fence<0?Retry:Blocked);
|
||||
for(const auto& reward:b.rewards) {
|
||||
if(!Q("SELECT id FROM item WHERE id="+N(reward.id)+" UNION ALL SELECT id FROM port_economy_custody WHERE id="+N(reward.id),rows))return stop(Retry);
|
||||
if(!rows.empty())return stop(Rejected);
|
||||
if(!Q("SELECT request FROM port_economy_item_reservations WHERE id="+N(reward.id)+" FOR UPDATE",rows))return stop(Retry);
|
||||
if(rows.empty()) {if(!Change("INSERT INTO port_economy_item_reservations(id,request) VALUES("+N(reward.id)+",'"+b.token+"')"))return stop(Retry);}
|
||||
else if(rows.size()!=1||rows[0].size()!=1||rows[0][0]!=b.token)return stop(Rejected);
|
||||
}
|
||||
std::string rolls;for(unsigned i=0;i<b.attempts;++i){const auto roll=draw();if(roll<1||roll>100)return stop(Rejected);rolls+=char(roll);}
|
||||
if(!Change("INSERT INTO port_cube_requests(token,account,pid,body,rolls,state,result,successes,fee,awards) VALUES('"+b.token+"',"+N(b.account)+","+N(b.player)+",X'"+PortEconomy::Hex(body.data(),body.size())+"',X'"+PortEconomy::Hex(rolls.data(),rolls.size())+"','PREPARED','prepared',0,0,X'0000')")||!db.Commit())return stop(Retry);
|
||||
return Prepared;
|
||||
}
|
||||
// Identity-only recovery loads the complete immutable request and fixed RNG
|
||||
// from storage. A disconnected caller cannot supply a replacement snapshot.
|
||||
Result Execute(const std::string& token,uint32_t account,uint32_t player,Receipt& receipt,const std::function<bool(const Batch&)>& authorize={}) {
|
||||
receipt={};if(!Identity(token)||!account||!player)return Rejected;
|
||||
if(!Ready()||!db.Begin())return Retry;
|
||||
Guard guard{db};
|
||||
auto stop=[](Result result){return result;};Rows rows;
|
||||
if(!LockAccount(account)||!Q("SELECT body,rolls,state,result,successes,fee,awards FROM port_cube_requests WHERE token='"+token+"' AND account="+N(account)+" AND pid="+N(player)+" FOR UPDATE",rows))return stop(Retry);
|
||||
if(rows.empty())return stop(Rejected);
|
||||
if(rows.size()!=1||rows[0].size()!=7)return stop(Retry);
|
||||
const auto saved=rows[0];Batch b;uint64_t fee=0;
|
||||
if(!Decode(saved[0],b)||b.token!=token||b.account!=account||b.player!=player)return stop(Retry);
|
||||
if(authorize&&!authorize(b))return stop(Blocked);
|
||||
if(saved[2]=="DONE") {
|
||||
return stop(DoneReceipt(b,saved,receipt)?Complete:Retry);
|
||||
}
|
||||
if(saved[2]!="PREPARED")return stop(Retry);
|
||||
const int fence=Fence(b);if(fence<=0)return stop(fence<0?Retry:Blocked);
|
||||
if(!One("SELECT gold FROM player WHERE id="+N(player)+" AND account_id="+N(account)+" FOR UPDATE",rows)||rows[0].size()!=1||!PortEconomy::Number(rows[0][0],fee,PortEconomy::GoldLimit))return stop(Retry);
|
||||
Settlement plan;
|
||||
if(fee!=b.gold)plan.result="gold_changed";
|
||||
else {
|
||||
bool matches=false;if(!Inventory(b,matches))return stop(Retry);
|
||||
if(!matches)plan.result="inventory_changed";
|
||||
else plan=SettlePlan(b,saved[1],lookup);
|
||||
}
|
||||
if(plan.result=="invalid")return stop(Retry); // corrupt persisted input: quarantine, never charge
|
||||
if(plan.result=="ok") {
|
||||
for(const auto& take:plan.takes) {
|
||||
const std::string where=" WHERE id="+N(take.id)+" AND owner_id="+N(player)+" AND window='INVENTORY' AND count="+N(take.before);
|
||||
if(!Change(take.count==take.before?"DELETE FROM item"+where:"UPDATE item SET count=count-"+N(take.count)+where))return stop(Retry);
|
||||
}
|
||||
if(plan.fee&&!Change("UPDATE player SET gold=gold-"+N(plan.fee)+" WHERE id="+N(player)+" AND account_id="+N(account)+" AND gold="+N(b.gold)))return stop(Retry);
|
||||
for(const auto& award:plan.awards)if(!Insert(player,award))return stop(Retry);
|
||||
} else {plan.successes=0;plan.fee=0;plan.awards.clear();}
|
||||
Writer awards;awards.items(plan.awards);
|
||||
if(!Change("UPDATE port_cube_requests SET state='DONE',result='"+plan.result+"',successes="+N(plan.successes)+",fee="+N(plan.fee)+",awards=X'"+PortEconomy::Hex(awards.data.data(),awards.data.size())+"' WHERE token='"+token+"' AND state='PREPARED'")||!db.Commit())return stop(Retry);
|
||||
receipt={plan.result,plan.successes,plan.fee,std::move(plan.awards)};return Complete;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
// Internal game/db protocol only. No client-supplied identity or price is trusted.
|
||||
namespace PortEconomy {
|
||||
constexpr uint8_t Header = 77;
|
||||
enum Operation : uint8_t { List=1, Buy, Refund, Claim, Cancel, Withdraw, GayaBuy, GayaRefresh, GayaExpand, Status, GayaRetire, UiStatus };
|
||||
// Reserved terminal generation: preserve the catalogue as an audit tombstone.
|
||||
constexpr uint64_t RetiredGeneration=INT64_MAX;
|
||||
constexpr int64_t GoldLimit=2000000000000000LL;
|
||||
#pragma pack(push,1)
|
||||
struct Offer { uint32_t vnum=0,count=0;int32_t price=0;uint8_t bought=0; };
|
||||
#pragma pack(pop)
|
||||
struct Reward {
|
||||
uint32_t id=0,vnum=0,count=0;
|
||||
int32_t sockets[3]={};uint8_t types[7]={};int16_t values[7]={};uint8_t extra[69]={};
|
||||
};
|
||||
struct Request {
|
||||
uint32_t version=1,account=0,player=0;
|
||||
uint8_t operation=0;
|
||||
char token[33]={};
|
||||
alignas(8) uint64_t reference=0;
|
||||
alignas(8) int64_t price=0;
|
||||
alignas(8) int64_t expectedGold=0;
|
||||
int32_t expectedGem=0,expectedOpen=0,deadline=0,nextDeadline=0;
|
||||
uint32_t item=0,itemVnum=0,itemCount=0;
|
||||
alignas(8) uint64_t generation=0;
|
||||
uint8_t slot=0,rewardCount=0;
|
||||
Offer offers[27],nextOffers[27];
|
||||
Reward rewards[10];
|
||||
Request() { std::memset(this,0,sizeof(*this));version=1; }
|
||||
};
|
||||
struct Reply { uint32_t account,player;uint8_t ok;char message[240]; };
|
||||
static_assert(sizeof(Offer)==13 && sizeof(Reward)==116,"stable item/offer records");
|
||||
static_assert(sizeof(Request)==1976 && sizeof(Reply)==252,"stable internal request/reply layout");
|
||||
static_assert(sizeof(Request)<8192,"bounded durable request");
|
||||
inline bool Token(const char* s) {
|
||||
if(s[32])return false;
|
||||
for(unsigned i=0;i<32;++i)if(!((s[i]>='0'&&s[i]<='9')||(s[i]>='a'&&s[i]<='f')))return false;
|
||||
return true;
|
||||
}
|
||||
inline bool Offers(const Offer* offers) {
|
||||
for(unsigned i=0;i<27;++i) {
|
||||
const auto& o=offers[i];
|
||||
if(!o.vnum || !o.count || o.count>2000 || o.price<1 || o.price>1000000 || o.bought>1)return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
inline bool Valid(const Request& r) {
|
||||
if(r.version!=1 || !r.player || !r.account || !Token(r.token) || r.operation<List || r.operation>UiStatus ||
|
||||
r.expectedGold<0 || r.expectedGold>GoldLimit || r.expectedGem<0 || r.expectedGem>1000000 ||
|
||||
r.expectedOpen<0 || r.expectedOpen>18 || r.rewardCount>10)return false;
|
||||
if(r.operation==UiStatus && (r.reference>1000000 || r.slot>2 || !r.generation || r.generation>UINT32_MAX))return false;
|
||||
if(r.operation==Status && r.reference>1000000)return false;
|
||||
if(r.operation!=GayaBuy && r.rewardCount)return false;
|
||||
if(r.operation==List && (!r.item || !r.itemVnum || !r.itemCount || r.price<1 || r.price>GoldLimit))return false;
|
||||
if((r.operation==Buy || r.operation==Refund || r.operation==Claim || r.operation==Cancel) && !r.reference)return false;
|
||||
if(r.operation==GayaBuy && (r.slot>=27 || !Offers(r.offers) || !r.rewardCount))return false;
|
||||
if(r.operation==GayaRefresh && (!Offers(r.nextOffers) || r.nextDeadline<=0 || (r.item && !r.itemCount)))return false;
|
||||
if(r.operation==GayaExpand && (!r.item || !r.itemCount || r.expectedOpen>=18))return false;
|
||||
for(unsigned i=0;i<r.rewardCount;++i) {
|
||||
if(!r.rewards[i].id || !r.rewards[i].vnum || !r.rewards[i].count || r.rewards[i].count>2000)return false;
|
||||
for(unsigned j=0;j<i;++j)if(r.rewards[j].id==r.rewards[i].id)return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
inline std::string Hex(const void* data,size_t size) {
|
||||
const auto* p=static_cast<const unsigned char*>(data);static const char hex[]="0123456789abcdef";
|
||||
std::string out;out.reserve(size*2);
|
||||
for(size_t i=0;i<size;++i){out+=hex[p[i]>>4];out+=hex[p[i]&15];}return out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
#pragma once
|
||||
#include "economy_store.h"
|
||||
#include <mysql/mysql.h>
|
||||
#include <mysql/errmsg.h>
|
||||
|
||||
namespace PortEconomy {
|
||||
// Use only on the DB main thread's direct connection. Automatic reconnection
|
||||
// remains off for the entire lifetime, including ambiguous COMMIT recovery.
|
||||
class Mysql {
|
||||
MYSQL* connection;
|
||||
bool active=false;
|
||||
bool pinned=false;
|
||||
unsigned previousTimeout=0;
|
||||
unsigned long thread=0;
|
||||
public:
|
||||
uint64_t affected=0,inserted=0,warnings=0;
|
||||
std::function<void(const std::string&)> afterStatement;
|
||||
explicit Mysql(MYSQL* handle):connection(handle) {
|
||||
// Reconnect only BEFORE entering the pinned transaction scope. Without
|
||||
// this step a dead direct handle could keep pending orders retrying
|
||||
// forever when no unrelated legacy query happens to reconnect it.
|
||||
my_bool allowReconnect=true;
|
||||
if(mysql_options(connection,MYSQL_OPT_RECONNECT,&allowReconnect)!=0 || mysql_ping(connection)!=0)return;
|
||||
my_bool reconnect=false;pinned=mysql_options(connection,MYSQL_OPT_RECONNECT,&reconnect)==0;
|
||||
thread=mysql_thread_id(connection);
|
||||
Rows rows;uint64_t value=0;
|
||||
if(Query("SELECT @@session.innodb_lock_wait_timeout",rows)&&rows.size()==1&&Number(rows[0][0],value,UINT32_MAX))previousTimeout=static_cast<unsigned>(value);
|
||||
}
|
||||
~Mysql(){Rollback();if(previousTimeout){Rows rows;Query("SET SESSION innodb_lock_wait_timeout="+std::to_string(previousTimeout),rows);}my_bool reconnect=true;mysql_options(connection,MYSQL_OPT_RECONNECT,&reconnect);}
|
||||
bool Query(const std::string& sql,Rows& rows) {
|
||||
rows.clear();affected=0;inserted=0;warnings=0;
|
||||
if(!pinned || mysql_thread_id(connection)!=thread || mysql_real_query(connection,sql.data(),static_cast<unsigned long>(sql.size())))return false;
|
||||
MYSQL_RES* result=mysql_store_result(connection);
|
||||
if(result) {
|
||||
MYSQL_ROW row;const unsigned fields=mysql_num_fields(result);
|
||||
while((row=mysql_fetch_row(result))) {
|
||||
const unsigned long* lengths=mysql_fetch_lengths(result);std::vector<std::string> values;
|
||||
for(unsigned i=0;i<fields;++i)values.emplace_back(row[i]?std::string(row[i],lengths[i]):std::string());
|
||||
rows.push_back(std::move(values));
|
||||
}
|
||||
const bool ok=mysql_errno(connection)==0;mysql_free_result(result);if(!ok)return false;
|
||||
} else if(mysql_field_count(connection))return false;
|
||||
affected=mysql_affected_rows(connection);inserted=mysql_insert_id(connection);warnings=mysql_warning_count(connection);
|
||||
if(afterStatement)afterStatement(sql);
|
||||
return mysql_thread_id(connection)==thread;
|
||||
}
|
||||
bool Begin(){Rows rows;if(active||!previousTimeout||!Query("SET SESSION innodb_lock_wait_timeout=3",rows)||!Query("START TRANSACTION",rows))return false;active=true;return true;}
|
||||
bool Commit(){Rows rows;if(!active||!Query("COMMIT",rows))return false;active=false;return true;}
|
||||
void Rollback(){if(active){Rows rows;Query("ROLLBACK",rows);active=false;}}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
#pragma once
|
||||
#include "economy.h"
|
||||
#include <array>
|
||||
#include <functional>
|
||||
#include <limits>
|
||||
#include <vector>
|
||||
|
||||
namespace PortEconomy {
|
||||
using Rows=std::vector<std::vector<std::string>>;
|
||||
inline bool Number(const std::string& s,uint64_t& out,uint64_t max=UINT64_MAX) {
|
||||
if(s.empty())return false;uint64_t n=0;
|
||||
for(char c:s){if(c<'0'||c>'9'||uint64_t(c-'0')>max||n>(max-uint64_t(c-'0'))/10)return false;n=n*10+uint64_t(c-'0');}
|
||||
out=n;return true;
|
||||
}
|
||||
// DB must supply Query(sql, rows), affected and inserted, plus Begin/Commit/Rollback.
|
||||
// This store NEVER runs against an online character or an undrained cache. The
|
||||
// DB coordinator owns that fence; game processes never execute these mutations.
|
||||
template<class DB> class Store {
|
||||
DB& db;
|
||||
std::function<unsigned(uint32_t)> size;
|
||||
std::string outcome;
|
||||
uint64_t reference=0;
|
||||
bool sqlOK=true;
|
||||
static std::string N(uint64_t n){return std::to_string(n);}
|
||||
bool Q(const std::string& sql,Rows& rows){if(!sqlOK)return false;sqlOK=db.Query(sql,rows);return sqlOK;}
|
||||
bool Run(const std::string& sql){Rows rows;return Q(sql,rows);}
|
||||
bool One(const std::string& sql,Rows& rows){return Q(sql,rows)&&rows.size()==1;}
|
||||
bool Change(const std::string& sql){return Run(sql)&&db.affected==1;}
|
||||
bool Reject(const char* why){outcome=why;return false;}
|
||||
bool Quest(uint32_t pid,const char* state,uint64_t& value) {
|
||||
Rows rows;if(!Q("SELECT lValue FROM quest WHERE dwPID="+N(pid)+" AND szName='gem' AND szState='"+state+"' FOR UPDATE",rows))return false;
|
||||
value=0;return rows.empty()||(rows.size()==1&&Number(rows[0][0],value,INT32_MAX));
|
||||
}
|
||||
bool SetQuest(uint32_t pid,const char* state,uint64_t value){
|
||||
return Run("INSERT INTO quest(dwPID,szName,szState,lValue) VALUES("+N(pid)+",'gem','"+state+"',"+N(value)+") ON DUPLICATE KEY UPDATE lValue=VALUES(lValue)");
|
||||
}
|
||||
bool Catalog(const Request& r,Offer* offers,uint64_t& generation,int32_t& deadline) {
|
||||
Rows rows;if(!Q("SELECT generation,deadline,offers FROM port_economy_gaya WHERE pid="+N(r.player)+" FOR UPDATE",rows))return false;
|
||||
if(rows.empty()) {
|
||||
if(r.generation || !Offers(r.offers) || r.deadline<0)return Reject("catalog_changed");
|
||||
std::memcpy(offers,r.offers,sizeof(r.offers));generation=0;deadline=r.deadline;return true;
|
||||
}
|
||||
uint64_t time=0;
|
||||
if(rows.size()!=1 || !Number(rows[0][0],generation) || !Number(rows[0][1],time,INT32_MAX) || rows[0][2].size()!=sizeof(r.offers))return Reject("catalog_corrupt");
|
||||
std::memcpy(offers,rows[0][2].data(),sizeof(r.offers));deadline=static_cast<int32_t>(time);
|
||||
if(!Offers(offers) || generation!=r.generation || deadline!=r.deadline || std::memcmp(offers,r.offers,sizeof(r.offers)))return Reject("catalog_changed");
|
||||
return true;
|
||||
}
|
||||
bool SaveCatalog(uint32_t pid,const Offer* offers,uint64_t generation,int32_t deadline) {
|
||||
if(generation>=RetiredGeneration-1 || !Offers(offers) || deadline<0)return Reject("catalog_corrupt");
|
||||
return Run("INSERT INTO port_economy_gaya(pid,generation,deadline,offers) VALUES("+N(pid)+","+N(generation+1)+","+N(static_cast<uint32_t>(deadline))+",X'"+Hex(offers,27*sizeof(Offer))+"') ON DUPLICATE KEY UPDATE generation=VALUES(generation),deadline=VALUES(deadline),offers=VALUES(offers)");
|
||||
}
|
||||
// Mall uses a 5x9 grid per page, three pages. Retain original item IDs and
|
||||
// every stored item column. Unknown sizes and malformed grids fail closed.
|
||||
bool MallCell(uint32_t account,uint32_t vnum,unsigned& cell) {
|
||||
const unsigned height=size(vnum);if(height<1 || height>3)return Reject("item_proto");
|
||||
std::array<bool,135> used={};Rows rows;
|
||||
if(!Q("SELECT pos,vnum FROM item WHERE owner_id="+N(account)+" AND window='MALL' FOR UPDATE",rows))return false;
|
||||
for(const auto& row:rows) {
|
||||
uint64_t pos=0,id=0;if(!Number(row[0],pos,134)||!Number(row[1],id,UINT32_MAX))return Reject("mall_corrupt");
|
||||
const unsigned h=size(static_cast<uint32_t>(id));if(h<1 || h>3 || (pos%45)/5+h>9)return Reject("mall_corrupt");
|
||||
for(unsigned j=0;j<h;++j){const size_t at=static_cast<size_t>(pos)+5*j;if(used[at])return Reject("mall_corrupt");used[at]=true;}
|
||||
}
|
||||
for(unsigned pos=0;pos<135;++pos) {
|
||||
if((pos%45)/5+height>9)continue;bool free=true;
|
||||
for(unsigned j=0;j<height;++j)if(used[pos+5*j])free=false;
|
||||
if(free){cell=pos;return true;}
|
||||
}
|
||||
return Reject("mall_full");
|
||||
}
|
||||
bool Deliver(uint32_t item,uint32_t account,uint32_t vnum) {
|
||||
unsigned cell=0;if(!MallCell(account,vnum,cell))return false;
|
||||
// Copy all columns by ordinal: readiness checks exact custody/item schema.
|
||||
if(!Change("INSERT INTO item SELECT * FROM port_economy_custody WHERE id="+N(item)))return false;
|
||||
return Change("UPDATE item SET owner_id="+N(account)+",window='MALL',pos="+N(cell)+" WHERE id="+N(item))&&
|
||||
Change("DELETE FROM port_economy_custody WHERE id="+N(item));
|
||||
}
|
||||
bool Consume(const Request& r,uint32_t vnum) {
|
||||
Rows rows;uint64_t count=0;
|
||||
if(!One("SELECT count FROM item WHERE id="+N(r.item)+" AND owner_id="+N(r.player)+" AND window='INVENTORY' AND pos<225 AND vnum="+N(vnum)+" FOR UPDATE",rows)||!Number(rows[0][0],count,2000)||!count||count!=r.itemCount)return Reject("consumable_changed");
|
||||
if(count==1)return Change("DELETE FROM item WHERE id="+N(r.item));
|
||||
return Change("UPDATE item SET count=count-1 WHERE id="+N(r.item));
|
||||
}
|
||||
bool Apply(const Request& r,uint64_t gold) {
|
||||
const std::string pid=N(r.player),aid=N(r.account);
|
||||
Rows rows;uint64_t a=0,b=0,c=0,d=0;
|
||||
switch(r.operation) {
|
||||
case List:
|
||||
if(!One("SELECT id FROM item WHERE id="+N(r.item)+" AND owner_id="+pid+" AND window='INVENTORY' AND vnum="+N(r.itemVnum)+" AND count="+N(r.itemCount)+" AND pos<225 FOR UPDATE",rows))return Reject("item_changed");
|
||||
if(!Change("INSERT INTO port_economy_custody SELECT * FROM item WHERE id="+N(r.item))||!Change("DELETE FROM item WHERE id="+N(r.item)))return false;
|
||||
if(!Change("INSERT INTO port_economy_listings(owner,account,item,price,state) VALUES("+pid+","+aid+","+N(r.item)+","+N(static_cast<uint64_t>(r.price))+",'OPEN')"))return false;
|
||||
reference=db.inserted;return reference!=0;
|
||||
case Buy:
|
||||
if(!One("SELECT owner,item,price,state FROM port_economy_listings WHERE id="+N(r.reference)+" FOR UPDATE",rows)||
|
||||
!Number(rows[0][0],a,UINT32_MAX)||!Number(rows[0][1],b,UINT32_MAX)||!Number(rows[0][2],c,GoldLimit)||rows[0][3]!="OPEN"||a==r.player||!c||c>gold||r.price!=static_cast<int64_t>(c))return Reject("listing_changed");
|
||||
if(!Change("UPDATE player SET gold=gold-"+N(c)+" WHERE id="+pid+" AND gold>="+N(c))||
|
||||
!Change("INSERT INTO port_economy_orders(request,listing,buyer,account,price,state) VALUES('"+std::string(r.token)+"',"+N(r.reference)+","+pid+","+aid+","+N(c)+",'READY')"))return false;
|
||||
reference=db.inserted;
|
||||
return Change("UPDATE port_economy_listings SET state='RESERVED',active_order="+N(reference)+" WHERE id="+N(r.reference));
|
||||
case Refund: case Claim:
|
||||
if(!One("SELECT listing,price,state FROM port_economy_orders WHERE id="+N(r.reference)+" AND buyer="+pid+" AND account="+aid+" FOR UPDATE",rows)||
|
||||
!Number(rows[0][0],a)||!Number(rows[0][1],b,GoldLimit))return Reject("order_missing");
|
||||
if(rows[0][2]==(r.operation==Claim?"CLAIMED":"REFUNDED")){reference=r.reference;return true;}
|
||||
if(rows[0][2]!="READY")return Reject("order_terminal");
|
||||
if(!One("SELECT owner,item,active_order FROM port_economy_listings WHERE id="+N(a)+" AND state='RESERVED' FOR UPDATE",rows)||
|
||||
!Number(rows[0][0],c,UINT32_MAX)||!Number(rows[0][1],d,UINT32_MAX)||rows[0][2]!=N(r.reference))return Reject("custody_changed");
|
||||
if(r.operation==Refund) {
|
||||
if(gold>uint64_t(GoldLimit)-b)return Reject("gold_limit");
|
||||
if(!Change("UPDATE player SET gold=gold+"+N(b)+" WHERE id="+pid)||!Change("UPDATE port_economy_listings SET state='OPEN',active_order=0 WHERE id="+N(a)))return false;
|
||||
} else {
|
||||
if(!One("SELECT vnum FROM port_economy_custody WHERE id="+N(d)+" FOR UPDATE",rows))return Reject("custody_missing");
|
||||
uint64_t vnum=0;if(!Number(rows[0][0],vnum,UINT32_MAX)||!Deliver(static_cast<uint32_t>(d),r.account,static_cast<uint32_t>(vnum)))return false;
|
||||
if(!Run("INSERT INTO port_economy_credit(pid,amount) VALUES("+N(c)+",0) ON DUPLICATE KEY UPDATE pid=VALUES(pid)")||
|
||||
!One("SELECT amount FROM port_economy_credit WHERE pid="+N(c)+" FOR UPDATE",rows)||!Number(rows[0][0],c,GoldLimit)||c>uint64_t(GoldLimit)-b)return Reject("seller_credit_limit");
|
||||
// Owner was decoded above; use the immutable listing relationship.
|
||||
if(!Change("UPDATE port_economy_credit SET amount=amount+"+N(b)+" WHERE pid=(SELECT owner FROM port_economy_listings WHERE id="+N(a)+")")||
|
||||
!Change("UPDATE port_economy_listings SET state='SOLD' WHERE id="+N(a)))return false;
|
||||
}
|
||||
reference=r.reference;
|
||||
return Change("UPDATE port_economy_orders SET state='"+std::string(r.operation==Claim?"CLAIMED":"REFUNDED")+"' WHERE id="+N(r.reference));
|
||||
case Cancel:
|
||||
if(!One("SELECT item FROM port_economy_listings WHERE id="+N(r.reference)+" AND owner="+pid+" AND state='OPEN' FOR UPDATE",rows)||!Number(rows[0][0],a,UINT32_MAX))return Reject("listing_changed");
|
||||
if(!One("SELECT vnum FROM port_economy_custody WHERE id="+N(a)+" FOR UPDATE",rows)||!Number(rows[0][0],b,UINT32_MAX)||!Deliver(static_cast<uint32_t>(a),r.account,static_cast<uint32_t>(b)))return false;
|
||||
reference=r.reference;return Change("UPDATE port_economy_listings SET state='CANCELLED' WHERE id="+N(r.reference));
|
||||
case Withdraw:
|
||||
if(!One("SELECT amount FROM port_economy_credit WHERE pid="+pid+" FOR UPDATE",rows)||!Number(rows[0][0],a,GoldLimit)||!a)return Reject("no_credit");
|
||||
if(gold>uint64_t(GoldLimit)-a)return Reject("gold_limit");
|
||||
return Change("UPDATE player SET gold=gold+"+N(a)+" WHERE id="+pid)&&Change("UPDATE port_economy_credit SET amount=0 WHERE pid="+pid);
|
||||
case GayaRetire: {
|
||||
// Explicit retirement never destroys a positive wallet, custody,
|
||||
// refundable order or seller credit. Keep offers/deadline for audit.
|
||||
if(!Quest(r.player,"points",a)||!Quest(r.player,"open_slot",b)||
|
||||
a!=static_cast<uint64_t>(r.expectedGem)||b!=static_cast<uint64_t>(r.expectedOpen))return Reject("wallet_changed");
|
||||
if(a)return Reject("gaya_balance_remaining");
|
||||
if(!One("SELECT (EXISTS(SELECT 1 FROM port_economy_listings WHERE owner="+pid+" AND state IN('OPEN','RESERVED')))+(EXISTS(SELECT 1 FROM port_economy_orders WHERE buyer="+pid+" AND state='READY'))+(EXISTS(SELECT 1 FROM port_economy_credit WHERE pid="+pid+" AND amount<>0))",rows)||rows[0][0]!="0")return Reject("assets_remaining");
|
||||
if(!One("SELECT generation,deadline,offers FROM port_economy_gaya WHERE pid="+pid+" FOR UPDATE",rows)||
|
||||
!Number(rows[0][0],c,RetiredGeneration)||rows[0][2].size()!=sizeof(r.offers))return Reject("catalog_corrupt");
|
||||
Offer retained[27];std::memcpy(retained,rows[0][2].data(),sizeof(retained));
|
||||
if(!Offers(retained))return Reject("catalog_corrupt");
|
||||
reference=c;
|
||||
if(c==RetiredGeneration)return true;
|
||||
return Change("UPDATE port_economy_gaya SET generation="+N(RetiredGeneration)+" WHERE pid="+pid);
|
||||
}
|
||||
case GayaBuy: case GayaRefresh: case GayaExpand: {
|
||||
if(!Q("SELECT generation FROM port_economy_gaya WHERE pid="+pid+" FOR UPDATE",rows))return false;
|
||||
if(!rows.empty()&&(!Number(rows[0][0],a,RetiredGeneration)||a==RetiredGeneration))return Reject("gaya_retired");
|
||||
uint64_t gem=0,open=0,generation=0;int32_t deadline=0;Offer offers[27];
|
||||
if(!Quest(r.player,"points",gem)||!Quest(r.player,"open_slot",open)||gem!=static_cast<uint64_t>(r.expectedGem)||open!=static_cast<uint64_t>(r.expectedOpen))return Reject("wallet_changed");
|
||||
if(r.operation==GayaExpand) {
|
||||
if(open>=18||!Consume(r,39064))return Reject("consumable_changed");
|
||||
return SetQuest(r.player,"open_slot",open+1);
|
||||
}
|
||||
if(!Catalog(r,offers,generation,deadline))return false;
|
||||
if(r.operation==GayaRefresh) {
|
||||
if(r.nextDeadline<deadline || (!r.item && r.nextDeadline==deadline))return Reject("refresh_changed");
|
||||
if(r.item) {if(!Consume(r,39063))return false;}
|
||||
else {if(!One("SELECT UNIX_TIMESTAMP()",rows)||!Number(rows[0][0],a)||uint64_t(deadline)>a)return Reject("refresh_early");}
|
||||
for(const auto& offer:r.nextOffers)if(offer.bought)return Reject("catalog_changed");
|
||||
return SaveCatalog(r.player,r.nextOffers,generation,r.nextDeadline)&&SetQuest(r.player,"left_time",static_cast<uint32_t>(r.nextDeadline));
|
||||
}
|
||||
auto& offer=offers[r.slot];
|
||||
if(offer.bought|| (r.slot>=9 && open<uint64_t(r.slot-8)) || gem<static_cast<uint32_t>(offer.price))return Reject("offer_unavailable");
|
||||
uint64_t total=0;
|
||||
for(unsigned i=0;i<r.rewardCount;++i) {
|
||||
const auto& reward=r.rewards[i];if(reward.vnum!=offer.vnum)return Reject("reward_changed");total+=reward.count;
|
||||
unsigned cell=0;if(!MallCell(r.account,reward.vnum,cell))return false;
|
||||
std::string columns="id,owner_id,window,pos,count,vnum",values=N(reward.id)+","+aid+",'MALL',"+N(cell)+","+N(reward.count)+","+N(reward.vnum);
|
||||
for(unsigned j=0;j<3;++j){columns+=",socket"+N(j);values+=","+std::to_string(reward.sockets[j]);}
|
||||
for(unsigned j=0;j<7;++j){columns+=",attrtype"+N(j)+",attrvalue"+N(j);values+=","+N(reward.types[j])+","+std::to_string(reward.values[j]);}
|
||||
columns+=",port_extra";values+=",X'"+Hex(reward.extra,sizeof(reward.extra))+"'";
|
||||
if(!Change("INSERT INTO item("+columns+") VALUES("+values+")"))return false;
|
||||
}
|
||||
if(total!=offer.count)return Reject("reward_changed");
|
||||
offer.bought=1;
|
||||
return SetQuest(r.player,"points",gem-static_cast<uint32_t>(offer.price))&&SaveCatalog(r.player,offers,generation,deadline);
|
||||
}
|
||||
default:return Reject("invalid_operation");
|
||||
}
|
||||
}
|
||||
public:
|
||||
Store(DB& database,std::function<unsigned(uint32_t)> itemSize):db(database),size(itemSize){}
|
||||
// Readiness is checked on every entry, so a missing/nontransactional table
|
||||
// never silently downgrades a payment to autocommit.
|
||||
bool Ready() {
|
||||
Rows rows;sqlOK=true;
|
||||
if(!One("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND ENGINE='InnoDB' AND TABLE_NAME IN ('player','item','quest','port_economy_custody','port_economy_requests','port_economy_pending','port_economy_listings','port_economy_orders','port_economy_credit','port_economy_gaya','port_economy_version','port_economy_account_lock','port_economy_item_reservations')",rows)||rows[0][0]!="13")return false;
|
||||
if(!One("SELECT version FROM port_economy_version WHERE id=1",rows)||rows[0][0]!="1")return false;
|
||||
Rows item,custody;
|
||||
return Q("SHOW COLUMNS FROM item",item)&&Q("SHOW COLUMNS FROM port_economy_custody",custody)&&item==custody;
|
||||
}
|
||||
bool Enqueue(const Request& r) {
|
||||
if(!Valid(r)||(r.operation==Status||r.operation==UiStatus)||!Ready()||!db.Begin())return false;
|
||||
Rows rows;bool success=false;
|
||||
const std::string token=r.token,body=Hex(&r,sizeof(r));
|
||||
if(Q("SELECT account,pid,body FROM port_economy_requests WHERE token='"+token+"' FOR UPDATE",rows)) {
|
||||
if(!rows.empty())success=rows.size()==1&&rows[0][0]==N(r.account)&&rows[0][1]==N(r.player)&&rows[0][2].size()==sizeof(r)&&!std::memcmp(rows[0][2].data(),&r,sizeof(r));
|
||||
else {
|
||||
success=true;
|
||||
for(unsigned i=0;i<r.rewardCount && success;++i) {
|
||||
Rows existing;
|
||||
success=Q("SELECT id FROM item WHERE id="+N(r.rewards[i].id)+" UNION ALL SELECT id FROM port_economy_custody WHERE id="+N(r.rewards[i].id),existing)&&existing.empty()&&
|
||||
Change("INSERT INTO port_economy_item_reservations(id,request) VALUES("+N(r.rewards[i].id)+",'"+token+"')");
|
||||
}
|
||||
success=success&&Change("INSERT INTO port_economy_pending(pid,token) VALUES("+N(r.player)+",'"+token+"')")&&
|
||||
Change("INSERT INTO port_economy_requests(token,account,pid,body,state,result,reference) VALUES('"+token+"',"+N(r.account)+","+N(r.player)+",X'"+body+"','PENDING','queued',0)");
|
||||
}
|
||||
}
|
||||
if(success&&db.Commit())return true;db.Rollback();return false;
|
||||
}
|
||||
enum Result { Retry, None, Settled };
|
||||
bool Abort(uint32_t pid,uint32_t account) {
|
||||
if(!Ready()||!db.Begin())return false;
|
||||
Rows rows;
|
||||
bool done=One("SELECT r.token FROM port_economy_pending p JOIN port_economy_requests r ON r.token=p.token WHERE p.pid="+N(pid)+" AND r.pid="+N(pid)+" AND r.account="+N(account)+" AND r.state='PENDING' FOR UPDATE",rows)&&
|
||||
Change("UPDATE port_economy_requests SET state='DONE',result='save_failed' WHERE pid="+N(pid)+" AND account="+N(account)+" AND state='PENDING'")&&
|
||||
Run("DELETE FROM port_economy_pending WHERE pid="+N(pid));
|
||||
if(done&&db.Commit())return true;db.Rollback();return false;
|
||||
}
|
||||
Result Settle(uint32_t pid,uint32_t account) {
|
||||
if(!Ready()||!db.Begin())return Retry;
|
||||
Rows rows;Request r;uint64_t gold=0;
|
||||
if(!Q("SELECT token FROM port_economy_pending WHERE pid="+N(pid)+" FOR UPDATE",rows)){db.Rollback();return Retry;}
|
||||
if(rows.empty()){db.Rollback();return None;}
|
||||
const std::string token=rows[0][0];
|
||||
if(!One("SELECT body FROM port_economy_requests WHERE token='"+token+"' AND account="+N(account)+" AND pid="+N(pid)+" AND state='PENDING' FOR UPDATE",rows)||rows[0][0].size()!=sizeof(r)){db.Rollback();return Retry;}
|
||||
std::memcpy(&r,rows[0][0].data(),sizeof(r));
|
||||
if(!Valid(r)||r.player!=pid||r.account!=account||std::string(r.token)!=token){db.Rollback();return Retry;}
|
||||
if(!Run("INSERT INTO port_economy_account_lock(account) VALUES("+N(account)+") ON DUPLICATE KEY UPDATE account=VALUES(account)")||!One("SELECT account FROM port_economy_account_lock WHERE account="+N(account)+" FOR UPDATE",rows)){db.Rollback();return Retry;}
|
||||
if(!One("SELECT gold FROM player WHERE id="+N(pid)+" AND account_id="+N(account)+" FOR UPDATE",rows)||!Number(rows[0][0],gold,GoldLimit)){db.Rollback();return Retry;}
|
||||
// A save lost before logout cannot authorize spending an older snapshot.
|
||||
outcome="ok";reference=0;
|
||||
if(gold!=static_cast<uint64_t>(r.expectedGold))outcome="wallet_changed";
|
||||
else {
|
||||
// Validation failures may happen after tentative writes (e.g. mall
|
||||
// fills midway through a multi-stack reward). Roll back to savepoint.
|
||||
if(!Run("SAVEPOINT economy_operation")){db.Rollback();return Retry;}
|
||||
if(!Apply(r,gold)) {
|
||||
if(!sqlOK){db.Rollback();return Retry;}
|
||||
if(!Run("ROLLBACK TO SAVEPOINT economy_operation")){db.Rollback();return Retry;}
|
||||
if(outcome=="ok")outcome="state_changed";reference=0;
|
||||
}
|
||||
}
|
||||
if(!Change("UPDATE port_economy_requests SET state='DONE',result='"+outcome+"',reference="+N(reference)+" WHERE token='"+token+"'")||
|
||||
!Change("DELETE FROM port_economy_pending WHERE pid="+N(pid))||!db.Commit()){db.Rollback();return Retry;}
|
||||
return Settled;
|
||||
}
|
||||
const std::string& Outcome()const{return outcome;}
|
||||
uint64_t Reference()const{return reference;}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
#pragma once
|
||||
#include "economy_store.h"
|
||||
|
||||
namespace PortEconomy {
|
||||
// Bounded, ASCII-only presentation over the existing authenticated DB reply.
|
||||
// Build the complete snapshot before emitting any frames. No UI read mutates
|
||||
// wallets, item ownership or order state, and no display slot is an asset ID.
|
||||
constexpr unsigned ViewPageSize=20;
|
||||
inline bool SignedNumber(const std::string& text,int64_t& out,int64_t minimum,int64_t maximum) {
|
||||
const bool negative=!text.empty()&&text[0]=='-';uint64_t value=0;
|
||||
if(!Number(negative?text.substr(1):text,value,negative?static_cast<uint64_t>(-minimum):static_cast<uint64_t>(maximum)))return false;
|
||||
out=negative?-static_cast<int64_t>(value):static_cast<int64_t>(value);return out>=minimum&&out<=maximum;
|
||||
}
|
||||
inline bool HexBytes(const std::string& text,size_t bytes) {
|
||||
if(text.size()!=bytes*2)return false;
|
||||
for(char c:text)if(!((c>='0'&&c<='9')||(c>='a'&&c<='f')||(c>='A'&&c<='F')))return false;
|
||||
return true;
|
||||
}
|
||||
template<class DB> bool View(DB& db,const Request& r,std::function<unsigned(uint32_t)> height,std::vector<std::string>& frames) {
|
||||
frames.clear();Rows rows;if(!Valid(r)||r.operation!=UiStatus)return false;
|
||||
// Transaction-scoped isolation applies to this read only, not later wallet
|
||||
// settlements on the shared direct connection.
|
||||
if(!db.Query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ",rows)||!db.Begin())return false;
|
||||
auto fail=[&](){db.Rollback();frames.clear();return false;};
|
||||
const auto pid=std::to_string(r.player),aid=std::to_string(r.account),seq=std::to_string(r.generation);
|
||||
if(!db.Query("SELECT amount FROM port_economy_credit WHERE pid="+pid,rows)||rows.size()>1)return fail();
|
||||
uint64_t credit=0;if(!rows.empty()&&!Number(rows[0][0],credit,GoldLimit))return fail();
|
||||
std::string columns="c.vnum,c.count,"+std::string(r.slot==2?"o.state":"l.state")+",c.socket0,c.socket1,c.socket2";
|
||||
for(unsigned i=0;i<7;++i)columns+=",c.attrtype"+std::to_string(i)+",c.attrvalue"+std::to_string(i);
|
||||
columns+=",HEX(c.port_extra)";
|
||||
std::string sql=r.slot==2 ? "SELECT o.id,o.price,l.owner,"+columns+" FROM port_economy_orders o JOIN port_economy_listings l ON l.id=o.listing LEFT JOIN port_economy_custody c ON c.id=l.item WHERE o.buyer="+pid+" AND o.account="+aid+" AND o.state='READY'" :
|
||||
"SELECT l.id,l.price,l.owner,"+columns+" FROM port_economy_listings l LEFT JOIN port_economy_custody c ON c.id=l.item WHERE "+
|
||||
(r.slot==1?"l.owner="+pid+" AND l.state IN('OPEN','RESERVED')":std::string("l.state='OPEN'")+(r.item?" AND l.owner="+std::to_string(r.item):""));
|
||||
sql+=" ORDER BY "+std::string(r.slot==2?"o.id":"l.id")+" DESC LIMIT 21 OFFSET "+std::to_string(r.reference*ViewPageSize);
|
||||
if(!db.Query(sql,rows)||rows.size()>ViewPageSize+1)return fail();
|
||||
const bool more=rows.size()>ViewPageSize;if(more)rows.pop_back();
|
||||
frames.push_back("MTECON1 begin "+seq+" "+std::to_string(r.slot)+" "+std::to_string(r.reference)+" "+std::to_string(rows.size())+" "+std::to_string(more)+" "+std::to_string(credit));
|
||||
for(size_t index=0;index<rows.size();++index) {
|
||||
const auto& row=rows[index];if(row.size()!=24)return fail();
|
||||
uint64_t id=0,price=0,owner=0,vnum=0,count=0;
|
||||
if(!Number(row[0],id)||!id||!Number(row[1],price,GoldLimit)||!price||!Number(row[2],owner,UINT32_MAX)||!owner||
|
||||
!Number(row[3],vnum,UINT32_MAX)||!vnum||!Number(row[4],count,2000)||!count)return fail();
|
||||
unsigned state=row[5]=="OPEN"?0:row[5]=="RESERVED"?1:row[5]=="READY"?2:3;
|
||||
const unsigned size=height(static_cast<uint32_t>(vnum));if(state==3||size<1||size>3)return fail();
|
||||
std::string item="MTECON1 row "+seq+" "+std::to_string(index)+" "+std::to_string(id)+" "+std::to_string(price)+" "+std::to_string(owner)+" "+std::to_string(state)+" "+std::to_string(vnum)+" "+std::to_string(count)+" "+std::to_string(size);
|
||||
for(unsigned i=6;i<9;++i){int64_t socket=0;if(!SignedNumber(row[i],socket,INT32_MIN,INT32_MAX))return fail();item+=" "+std::to_string(socket);}
|
||||
frames.push_back(item);
|
||||
uint8_t attrs[21]={};
|
||||
for(unsigned i=0;i<7;++i){uint64_t type=0;int64_t value=0;
|
||||
if(!Number(row[9+2*i],type,UINT8_MAX)||!SignedNumber(row[10+2*i],value,INT16_MIN,INT16_MAX))return fail();
|
||||
const auto bits=static_cast<uint16_t>(value);attrs[3*i]=static_cast<uint8_t>(type);attrs[3*i+1]=static_cast<uint8_t>(bits&255);attrs[3*i+2]=static_cast<uint8_t>(bits>>8);
|
||||
}
|
||||
std::string extra=row[23];if(extra.empty())extra=std::string(138,'0');if(!HexBytes(extra,69))return fail();
|
||||
frames.push_back("MTECON1 meta "+seq+" "+std::to_string(index)+" "+Hex(attrs,sizeof(attrs))+extra);
|
||||
}
|
||||
// A supplied receipt is scoped to the current account/player. On a fresh
|
||||
// process the latest result is informational; actionable assets come from
|
||||
// the authoritative orders/listings/credit views above.
|
||||
if(!db.Query("SELECT state,result,reference FROM port_economy_requests WHERE pid="+pid+" AND account="+aid+
|
||||
(std::string(r.token)==std::string(32,'0')?" ORDER BY created_at DESC,token DESC LIMIT 1":" AND token='"+std::string(r.token)+"'"),rows)||rows.size()>1)return fail();
|
||||
if(!rows.empty()) {
|
||||
uint64_t reference=0;
|
||||
if(rows[0].size()!=3||!Number(rows[0][2],reference)||rows[0][1].size()>64||(rows[0][0]!="DONE"&&rows[0][0]!="PENDING"))return fail();
|
||||
frames.push_back("MTECON1 result "+seq+" "+rows[0][0]+" "+(rows[0][1].empty()?std::string("00"):Hex(rows[0][1].data(),rows[0][1].size()))+" "+std::to_string(reference));
|
||||
}
|
||||
frames.push_back("MTECON1 end "+seq);
|
||||
for(const auto& frame:frames)if(frame.size()>=sizeof(Reply::message))return fail();
|
||||
if(!db.Commit())return fail();return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
#pragma once
|
||||
#include <cerrno>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <fcntl.h>
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <sys/file.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
// A separate lifetime lock survives replacement of the catalogue inode. Wallet
|
||||
// and item persistence are separate: this file is not an economic transaction.
|
||||
class PortGayaCatalogFile {
|
||||
int directory_=-1, lock_=-1;
|
||||
bool healthy_=false;
|
||||
std::string name_, error_;
|
||||
bool Fail(const char* reason) { healthy_=false;error_=reason;return false; }
|
||||
static uint32_t Hash(const std::string& s) {
|
||||
uint32_t h=2166136261u;for(unsigned char c:s){h^=c;h*=16777619u;}return h;
|
||||
}
|
||||
static bool Number(const std::string& s,uint64_t maximum,uint64_t& out) {
|
||||
if(s.empty())return false;
|
||||
uint64_t n=0;
|
||||
for(char c:s){if(c<'0'||c>'9'||uint64_t(c-'0')>maximum||n>(maximum-uint64_t(c-'0'))/10)return false;n=n*10+uint64_t(c-'0');}
|
||||
out=n;return true;
|
||||
}
|
||||
template<class Item> static bool Valid(unsigned slot,const Item& item) {
|
||||
return slot<27 && item.itemVnum && item.itemCount>0 && item.itemCount<=2000 && item.itemPrice>0 && item.itemPrice<=1000000;
|
||||
}
|
||||
public:
|
||||
enum Result { Error, Missing, Loaded };
|
||||
PortGayaCatalogFile()=default;
|
||||
PortGayaCatalogFile(const PortGayaCatalogFile&)=delete;
|
||||
PortGayaCatalogFile& operator=(const PortGayaCatalogFile&)=delete;
|
||||
~PortGayaCatalogFile(){if(lock_>=0)close(lock_);if(directory_>=0)close(directory_);}
|
||||
bool Ready()const{return healthy_;}
|
||||
const std::string& ErrorText()const{return error_;}
|
||||
bool Open(const std::string& directory,uint32_t player) {
|
||||
if(directory_>=0 || !player)return Fail("invalid or already opened catalogue");
|
||||
// Only the configured data directory is created. Parent directories must exist.
|
||||
if(mkdir(directory.c_str(),0700)!=0 && errno!=EEXIST)return Fail("cannot create catalogue directory");
|
||||
directory_=open(directory.c_str(),O_RDONLY|O_DIRECTORY|O_NOFOLLOW);
|
||||
if(directory_<0)return Fail("cannot open catalogue directory");
|
||||
name_=std::to_string(player);
|
||||
lock_=openat(directory_,(name_+".lock").c_str(),O_RDWR|O_CREAT|O_NOFOLLOW,0600);
|
||||
if(lock_<0)return Fail("cannot open catalogue lock");
|
||||
struct stat info={};
|
||||
if(fstat(lock_,&info)!=0 || !S_ISREG(info.st_mode) || flock(lock_,LOCK_EX|LOCK_NB)!=0)
|
||||
return Fail("catalogue already owned or invalid lock file");
|
||||
healthy_=true;return true;
|
||||
}
|
||||
template<class Item> Result Load(std::map<uint8_t,Item>& output,int& refresh) {
|
||||
if(!healthy_)return Error;
|
||||
int fd=openat(directory_,name_.c_str(),O_RDONLY|O_NOFOLLOW);
|
||||
if(fd<0){if(errno==ENOENT){output.clear();refresh=0;return Missing;}Fail("cannot read catalogue");return Error;}
|
||||
struct stat info={};
|
||||
if(fstat(fd,&info)!=0 || !S_ISREG(info.st_mode) || info.st_size<1 || info.st_size>16384){close(fd);Fail("invalid catalogue file");return Error;}
|
||||
std::string bytes;char buf[1024];bool readOK=true;
|
||||
for(;;){ssize_t n=read(fd,buf,sizeof(buf));if(n<0&&errno==EINTR)continue;if(n<0){readOK=false;break;}if(!n)break;bytes.append(buf,size_t(n));if(bytes.size()>16384){readOK=false;break;}}
|
||||
close(fd);
|
||||
if(!readOK || bytes.empty() || bytes.back()!='\n'){Fail("truncated catalogue");return Error;}
|
||||
const auto newline=bytes.find('\n');std::string header=bytes.substr(0,newline),body=bytes.substr(newline+1);
|
||||
int decodedRefresh=0;
|
||||
if(header!="index-vnum-count-price-buyed") {
|
||||
std::istringstream fields(header);std::string version,deadline,checksum,tail;uint64_t parsed=0;
|
||||
if(!(fields>>version>>deadline>>checksum) || fields>>tail || version!="gaya-v2" || !Number(deadline,INT32_MAX,parsed) || checksum!=std::to_string(Hash(body))) {
|
||||
Fail("invalid catalogue header or checksum");return Error;
|
||||
}
|
||||
decodedRefresh=static_cast<int>(parsed);
|
||||
}
|
||||
std::map<uint8_t,Item> decoded;std::istringstream rows(body);std::string line;
|
||||
while(std::getline(rows,line)) {
|
||||
std::istringstream fields(line);std::string tokens[5],tail;uint64_t values[5]={};
|
||||
if(!(fields>>tokens[0]>>tokens[1]>>tokens[2]>>tokens[3]>>tokens[4]) || fields>>tail ||
|
||||
!Number(tokens[0],26,values[0]) || !Number(tokens[1],UINT32_MAX,values[1]) ||
|
||||
!Number(tokens[2],2000,values[2]) || !Number(tokens[3],1000000,values[3]) || !Number(tokens[4],1,values[4])) {
|
||||
Fail("invalid catalogue row");return Error;
|
||||
}
|
||||
Item item={};item.itemVnum=static_cast<uint32_t>(values[1]);item.itemCount=static_cast<uint32_t>(values[2]);item.itemPrice=static_cast<int>(values[3]);item.itemBuyed=values[4]!=0;
|
||||
if(!Valid(unsigned(values[0]),item) || !decoded.emplace(uint8_t(values[0]),item).second){Fail("invalid or duplicate catalogue slot");return Error;}
|
||||
}
|
||||
if(decoded.empty()){Fail("empty catalogue");return Error;}
|
||||
output.swap(decoded);refresh=decodedRefresh;return Loaded;
|
||||
}
|
||||
template<class Item> bool Save(const std::map<uint8_t,Item>& items,int refresh) {
|
||||
if(!healthy_)return false;
|
||||
if(items.empty() || items.size()>27 || refresh<0)return Fail("invalid catalogue snapshot");
|
||||
std::ostringstream rows;
|
||||
for(const auto& row:items){if(!Valid(row.first,row.second))return Fail("invalid catalogue snapshot row");const auto& i=row.second;rows<<unsigned(row.first)<<' '<<i.itemVnum<<' '<<i.itemCount<<' '<<i.itemPrice<<' '<<(i.itemBuyed?1:0)<<'\n';}
|
||||
const std::string body=rows.str(),bytes="gaya-v2 "+std::to_string(refresh)+" "+std::to_string(Hash(body))+"\n"+body;
|
||||
const std::string temporary=name_+".tmp."+std::to_string(getpid());
|
||||
int fd=openat(directory_,temporary.c_str(),O_WRONLY|O_CREAT|O_EXCL|O_NOFOLLOW,0600);
|
||||
if(fd<0)return Fail("cannot create catalogue snapshot");
|
||||
bool written=true;size_t offset=0;
|
||||
while(offset<bytes.size()){ssize_t n=write(fd,bytes.data()+offset,bytes.size()-offset);if(n<0&&errno==EINTR)continue;if(n<=0){written=false;break;}offset+=size_t(n);}
|
||||
if(written && fsync(fd)!=0)written=false;
|
||||
if(close(fd)!=0)written=false;
|
||||
if(!written){unlinkat(directory_,temporary.c_str(),0);return Fail("catalogue write/fsync failed; old snapshot retained");}
|
||||
if(renameat(directory_,temporary.c_str(),directory_,name_.c_str())!=0){unlinkat(directory_,temporary.c_str(),0);return Fail("catalogue replace failed; old snapshot retained");}
|
||||
if(fsync(directory_)!=0)return Fail("catalogue directory fsync failed; snapshot outcome requires reload");
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
inline bool PortGayaNextRefresh(int64_t now,int previous,bool elapsedCadence,int& next) {
|
||||
const int64_t period=5*60*60;
|
||||
if(now<0 || now>INT32_MAX-period || previous<0)return false;
|
||||
int64_t result=now+period;
|
||||
if(elapsedCadence && previous>0) {
|
||||
if(previous>now)result=previous;
|
||||
else result=int64_t(previous)+((now-previous)/period+1)*period;
|
||||
}
|
||||
if(result>INT32_MAX)return false;
|
||||
next=static_cast<int>(result);return true;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
// Compare against bounded differences: never negate caller-supplied INT64_MIN.
|
||||
inline bool PortGoldCanChange(int64_t balance,int64_t delta,int64_t maximum) {
|
||||
return maximum>=0 && balance>=0 && balance<=maximum && delta>=-balance && delta<=maximum-balance;
|
||||
}
|
||||
inline bool PortGoldTotal(int64_t price,uint32_t count,int64_t maximum,int64_t& total) {
|
||||
if(price<=0 || !count || maximum<0 || price>maximum/int64_t(count))return false;
|
||||
total=price*int64_t(count);return true;
|
||||
}
|
||||
@@ -31,8 +31,8 @@ enum EItemDragonSoulSockets
|
||||
ITEM_SOCKET_DRAGON_SOUL_ACTIVE_IDX = 2,
|
||||
ITEM_SOCKET_CHARGING_AMOUNT_IDX = 2,
|
||||
};
|
||||
// 헐 이거 미친거 아니야?
|
||||
// 나중에 소켓 확장하면 어쩌려고 이지랄 -_-;;;
|
||||
// 헐 이거 미친거 아니야?
|
||||
// 나중에 소켓 확장하면 어쩌려고 이지랄 -_-;;;
|
||||
enum EItemUniqueSockets
|
||||
{
|
||||
ITEM_SOCKET_UNIQUE_SAVE_TIME = ITEM_SOCKET_MAX_NUM - 2,
|
||||
@@ -42,18 +42,18 @@ enum EItemUniqueSockets
|
||||
enum EItemTypes
|
||||
{
|
||||
ITEM_NONE, //0
|
||||
ITEM_WEAPON, //1//무기
|
||||
ITEM_ARMOR, //2//갑옷
|
||||
ITEM_USE, //3//아이템 사용
|
||||
ITEM_WEAPON, //1//무기
|
||||
ITEM_ARMOR, //2//갑옷
|
||||
ITEM_USE, //3//아이템 사용
|
||||
ITEM_AUTOUSE, //4
|
||||
ITEM_MATERIAL, //5
|
||||
ITEM_SPECIAL, //6 //스페셜 아이템
|
||||
ITEM_SPECIAL, //6 //스페셜 아이템
|
||||
ITEM_TOOL, //7
|
||||
ITEM_LOTTERY, //8//복권
|
||||
ITEM_ELK, //9//돈
|
||||
ITEM_LOTTERY, //8//복권
|
||||
ITEM_ELK, //9//돈
|
||||
ITEM_METIN, //10
|
||||
ITEM_CONTAINER, //11
|
||||
ITEM_FISH, //12//낚시
|
||||
ITEM_FISH, //12//낚시
|
||||
ITEM_ROD, //13
|
||||
ITEM_RESOURCE, //14
|
||||
ITEM_CAMPFIRE, //15
|
||||
@@ -61,27 +61,26 @@ enum EItemTypes
|
||||
ITEM_SKILLBOOK, //17
|
||||
ITEM_QUEST, //18
|
||||
ITEM_POLYMORPH, //19
|
||||
ITEM_TREASURE_BOX, //20//보물상자
|
||||
ITEM_TREASURE_KEY, //21//보물상자 열쇠
|
||||
ITEM_TREASURE_BOX, //20//보물상자
|
||||
ITEM_TREASURE_KEY, //21//보물상자 열쇠
|
||||
ITEM_SKILLFORGET, //22
|
||||
ITEM_GIFTBOX, //23
|
||||
ITEM_PICK, //24
|
||||
ITEM_HAIR, //25//머리
|
||||
ITEM_TOTEM, //26//토템
|
||||
ITEM_BLEND, //27//생성될때 랜덤하게 속성이 붙는 약물
|
||||
ITEM_COSTUME, //28//코스츔 아이템 (2011년 8월 추가된 코스츔 시스템용 아이템)
|
||||
ITEM_DS, //29 //용혼석
|
||||
ITEM_SPECIAL_DS, //30 // 특수한 용혼석 (DS_SLOT에 착용하는 UNIQUE 아이템이라 생각하면 됨)
|
||||
ITEM_EXTRACT, //31 추출도구.
|
||||
ITEM_SECONDARY_COIN, //32 ?? 명도전??
|
||||
ITEM_RING, //33 반지
|
||||
ITEM_BELT, //34 벨트
|
||||
ITEM_HAIR, //25//머리
|
||||
ITEM_TOTEM, //26//토템
|
||||
ITEM_BLEND, //27//생성될때 랜덤하게 속성이 붙는 약물
|
||||
ITEM_COSTUME, //28//코스츔 아이템 (2011년 8월 추가된 코스츔 시스템용 아이템)
|
||||
ITEM_DS, //29 //용혼석
|
||||
ITEM_SPECIAL_DS, //30 // 특수한 용혼석 (DS_SLOT에 착용하는 UNIQUE 아이템이라 생각하면 됨)
|
||||
ITEM_EXTRACT, //31 추출도구.
|
||||
ITEM_SECONDARY_COIN, //32 ?? 명도전??
|
||||
ITEM_RING, //33 반지
|
||||
ITEM_BELT, //34 벨트
|
||||
ITEM_SHINING, //35 AVA2 shining (not ported, keeps the AVA2 numbering)
|
||||
ITEM_NEW_RINGS, //36 AVA2 new rings (port_rings.cpp), worn in WEAR_RINGS_1/2
|
||||
ITEM_PET, // PORT: AVA2 growable pets, explicit item type 37.
|
||||
};
|
||||
|
||||
enum EPetSubTypes { PET_LEVELABLE, PET_EGG, PET_TRANSPORTBOX, PET_PROTEIN, PET_CHANGE_NAME_ITEM, PET_DEW, PET_SKILL, PET_PRIMIUM_FEEDSTUFF, PET_ATTR_CHANGE, PET_ATTR_DETERMINE, PET_EXPFOOD_PER, PET_SKILL_DEL_BOOK, PET_SKILL_ALL_DEL_BOOK, PET_EXPFOOD, PET_FEEDSTUFF };
|
||||
enum EShiningSubTypes { SHINING_WEAPON, SHINING_ARMOR, SHINING_SPECIAL };
|
||||
|
||||
enum EMetinSubTypes
|
||||
@@ -100,6 +99,9 @@ enum EWeaponSubTypes
|
||||
WEAPON_FAN,
|
||||
WEAPON_ARROW,
|
||||
WEAPON_MOUNT_SPEAR,
|
||||
// PORT: preserve AVA2 numeric positions; reserving claw does not enable Wolfman.
|
||||
WEAPON_CLAW = 8,
|
||||
WEAPON_QUIVER = 9,
|
||||
WEAPON_NUM_TYPES,
|
||||
};
|
||||
|
||||
@@ -118,8 +120,8 @@ enum EArmorSubTypes
|
||||
|
||||
enum ECostumeSubTypes
|
||||
{
|
||||
COSTUME_BODY = ARMOR_BODY, // [중요!!] ECostumeSubTypes enum value는 종류별로 EArmorSubTypes의 그것과 같아야 함.
|
||||
COSTUME_HAIR = ARMOR_HEAD, // 이는 코스츔 아이템에 추가 속성을 붙이겠다는 사업부의 요청에 따라서 기존 로직을 활용하기 위함임.
|
||||
COSTUME_BODY = ARMOR_BODY, // [중요!!] ECostumeSubTypes enum value는 종류별로 EArmorSubTypes의 그것과 같아야 함.
|
||||
COSTUME_HAIR = ARMOR_HEAD, // 이는 코스츔 아이템에 추가 속성을 붙이겠다는 사업부의 요청에 따라서 기존 로직을 활용하기 위함임.
|
||||
COSTUME_MOUNT = 2, // AVA2 mount costume (value0 = horse race)
|
||||
COSTUME_SASH = 3, // AVA2 sash (85001..85024)
|
||||
COSTUME_MOUNT_SKIN = 4, // AVA2 mount skin (value0 = horse race, needs COSTUME_MOUNT)
|
||||
@@ -129,6 +131,25 @@ enum ECostumeSubTypes
|
||||
COSTUME_NUM_TYPES,
|
||||
};
|
||||
|
||||
enum EPetSubTypes
|
||||
{
|
||||
PET_LEVELABLE,
|
||||
PET_EGG,
|
||||
PET_TRANSPORTBOX,
|
||||
PET_PROTEIN,
|
||||
PET_CHANGE_NAME_ITEM,
|
||||
PET_DEW,
|
||||
PET_SKILL,
|
||||
PET_PRIMIUM_FEEDSTUFF,
|
||||
PET_ATTR_CHANGE,
|
||||
PET_ATTR_DETERMINE,
|
||||
PET_EXPFOOD_PER,
|
||||
PET_SKILL_DEL_BOOK,
|
||||
PET_SKILL_ALL_DEL_BOOK,
|
||||
PET_EXPFOOD,
|
||||
PET_FEEDSTUFF,
|
||||
};
|
||||
|
||||
enum EDragonSoulSubType
|
||||
{
|
||||
DS_SLOT1,
|
||||
@@ -228,8 +249,8 @@ enum EUseSubTypes
|
||||
USE_UNBIND,
|
||||
USE_TIME_CHARGE_PER,
|
||||
USE_TIME_CHARGE_FIX, // 28
|
||||
USE_PUT_INTO_BELT_SOCKET, // 29 벨트 소켓에 사용할 수 있는 아이템
|
||||
USE_PUT_INTO_RING_SOCKET, // 30 반지 소켓에 사용할 수 있는 아이템 (유니크 반지 말고, 새로 추가된 반지 슬롯)
|
||||
USE_PUT_INTO_BELT_SOCKET, // 29 벨트 소켓에 사용할 수 있는 아이템
|
||||
USE_PUT_INTO_RING_SOCKET, // 30 반지 소켓에 사용할 수 있는 아이템 (유니크 반지 말고, 새로 추가된 반지 슬롯)
|
||||
};
|
||||
|
||||
enum EExtractSubTypes
|
||||
@@ -283,7 +304,7 @@ enum EItemFlag
|
||||
{
|
||||
ITEM_FLAG_REFINEABLE = (1 << 0),
|
||||
ITEM_FLAG_SAVE = (1 << 1),
|
||||
ITEM_FLAG_STACKABLE = (1 << 2), // 여러개 합칠 수 있음
|
||||
ITEM_FLAG_STACKABLE = (1 << 2), // 여러개 합칠 수 있음
|
||||
ITEM_FLAG_COUNT_PER_1GOLD = (1 << 3),
|
||||
ITEM_FLAG_SLOW_QUERY = (1 << 4),
|
||||
ITEM_FLAG_UNUSED01 = (1 << 5), // UNUSED
|
||||
@@ -300,24 +321,24 @@ enum EItemFlag
|
||||
|
||||
enum EItemAntiFlag
|
||||
{
|
||||
ITEM_ANTIFLAG_FEMALE = (1 << 0), // 여성 사용 불가
|
||||
ITEM_ANTIFLAG_MALE = (1 << 1), // 남성 사용 불가
|
||||
ITEM_ANTIFLAG_WARRIOR = (1 << 2), // 무사 사용 불가
|
||||
ITEM_ANTIFLAG_ASSASSIN = (1 << 3), // 자객 사용 불가
|
||||
ITEM_ANTIFLAG_SURA = (1 << 4), // 수라 사용 불가
|
||||
ITEM_ANTIFLAG_SHAMAN = (1 << 5), // 무당 사용 불가
|
||||
ITEM_ANTIFLAG_GET = (1 << 6), // 집을 수 없음
|
||||
ITEM_ANTIFLAG_DROP = (1 << 7), // 버릴 수 없음
|
||||
ITEM_ANTIFLAG_SELL = (1 << 8), // 팔 수 없음
|
||||
ITEM_ANTIFLAG_EMPIRE_A = (1 << 9), // A 제국 사용 불가
|
||||
ITEM_ANTIFLAG_EMPIRE_B = (1 << 10), // B 제국 사용 불가
|
||||
ITEM_ANTIFLAG_EMPIRE_C = (1 << 11), // C 제국 사용 불가
|
||||
ITEM_ANTIFLAG_SAVE = (1 << 12), // 저장되지 않음
|
||||
ITEM_ANTIFLAG_GIVE = (1 << 13), // 거래 불가
|
||||
ITEM_ANTIFLAG_PKDROP = (1 << 14), // PK시 떨어지지 않음
|
||||
ITEM_ANTIFLAG_STACK = (1 << 15), // 합칠 수 없음
|
||||
ITEM_ANTIFLAG_MYSHOP = (1 << 16), // 개인 상점에 올릴 수 없음
|
||||
ITEM_ANTIFLAG_SAFEBOX = (1 << 17), // 창고에 넣을 수 없음
|
||||
ITEM_ANTIFLAG_FEMALE = (1 << 0), // 여성 사용 불가
|
||||
ITEM_ANTIFLAG_MALE = (1 << 1), // 남성 사용 불가
|
||||
ITEM_ANTIFLAG_WARRIOR = (1 << 2), // 무사 사용 불가
|
||||
ITEM_ANTIFLAG_ASSASSIN = (1 << 3), // 자객 사용 불가
|
||||
ITEM_ANTIFLAG_SURA = (1 << 4), // 수라 사용 불가
|
||||
ITEM_ANTIFLAG_SHAMAN = (1 << 5), // 무당 사용 불가
|
||||
ITEM_ANTIFLAG_GET = (1 << 6), // 집을 수 없음
|
||||
ITEM_ANTIFLAG_DROP = (1 << 7), // 버릴 수 없음
|
||||
ITEM_ANTIFLAG_SELL = (1 << 8), // 팔 수 없음
|
||||
ITEM_ANTIFLAG_EMPIRE_A = (1 << 9), // A 제국 사용 불가
|
||||
ITEM_ANTIFLAG_EMPIRE_B = (1 << 10), // B 제국 사용 불가
|
||||
ITEM_ANTIFLAG_EMPIRE_C = (1 << 11), // C 제국 사용 불가
|
||||
ITEM_ANTIFLAG_SAVE = (1 << 12), // 저장되지 않음
|
||||
ITEM_ANTIFLAG_GIVE = (1 << 13), // 거래 불가
|
||||
ITEM_ANTIFLAG_PKDROP = (1 << 14), // PK시 떨어지지 않음
|
||||
ITEM_ANTIFLAG_STACK = (1 << 15), // 합칠 수 없음
|
||||
ITEM_ANTIFLAG_MYSHOP = (1 << 16), // 개인 상점에 올릴 수 없음
|
||||
ITEM_ANTIFLAG_SAFEBOX = (1 << 17), // 창고에 넣을 수 없음
|
||||
};
|
||||
|
||||
enum EItemWearableFlag
|
||||
@@ -348,16 +369,16 @@ enum ELimitTypes
|
||||
LIMIT_CON,
|
||||
LIMIT_PCBANG,
|
||||
|
||||
/// 착용 여부와 상관 없이 실시간으로 시간 차감 (socket0에 소멸 시간이 박힘: unix_timestamp 타입)
|
||||
/// 착용 여부와 상관 없이 실시간으로 시간 차감 (socket0에 소멸 시간이 박힘: unix_timestamp 타입)
|
||||
LIMIT_REAL_TIME,
|
||||
|
||||
/// 아이템을 맨 처음 사용(혹은 착용) 한 순간부터 리얼타임 타이머 시작
|
||||
/// 최초 사용 전에는 socket0에 사용가능시간(초단위, 0이면 프로토의 limit value값 사용) 값이 쓰여있다가
|
||||
/// 아이템 사용시 socket1에 사용 횟수가 박히고 socket0에 unix_timestamp 타입의 소멸시간이 박힘.
|
||||
/// 아이템을 맨 처음 사용(혹은 착용) 한 순간부터 리얼타임 타이머 시작
|
||||
/// 최초 사용 전에는 socket0에 사용가능시간(초단위, 0이면 프로토의 limit value값 사용) 값이 쓰여있다가
|
||||
/// 아이템 사용시 socket1에 사용 횟수가 박히고 socket0에 unix_timestamp 타입의 소멸시간이 박힘.
|
||||
LIMIT_REAL_TIME_START_FIRST_USE,
|
||||
|
||||
/// 아이템을 착용 중일 때만 사용 시간이 차감되는 아이템
|
||||
/// socket0에 남은 시간이 초단위로 박힘. (아이템 최초 사용시 해당 값이 0이면 프로토의 limit value값을 socket0에 복사)
|
||||
/// 아이템을 착용 중일 때만 사용 시간이 차감되는 아이템
|
||||
/// socket0에 남은 시간이 초단위로 박힘. (아이템 최초 사용시 해당 값이 0이면 프로토의 limit value값을 socket0에 복사)
|
||||
LIMIT_TIMER_BASED_ON_WEAR,
|
||||
|
||||
LIMIT_MAX_NUM
|
||||
|
||||
+127
-72
@@ -1,6 +1,9 @@
|
||||
#ifndef __INC_METIN_II_LENGTH_H__
|
||||
#define __INC_METIN_II_LENGTH_H__
|
||||
|
||||
// Feature-dependent wire layouts must not depend on a caller's include order.
|
||||
#include "service.h"
|
||||
|
||||
#define WORD_MAX 0xffff
|
||||
enum EMisc
|
||||
{
|
||||
@@ -11,7 +14,12 @@ enum EMisc
|
||||
PLAYER_PER_ACCOUNT = 4,
|
||||
ACCOUNT_STATUS_MAX_LEN = 8,
|
||||
CHARACTER_NAME_MAX_LEN = 24,
|
||||
#ifdef ENABLE_OFFLINESHOP_SYSTEM
|
||||
OFFLINE_SHOP_HOST_ITEM_MAX_NUM = 80,
|
||||
SHOP_SIGN_MAX_LEN = 45,
|
||||
#else
|
||||
SHOP_SIGN_MAX_LEN = 32,
|
||||
#endif
|
||||
INVENTORY_PAGE_SIZE = 45, // 5 x 9
|
||||
INVENTORY_PAGE_COUNT = 5, // MT: 40250 ships 2 pages (90 cells)
|
||||
INVENTORY_MAX_NUM = INVENTORY_PAGE_SIZE * INVENTORY_PAGE_COUNT,
|
||||
@@ -24,10 +32,10 @@ enum EMisc
|
||||
|
||||
GUILD_NAME_MAX_LEN = 12,
|
||||
|
||||
SHOP_HOST_ITEM_MAX_NUM = 40, /* 호스트의 최대 아이템 개수 */
|
||||
SHOP_GUEST_ITEM_MAX_NUM = 18, /* 게스트의 최대 아이템 개수 */
|
||||
SHOP_HOST_ITEM_MAX_NUM = 40, /* 호스트의 최대 아이템 개수 */
|
||||
SHOP_GUEST_ITEM_MAX_NUM = 18, /* 게스트의 최대 아이템 개수 */
|
||||
|
||||
SHOP_PRICELIST_MAX_NUM = 40, ///< 개인상점 가격정보 리스트에서 유지할 가격정보의 최대 갯수
|
||||
SHOP_PRICELIST_MAX_NUM = 40, ///< 개인상점 가격정보 리스트에서 유지할 가격정보의 최대 갯수
|
||||
|
||||
CHAT_MAX_LEN = 512,
|
||||
|
||||
@@ -48,6 +56,13 @@ enum EMisc
|
||||
ATTRIBUTE_MAX_VALUE = 20,
|
||||
CHARACTER_PATH_MAX_NUM = 64,
|
||||
SKILL_MAX_NUM = 255,
|
||||
|
||||
#ifdef ENABLE_NEW_PET_SYSTEM
|
||||
PET_MAX_EVOLUTION_CONST = 3,
|
||||
PET_MAX_LEVEL_CONST = 120,
|
||||
PET_APPLY_MAX_NUM = 3,
|
||||
PET_SKILLS_MAX_NUM = 15,
|
||||
#endif
|
||||
SKILLBOOK_DELAY_MIN = 64800,
|
||||
SKILLBOOK_DELAY_MAX = 108000,
|
||||
SKILL_MAX_LEVEL = 40,
|
||||
@@ -68,6 +83,7 @@ enum EMisc
|
||||
|
||||
//LIMIT_GOLD
|
||||
GOLD_MAX = 2000000000,
|
||||
GOLD_MAX_64 = 2000000000000000LL,
|
||||
|
||||
MAX_PASSPOD = 8 ,
|
||||
|
||||
@@ -84,21 +100,33 @@ enum EMisc
|
||||
|
||||
BELT_INVENTORY_SLOT_COUNT = BELT_INVENTORY_SLOT_WIDTH * BELT_INVENTORY_SLOT_HEIGHT,
|
||||
|
||||
#ifdef ENABLE_SPECIAL_STORAGE
|
||||
SPECIAL_INVENTORY_PAGE_COLUMN = 5,
|
||||
SPECIAL_INVENTORY_PAGE_ROW = 9,
|
||||
SPECIAL_INVENTORY_PAGE_SIZE = SPECIAL_INVENTORY_PAGE_COLUMN * SPECIAL_INVENTORY_PAGE_ROW,
|
||||
SPECIAL_INVENTORY_PAGE_COUNT = 4,
|
||||
SPECIAL_INVENTORY_MAX_NUM = SPECIAL_INVENTORY_PAGE_SIZE * SPECIAL_INVENTORY_PAGE_COUNT,
|
||||
#endif
|
||||
|
||||
#ifdef UNLOCK_INVENTORY_WORLDARD
|
||||
UNLOCK_INVENTORY_MAX = 6,
|
||||
#endif
|
||||
|
||||
|
||||
/**
|
||||
**** 현재까지 할당 된 아이템 영역 정리 (DB상 Item Position) ****
|
||||
**** 현재까지 할당 된 아이템 영역 정리 (DB상 Item Position) ****
|
||||
+------------------------------------------------------+ 0
|
||||
| 캐릭터 기본 인벤토리 (45칸 * 2페이지) 90칸 |
|
||||
| 캐릭터 기본 인벤토리 (45칸 * 2페이지) 90칸 |
|
||||
+------------------------------------------------------+ 225 = INVENTORY_MAX_NUM(225) MT: 5 pages; 40250 had 90 and every cell below moved by +135
|
||||
| 캐릭터 장비 창 (착용중인 아이템) 32칸 |
|
||||
| 캐릭터 장비 창 (착용중인 아이템) 32칸 |
|
||||
+------------------------------------------------------+ 257 = INVENTORY_MAX_NUM(225) + WEAR_MAX_NUM(32)
|
||||
| 용혼석 장비 창 (착용중인 용혼석) 12칸 |
|
||||
| 용혼석 장비 창 (착용중인 용혼석) 12칸 |
|
||||
+------------------------------------------------------+ 269 = 257 + DS_SLOT_MAX(6) * DRAGON_SOUL_DECK_MAX_NUM(2)
|
||||
| 용혼석 장비 창 예약 (아직 미사용) 18칸 |
|
||||
| 용혼석 장비 창 예약 (아직 미사용) 18칸 |
|
||||
+------------------------------------------------------+ 287 = 269 + DS_SLOT_MAX(6) * DRAGON_SOUL_DECK_RESERVED_MAX_NUM(3)
|
||||
| 벨트 인벤토리 (벨트 착용시에만 벨트 레벨에 따라 활성)|
|
||||
| 벨트 인벤토리 (벨트 착용시에만 벨트 레벨에 따라 활성)|
|
||||
+------------------------------------------------------+ 303 = 287 + BELT_INVENTORY_SLOT_COUNT(16) = INVENTORY_AND_EQUIP_CELL_MAX
|
||||
| 미사용 |
|
||||
| 미사용 |
|
||||
+------------------------------------------------------+ ??
|
||||
*/
|
||||
};
|
||||
@@ -133,10 +161,10 @@ enum EWearPositions
|
||||
WEAR_COSTUME_BODY, // 19
|
||||
WEAR_COSTUME_HAIR, // 20
|
||||
|
||||
WEAR_RING1, // 21 : 신규 반지슬롯1 (왼쪽)
|
||||
WEAR_RING2, // 22 : 신규 반지슬롯2 (오른쪽)
|
||||
WEAR_RING1, // 21 : 신규 반지슬롯1 (왼쪽)
|
||||
WEAR_RING2, // 22 : 신규 반지슬롯2 (오른쪽)
|
||||
|
||||
WEAR_BELT, // 23 : 신규 벨트슬롯
|
||||
WEAR_BELT, // 23 : 신규 벨트슬롯
|
||||
WEAR_COSTUME_SASH, // 24 : AVA2 sash
|
||||
WEAR_COSTUME_MOUNT, // 25 : AVA2 mount costume
|
||||
WEAR_COSTUME_MOUNT_SKIN, // 26 : AVA2 mount skin
|
||||
@@ -160,7 +188,7 @@ enum EDragonSoulDeckType
|
||||
DRAGON_SOUL_DECK_1,
|
||||
DRAGON_SOUL_DECK_MAX_NUM = 2,
|
||||
|
||||
DRAGON_SOUL_DECK_RESERVED_MAX_NUM = 3, // NOTE: 중요! 아직 사용중이진 않지만, 3페이지 분량을 예약 해 둠. DS DECK을 늘릴 경우 반드시 그 수만큼 RESERVED에서 차감해야 함!
|
||||
DRAGON_SOUL_DECK_RESERVED_MAX_NUM = 3, // NOTE: 중요! 아직 사용중이진 않지만, 3페이지 분량을 예약 해 둠. DS DECK을 늘릴 경우 반드시 그 수만큼 RESERVED에서 차감해야 함!
|
||||
};
|
||||
|
||||
enum ESex
|
||||
@@ -182,7 +210,7 @@ enum EDirection
|
||||
DIR_MAX_NUM
|
||||
};
|
||||
|
||||
#define ABILITY_MAX_LEVEL 10 /* 기술 최대 레벨 */
|
||||
#define ABILITY_MAX_LEVEL 10 /* 기술 최대 레벨 */
|
||||
|
||||
enum EAbilityDifficulty
|
||||
{
|
||||
@@ -195,9 +223,9 @@ enum EAbilityDifficulty
|
||||
|
||||
enum EAbilityCategory
|
||||
{
|
||||
CATEGORY_PHYSICAL, /* 신체적 어빌리티 */
|
||||
CATEGORY_MENTAL, /* 정신적 어빌리티 */
|
||||
CATEGORY_ATTRIBUTE, /* 능력 어빌리티 */
|
||||
CATEGORY_PHYSICAL, /* 신체적 어빌리티 */
|
||||
CATEGORY_MENTAL, /* 정신적 어빌리티 */
|
||||
CATEGORY_ATTRIBUTE, /* 능력 어빌리티 */
|
||||
CATEGORY_NUM_TYPES
|
||||
};
|
||||
|
||||
@@ -268,13 +296,13 @@ enum EParts
|
||||
|
||||
enum EChatType
|
||||
{
|
||||
CHAT_TYPE_TALKING, /* 그냥 채팅 */
|
||||
CHAT_TYPE_INFO, /* 정보 (아이템을 집었다, 경험치를 얻었다. 등) */
|
||||
CHAT_TYPE_NOTICE, /* 공지사항 */
|
||||
CHAT_TYPE_PARTY, /* 파티말 */
|
||||
CHAT_TYPE_GUILD, /* 길드말 */
|
||||
CHAT_TYPE_COMMAND, /* 일반 명령 */
|
||||
CHAT_TYPE_SHOUT, /* 외치기 */
|
||||
CHAT_TYPE_TALKING, /* 그냥 채팅 */
|
||||
CHAT_TYPE_INFO, /* 정보 (아이템을 집었다, 경험치를 얻었다. 등) */
|
||||
CHAT_TYPE_NOTICE, /* 공지사항 */
|
||||
CHAT_TYPE_PARTY, /* 파티말 */
|
||||
CHAT_TYPE_GUILD, /* 길드말 */
|
||||
CHAT_TYPE_COMMAND, /* 일반 명령 */
|
||||
CHAT_TYPE_SHOUT, /* 외치기 */
|
||||
CHAT_TYPE_WHISPER,
|
||||
CHAT_TYPE_BIG_NOTICE,
|
||||
CHAT_TYPE_MONARCH_NOTICE,
|
||||
@@ -335,7 +363,10 @@ enum ECharType
|
||||
CHAR_TYPE_PC,
|
||||
CHAR_TYPE_POLYMORPH_PC,
|
||||
CHAR_TYPE_HORSE,
|
||||
CHAR_TYPE_GOTO
|
||||
CHAR_TYPE_GOTO,
|
||||
#ifdef ENABLE_NEW_PET_SYSTEM
|
||||
CHAR_TYPE_PET,
|
||||
#endif
|
||||
};
|
||||
|
||||
enum EBattleType
|
||||
@@ -417,44 +448,46 @@ enum EApplyTypes
|
||||
APPLY_ATTBONUS_SURA, // 61
|
||||
APPLY_ATTBONUS_SHAMAN, // 62
|
||||
APPLY_ATTBONUS_MONSTER, // 63
|
||||
APPLY_MALL_ATTBONUS, // 64 공격력 +x%
|
||||
APPLY_MALL_DEFBONUS, // 65 방어력 +x%
|
||||
APPLY_MALL_EXPBONUS, // 66 경험치 +x%
|
||||
APPLY_MALL_ITEMBONUS, // 67 아이템 드롭율 x/10배
|
||||
APPLY_MALL_GOLDBONUS, // 68 돈 드롭율 x/10배
|
||||
APPLY_MAX_HP_PCT, // 69 최대 생명력 +x%
|
||||
APPLY_MAX_SP_PCT, // 70 최대 정신력 +x%
|
||||
APPLY_SKILL_DAMAGE_BONUS, // 71 스킬 데미지 * (100+x)%
|
||||
APPLY_NORMAL_HIT_DAMAGE_BONUS, // 72 평타 데미지 * (100+x)%
|
||||
APPLY_SKILL_DEFEND_BONUS, // 73 스킬 데미지 방어 * (100-x)%
|
||||
APPLY_NORMAL_HIT_DEFEND_BONUS, // 74 평타 데미지 방어 * (100-x)%
|
||||
APPLY_PC_BANG_EXP_BONUS, // 75 PC방 아이템 EXP 보너스
|
||||
APPLY_PC_BANG_DROP_BONUS, // 76 PC방 아이템 드롭율 보너스
|
||||
APPLY_MALL_ATTBONUS, // 64 공격력 +x%
|
||||
APPLY_MALL_DEFBONUS, // 65 방어력 +x%
|
||||
APPLY_MALL_EXPBONUS, // 66 경험치 +x%
|
||||
APPLY_MALL_ITEMBONUS, // 67 아이템 드롭율 x/10배
|
||||
APPLY_MALL_GOLDBONUS, // 68 돈 드롭율 x/10배
|
||||
APPLY_MAX_HP_PCT, // 69 최대 생명력 +x%
|
||||
APPLY_MAX_SP_PCT, // 70 최대 정신력 +x%
|
||||
APPLY_SKILL_DAMAGE_BONUS, // 71 스킬 데미지 * (100+x)%
|
||||
APPLY_NORMAL_HIT_DAMAGE_BONUS, // 72 평타 데미지 * (100+x)%
|
||||
APPLY_SKILL_DEFEND_BONUS, // 73 스킬 데미지 방어 * (100-x)%
|
||||
APPLY_NORMAL_HIT_DEFEND_BONUS, // 74 평타 데미지 방어 * (100-x)%
|
||||
APPLY_PC_BANG_EXP_BONUS, // 75 PC방 아이템 EXP 보너스
|
||||
APPLY_PC_BANG_DROP_BONUS, // 76 PC방 아이템 드롭율 보너스
|
||||
|
||||
APPLY_EXTRACT_HP_PCT, // 77 사용시 HP 소모
|
||||
APPLY_EXTRACT_HP_PCT, // 77 사용시 HP 소모
|
||||
|
||||
APPLY_RESIST_WARRIOR, // 78 무사에게 저항
|
||||
APPLY_RESIST_ASSASSIN, // 79 자객에게 저항
|
||||
APPLY_RESIST_SURA, // 80 수라에게 저항
|
||||
APPLY_RESIST_SHAMAN, // 81 무당에게 저항
|
||||
APPLY_ENERGY, // 82 기력
|
||||
APPLY_DEF_GRADE, // 83 방어력. DEF_GRADE_BONUS는 클라에서 두배로 보여지는 의도된 버그(...)가 있다.
|
||||
APPLY_COSTUME_ATTR_BONUS, // 84 코스튬 아이템에 붙은 속성치 보너스
|
||||
APPLY_MAGIC_ATTBONUS_PER, // 85 마법 공격력 +x%
|
||||
APPLY_MELEE_MAGIC_ATTBONUS_PER, // 86 마법 + 밀리 공격력 +x%
|
||||
APPLY_RESIST_WARRIOR, // 78 무사에게 저항
|
||||
APPLY_RESIST_ASSASSIN, // 79 자객에게 저항
|
||||
APPLY_RESIST_SURA, // 80 수라에게 저항
|
||||
APPLY_RESIST_SHAMAN, // 81 무당에게 저항
|
||||
APPLY_ENERGY, // 82 기력
|
||||
APPLY_DEF_GRADE, // 83 방어력. DEF_GRADE_BONUS는 클라에서 두배로 보여지는 의도된 버그(...)가 있다.
|
||||
APPLY_COSTUME_ATTR_BONUS, // 84 코스튬 아이템에 붙은 속성치 보너스
|
||||
APPLY_MAGIC_ATTBONUS_PER, // 85 마법 공격력 +x%
|
||||
APPLY_MELEE_MAGIC_ATTBONUS_PER, // 86 마법 + 밀리 공격력 +x%
|
||||
|
||||
APPLY_RESIST_ICE, // 87 냉기 저항
|
||||
APPLY_RESIST_EARTH, // 88 대지 저항
|
||||
APPLY_RESIST_DARK, // 89 어둠 저항
|
||||
APPLY_RESIST_ICE, // 87 냉기 저항
|
||||
APPLY_RESIST_EARTH, // 88 대지 저항
|
||||
APPLY_RESIST_DARK, // 89 어둠 저항
|
||||
|
||||
APPLY_ANTI_CRITICAL_PCT, //90 크리티컬 저항
|
||||
APPLY_ANTI_PENETRATE_PCT, //91 관통타격 저항
|
||||
APPLY_ANTI_CRITICAL_PCT, //90 크리티컬 저항
|
||||
APPLY_ANTI_PENETRATE_PCT, //91 관통타격 저항
|
||||
|
||||
|
||||
// PORT AVA2 bonus numbering (AVA2 common/length.h): 92-138 are AVA2 applies not ported yet,
|
||||
// kept free so later ports and the client item_proto keep AVA2's numbers.
|
||||
// AVA2 ELEMENT_NEW_BONUSES: attack bonus % against monsters of the element (RACE_FLAG_ATT_*), on the talismans.
|
||||
APPLY_ENCHANT_ELEC = 123,
|
||||
APPLY_RESIST_MAGIC_REDUCTION = 98, // AVA2 ENABLE_MAGIC_REDUCTION_SYSTEM.
|
||||
APPLY_RESIST_HUMAN = 99, // AVA2 growing-pet skill 17.
|
||||
APPLY_ENCHANT_ELEC = 123,
|
||||
APPLY_ENCHANT_FIRE = 124,
|
||||
APPLY_ENCHANT_ICE = 125,
|
||||
APPLY_ENCHANT_WIND = 126,
|
||||
@@ -506,6 +539,13 @@ enum EWindows
|
||||
DRAGON_SOUL_INVENTORY,
|
||||
BELT_INVENTORY,
|
||||
SWITCHBOT, // PORT: 7 = player.item.window enum 'SWITCHBOT' (appended after BELT_INVENTORY)
|
||||
#ifdef ENABLE_SPECIAL_STORAGE
|
||||
UPGRADE_INVENTORY, // 8
|
||||
BOOK_INVENTORY, // 9
|
||||
STONE_INVENTORY, // 10
|
||||
CHANGE_INVENTORY, // 11
|
||||
COSTUME_INVENTORY, // 12
|
||||
#endif
|
||||
#ifdef __AUCTION__
|
||||
AUCTION,
|
||||
#endif
|
||||
@@ -628,7 +668,7 @@ enum EGuildWarState
|
||||
GUILD_WAR_OVER,
|
||||
GUILD_WAR_RESERVE,
|
||||
|
||||
GUILD_WAR_DURATION = 30*60, // 1시간
|
||||
GUILD_WAR_DURATION = 30*60, // 1시간
|
||||
GUILD_WAR_WIN_POINT = 1000,
|
||||
GUILD_WAR_LADDER_HALF_PENALTY_TIME = 12*60*60,
|
||||
};
|
||||
@@ -672,13 +712,13 @@ enum EMoneyLogType
|
||||
|
||||
enum EPremiumTypes
|
||||
{
|
||||
PREMIUM_EXP, // 경험치가 1.2배
|
||||
PREMIUM_ITEM, // 아이템 드롭율이 2배
|
||||
PREMIUM_SAFEBOX, // 창고가 1칸에서 3칸
|
||||
PREMIUM_AUTOLOOT, // 돈 자동 줍기
|
||||
PREMIUM_FISH_MIND, // 고급 물고기 낚일 확률 상승
|
||||
PREMIUM_MARRIAGE_FAST, // 금실 증가 양을 빠르게합니다.
|
||||
PREMIUM_GOLD, // 돈 드롭율이 1.5배
|
||||
PREMIUM_EXP, // 경험치가 1.2배
|
||||
PREMIUM_ITEM, // 아이템 드롭율이 2배
|
||||
PREMIUM_SAFEBOX, // 창고가 1칸에서 3칸
|
||||
PREMIUM_AUTOLOOT, // 돈 자동 줍기
|
||||
PREMIUM_FISH_MIND, // 고급 물고기 낚일 확률 상승
|
||||
PREMIUM_MARRIAGE_FAST, // 금실 증가 양을 빠르게합니다.
|
||||
PREMIUM_GOLD, // 돈 드롭율이 1.5배
|
||||
PREMIUM_MAX_NUM = 9
|
||||
};
|
||||
|
||||
@@ -708,10 +748,10 @@ enum SPECIAL_EFFECT
|
||||
SE_AUTO_HPUP,
|
||||
SE_AUTO_SPUP,
|
||||
|
||||
SE_EQUIP_RAMADAN_RING, // 라마단 초승달의 반지(71135) 착용할 때 이펙트 (발동이펙트임, 지속이펙트 아님)
|
||||
SE_EQUIP_HALLOWEEN_CANDY, // 할로윈 사탕을 착용(-_-;)한 순간에 발동하는 이펙트
|
||||
SE_EQUIP_HAPPINESS_RING, // 크리스마스 행복의 반지(71143) 착용할 때 이펙트 (발동이펙트임, 지속이펙트 아님)
|
||||
SE_EQUIP_LOVE_PENDANT, // 발렌타인 사랑의 팬던트(71145) 착용할 때 이펙트 (발동이펙트임, 지속이펙트 아님)
|
||||
SE_EQUIP_RAMADAN_RING, // 라마단 초승달의 반지(71135) 착용할 때 이펙트 (발동이펙트임, 지속이펙트 아님)
|
||||
SE_EQUIP_HALLOWEEN_CANDY, // 할로윈 사탕을 착용(-_-;)한 순간에 발동하는 이펙트
|
||||
SE_EQUIP_HAPPINESS_RING, // 크리스마스 행복의 반지(71143) 착용할 때 이펙트 (발동이펙트임, 지속이펙트 아님)
|
||||
SE_EQUIP_LOVE_PENDANT, // 발렌타인 사랑의 팬던트(71145) 착용할 때 이펙트 (발동이펙트임, 지속이펙트 아님)
|
||||
SE_EFFECT_SASH_SUCCEDED, // AVA2 sash combine success
|
||||
SE_EFFECT_SASH_EQUIP,
|
||||
} ;
|
||||
@@ -728,10 +768,10 @@ enum ETeenFlags
|
||||
|
||||
#include "item_length.h"
|
||||
|
||||
// inventory의 position을 나타내는 구조체
|
||||
// int와의 암시적 형변환이 있는 이유는,
|
||||
// 인벤 관련된 모든 함수가 window_type은 받지 않고, cell 하나만 받았기 때문에,(기존에는 인벤이 하나 뿐이어서 inventory type이란게 필요없었기 때문에,)
|
||||
// 인벤 관련 모든 함수 호출부분을 수정하는 것이 난감하기 떄문이다.
|
||||
// inventory의 position을 나타내는 구조체
|
||||
// int와의 암시적 형변환이 있는 이유는,
|
||||
// 인벤 관련된 모든 함수가 window_type은 받지 않고, cell 하나만 받았기 때문에,(기존에는 인벤이 하나 뿐이어서 inventory type이란게 필요없었기 때문에,)
|
||||
// 인벤 관련 모든 함수 호출부분을 수정하는 것이 난감하기 떄문이다.
|
||||
|
||||
enum EDragonSoulRefineWindowSize
|
||||
{
|
||||
@@ -782,7 +822,15 @@ typedef struct SItemPos
|
||||
return cell < (DRAGON_SOUL_INVENTORY_MAX_NUM);
|
||||
case SWITCHBOT:
|
||||
return cell < SWITCHBOT_SLOT_COUNT;
|
||||
// 동적으로 크기가 정해지는 window는 valid 체크를 할 수가 없다.
|
||||
#ifdef ENABLE_SPECIAL_STORAGE
|
||||
case UPGRADE_INVENTORY:
|
||||
case BOOK_INVENTORY:
|
||||
case STONE_INVENTORY:
|
||||
case CHANGE_INVENTORY:
|
||||
case COSTUME_INVENTORY:
|
||||
return cell < SPECIAL_INVENTORY_MAX_NUM;
|
||||
#endif
|
||||
// 동적으로 크기가 정해지는 window는 valid 체크를 할 수가 없다.
|
||||
case SAFEBOX:
|
||||
case MALL:
|
||||
return false;
|
||||
@@ -826,6 +874,13 @@ typedef struct SItemPos
|
||||
return SWITCHBOT == window_type && cell < SWITCHBOT_SLOT_COUNT;
|
||||
}
|
||||
|
||||
#ifdef ENABLE_SPECIAL_STORAGE
|
||||
bool IsSpecialInventoryPosition() const
|
||||
{
|
||||
return (window_type >= UPGRADE_INVENTORY && window_type <= COSTUME_INVENTORY) && (cell < SPECIAL_INVENTORY_MAX_NUM);
|
||||
}
|
||||
#endif
|
||||
|
||||
bool operator==(const struct SItemPos& rhs) const
|
||||
{
|
||||
return (window_type == rhs.window_type) && (cell == rhs.cell);
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
#pragma once
|
||||
// The legacy offline shop has no durable, atomic custody/payment/delivery order.
|
||||
// Keep ALL mutation and startup expiry cleanup closed until the replacement has
|
||||
// passed cross-core DB-failure recovery acceptance. No event/GM flag can bypass it.
|
||||
inline bool PortOfflineShopEconomyReady() { return false; }
|
||||
@@ -0,0 +1,131 @@
|
||||
#pragma once
|
||||
#include "ava2_itemshop.h"
|
||||
#include <cerrno>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <ctime>
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <fcntl.h>
|
||||
#include <sys/file.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
// A separate lifetime lock survives atomic compaction. The current data file is
|
||||
// locked too, so an already-running legacy append-only writer excludes startup.
|
||||
class PointJournal {
|
||||
struct Entry { Ava2ShopRequest request; uint64_t created; };
|
||||
int fd_=-1, lock_=-1, directory_=-1;
|
||||
bool healthy_=false;
|
||||
uint64_t bytes_=0;
|
||||
std::string name_, error_;
|
||||
std::map<std::string,Entry> pending_;
|
||||
bool Fail(const char* reason){healthy_=false;error_=reason;return false;}
|
||||
static uint32_t Hash(const std::string& data){uint32_t h=2166136261u;for(unsigned char c:data){h^=c;h*=16777619u;}return h;}
|
||||
static bool Token(const std::string& s){if(s.size()!=32)return false;for(char c:s)if(!((c>='0'&&c<='9')||(c>='a'&&c<='f')||(c>='A'&&c<='F')))return false;return true;}
|
||||
static bool Terminal(unsigned status){return status==0 || status==1 || status==2 || status==7;}
|
||||
static bool Regular(int fd){struct stat info={};return fstat(fd,&info)==0 && S_ISREG(info.st_mode);}
|
||||
static bool Unsigned(std::istringstream& in,uint64_t& value,uint64_t maximum){
|
||||
std::string text;if(!(in>>text)||text.empty())return false;value=0;
|
||||
for(unsigned char c:text){if(c<'0'||c>'9')return false;const unsigned digit=c-'0';if(value>maximum/10 || (value==maximum/10 && digit>maximum%10))return false;value=value*10+digit;}return true;
|
||||
}
|
||||
static Ava2ShopRequest Canonical(const Ava2ShopRequest& r){
|
||||
Ava2ShopRequest result={};result.operation=3;result.account=r.account;result.player=r.player;result.product=r.product;result.count=r.count;result.expectedVnum=r.expectedVnum;memcpy(result.token,r.token,32);return result;
|
||||
}
|
||||
static std::string IntentPayload(const Entry& entry){
|
||||
const auto& r=entry.request;std::ostringstream out;out<<"INTENT v2 "<<r.token<<' '<<r.account<<' '<<r.player<<' '<<r.product<<' '<<r.count<<' '<<r.expectedVnum<<' '<<entry.created;return out.str();
|
||||
}
|
||||
static std::string Record(const std::string& payload){char checksum[16];snprintf(checksum,sizeof(checksum)," %08x\n",Hash(payload));return payload+checksum;}
|
||||
static bool WriteAll(int fd,const std::string& line){
|
||||
size_t offset=0;while(offset<line.size()){const ssize_t n=write(fd,line.data()+offset,line.size()-offset);if(n<0&&errno==EINTR)continue;if(n<=0)return false;offset+=static_cast<size_t>(n);}return true;
|
||||
}
|
||||
bool Append(const std::string& payload){
|
||||
if(!healthy_)return false;const auto line=Record(payload);
|
||||
if(!WriteAll(fd_,line))return Fail("journal write failed; issuance paused; retain original journal for repair");
|
||||
if(fsync(fd_)!=0)return Fail("journal fsync failed; issuance paused; settlement may replay with same token");
|
||||
bytes_+=line.size();return true;
|
||||
}
|
||||
public:
|
||||
PointJournal()=default;
|
||||
PointJournal(const PointJournal&)=delete;
|
||||
~PointJournal(){if(fd_>=0)close(fd_);if(lock_>=0)close(lock_);if(directory_>=0)close(directory_);}
|
||||
bool Ready()const{return healthy_;}
|
||||
const std::string& Error()const{return error_;}
|
||||
bool NeedsCompaction()const{return healthy_ && bytes_>=1024*1024 && (bytes_-4096)/512>pending_.size();}
|
||||
bool Open(const std::string& path,std::map<std::string,Ava2ShopRequest>& pending){
|
||||
if(fd_>=0 || directory_>=0)return Fail("journal already open");
|
||||
const auto slash=path.rfind('/');const std::string dir=slash==std::string::npos?".":slash==0?"/":path.substr(0,slash);
|
||||
name_=slash==std::string::npos?path:path.substr(slash+1);
|
||||
if(name_.empty()||name_=="."||name_=="..")return Fail("invalid journal filename");
|
||||
if(mkdir(dir.c_str(),0700)!=0&&errno!=EEXIST)return Fail("cannot create journal directory");
|
||||
directory_=open(dir.c_str(),O_RDONLY|O_DIRECTORY|O_NOFOLLOW);if(directory_<0)return Fail("cannot open journal directory");
|
||||
const std::string lockName=name_+".lock";
|
||||
lock_=openat(directory_,lockName.c_str(),O_RDWR|O_CREAT|O_NOFOLLOW,0600);
|
||||
if(lock_<0||!Regular(lock_)||flock(lock_,LOCK_EX|LOCK_NB)!=0)return Fail("journal lock unavailable or already owned");
|
||||
fd_=openat(directory_,name_.c_str(),O_RDWR|O_CREAT|O_APPEND|O_NOFOLLOW,0600);
|
||||
if(fd_<0||!Regular(fd_))return Fail("cannot open regular journal");
|
||||
if(flock(fd_,LOCK_EX|LOCK_NB)!=0)return Fail("journal already owned by another process");
|
||||
struct stat info={};if(fstat(fd_,&info)!=0||info.st_size<0)return Fail("cannot stat journal");bytes_=static_cast<uint64_t>(info.st_size);
|
||||
if(fsync(fd_)!=0||fsync(lock_)!=0||fsync(directory_)!=0)return Fail("cannot persist journal directory entry");
|
||||
const int reader=dup(fd_);if(reader<0)return Fail("cannot duplicate journal reader");
|
||||
FILE* input=fdopen(reader,"r");if(!input){close(reader);return Fail("cannot read journal");}
|
||||
pending.clear();rewind(input);char line[512];bool valid=true;
|
||||
while(fgets(line,sizeof(line),input)){
|
||||
const size_t size=strlen(line);if(!size||line[size-1]!='\n'){valid=false;break;}
|
||||
std::string raw(line,size-1);std::istringstream fields(raw);std::string op,version,token,tail;fields>>op>>version>>token;
|
||||
if(!Token(token)||(version!="v1"&&version!="v2")){valid=false;break;}
|
||||
if(version=="v2"){
|
||||
const auto split=raw.rfind(' ');unsigned checksum=0;char extra=0;
|
||||
if(split==std::string::npos||sscanf(raw.c_str()+split+1,"%8x%c",&checksum,&extra)!=1||checksum!=Hash(raw.substr(0,split))){valid=false;break;}
|
||||
fields.clear();fields.str(raw.substr(0,split));fields>>op>>version>>token;
|
||||
}
|
||||
if(op=="INTENT"){
|
||||
Entry entry={};auto& r=entry.request;r.operation=3;uint64_t account=0,player=0,product=0,count=0,level=0;
|
||||
if(!Unsigned(fields,account,UINT32_MAX)||!Unsigned(fields,player,UINT32_MAX)||!Unsigned(fields,product,UINT32_MAX)||
|
||||
!Unsigned(fields,count,1000000)||!Unsigned(fields,level,255)||!Unsigned(fields,entry.created,UINT64_MAX)||fields>>tail||!account||!player||!product||!count||!level){valid=false;break;}
|
||||
r.account=static_cast<uint32_t>(account);r.player=static_cast<uint32_t>(player);r.product=static_cast<uint32_t>(product);r.count=static_cast<uint32_t>(count);r.expectedVnum=static_cast<uint32_t>(level);memcpy(r.token,token.c_str(),32);
|
||||
const auto found=pending_.find(token);
|
||||
if(found!=pending_.end()&&memcmp(&found->second.request,&r,sizeof(r))!=0){valid=false;break;}
|
||||
pending_[token]=entry;pending[token]=r;
|
||||
}else if(op=="DONE"){
|
||||
uint64_t status=0,granted=0,balance=0,created=0;
|
||||
if(!Unsigned(fields,status,255)||!Terminal(static_cast<unsigned>(status))||!Unsigned(fields,granted,1000000)||!Unsigned(fields,balance,INT64_MAX)||!Unsigned(fields,created,UINT64_MAX)||fields>>tail||(status!=0&&granted!=0)){valid=false;break;}
|
||||
const auto found=pending_.find(token);
|
||||
if(found!=pending_.end() && granted>found->second.request.count){valid=false;break;}
|
||||
pending_.erase(token);pending.erase(token);
|
||||
}else{valid=false;break;}
|
||||
}
|
||||
if(ferror(input))valid=false;fclose(input);
|
||||
if(!valid)return Fail("corrupt journal: preserve bytes, pause issuance and repair tail before resuming");
|
||||
healthy_=true;return true;
|
||||
}
|
||||
bool Intent(const Ava2ShopRequest& r){
|
||||
if(r.operation!=3 || r.token[32] || !Token(std::string(r.token,32)) || !r.account || !r.player || !r.product || !r.count || r.count>1000000 || !r.expectedVnum || r.expectedVnum>255){error_="invalid reward intent";return false;}
|
||||
Entry entry={Canonical(r),static_cast<uint64_t>(time(0))};const auto found=pending_.find(r.token);
|
||||
if(found!=pending_.end() && memcmp(&found->second.request,&entry.request,sizeof(r))!=0){error_="conflicting reward intent";return false;}
|
||||
if(!Append(IntentPayload(entry)))return false;pending_[r.token]=entry;return true;
|
||||
}
|
||||
bool Done(const char* token,uint8_t status,uint32_t granted,int64_t balance){
|
||||
if(!token || strnlen(token,33)!=32 || !Token(std::string(token,32)) || balance<0 || !Terminal(status) || (status!=0 && granted!=0)){error_="invalid reward completion";return false;}
|
||||
const auto found=pending_.find(token);
|
||||
if(found==pending_.end() || granted>found->second.request.count){error_="unknown or excessive reward completion";return false;}
|
||||
std::ostringstream out;out<<"DONE v2 "<<token<<' '<<unsigned(status)<<' '<<granted<<' '<<balance<<' '<<uint64_t(time(0));
|
||||
if(!Append(out.str()))return false;pending_.erase(found);return true;
|
||||
}
|
||||
bool Compact(){
|
||||
if(!healthy_)return false;
|
||||
const std::string temporary=name_+".compact."+std::to_string(getpid());
|
||||
const int next=openat(directory_,temporary.c_str(),O_RDWR|O_CREAT|O_EXCL|O_APPEND|O_NOFOLLOW,0600);
|
||||
if(next<0)return Fail("cannot create journal compact snapshot; original retained");
|
||||
uint64_t size=0;bool valid=flock(next,LOCK_EX|LOCK_NB)==0;
|
||||
for(const auto& entry:pending_){if(!valid)break;const auto line=Record(IntentPayload(entry.second));valid=WriteAll(next,line);size+=line.size();}
|
||||
if(valid)valid=fsync(next)==0;
|
||||
if(!valid){close(next);unlinkat(directory_,temporary.c_str(),0);return Fail("cannot persist journal compact snapshot; original retained");}
|
||||
if(renameat(directory_,temporary.c_str(),directory_,name_.c_str())!=0){close(next);unlinkat(directory_,temporary.c_str(),0);return Fail("cannot publish journal compact snapshot; original retained");}
|
||||
const int previous=fd_;fd_=next;bytes_=size;
|
||||
const bool synced=fsync(directory_)==0;close(previous);
|
||||
if(!synced)return Fail("journal compact directory sync failed; issuance paused; both snapshots retain pending intentions");
|
||||
return true;
|
||||
}
|
||||
};
|
||||
@@ -22,11 +22,13 @@ inline std::string PortItemExtraHex(const PortItemExtra& extra) {
|
||||
return result;
|
||||
}
|
||||
inline bool PortItemExtraRead(const char* hex,PortItemExtra& extra) {
|
||||
std::memset(&extra,0,sizeof(extra));
|
||||
if(!hex || !*hex)return true;
|
||||
if(std::strlen(hex)!=sizeof(extra)*2)return false;
|
||||
PortItemExtra decoded = {};
|
||||
if(!hex)return false;
|
||||
if(!*hex){extra=decoded;return true;}
|
||||
if(std::strlen(hex)!=sizeof(decoded)*2)return false;
|
||||
auto nibble=[](char c){return c>='0' && c<='9'?c-'0':c>='A' && c<='F'?c-'A'+10:c>='a' && c<='f'?c-'a'+10:-1;};
|
||||
auto p=reinterpret_cast<unsigned char*>(&extra);
|
||||
for(unsigned i=0;i<sizeof(extra);++i){int a=nibble(hex[2*i]),b=nibble(hex[2*i+1]);if(a<0 || b<0){std::memset(&extra,0,sizeof(extra));return false;}p[i]=(a<<4)|b;}
|
||||
extra.name[24]=0;return true;
|
||||
auto p=reinterpret_cast<unsigned char*>(&decoded);
|
||||
for(unsigned i=0;i<sizeof(decoded);++i){int a=nibble(hex[2*i]),b=nibble(hex[2*i+1]);if(a<0 || b<0)return false;p[i]=static_cast<unsigned char>((a<<4)|b);}
|
||||
if(decoded.name[24]!=0)return false;
|
||||
extra=decoded;return true;
|
||||
}
|
||||
|
||||
@@ -4,8 +4,17 @@
|
||||
#define ENABLE_AUTODETECT_INTERNAL_IP
|
||||
#define ENABLE_PROXY_IP
|
||||
#define ENABLE_PORT_SECURITY
|
||||
#define _IMPROVED_PACKET_ENCRYPTION_ // 패킷 암호화 개선
|
||||
#define _IMPROVED_PACKET_ENCRYPTION_
|
||||
//#define __AUCTION__
|
||||
#define __PET_SYSTEM__
|
||||
#define ENABLE_NEW_PET_SYSTEM
|
||||
#define ENABLE_ATTR_6TH_7TH
|
||||
#define __BL_67_ATTR__
|
||||
#define ENABLE_SPECIAL_STORAGE
|
||||
#define UNLOCK_INVENTORY_WORLDARD
|
||||
#define ENABLE_OFFLINESHOP_SYSTEM
|
||||
#ifdef ENABLE_OFFLINESHOP_SYSTEM
|
||||
#define ENABLE_SHOP_SEARCH_SYSTEM
|
||||
#endif
|
||||
#define __UDP_BLOCK__
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
#pragma once
|
||||
#include "gold_bounds.h"
|
||||
// Free NPC items are valid. Invalid or unrepresentable quotes never mutate output.
|
||||
inline bool PortShopQuote(int64_t price, bool otherEmpire, int64_t maximum, int64_t& quote) {
|
||||
const int multiplier = otherEmpire ? 3 : 1;
|
||||
if (price < 0 || maximum < 0 || price > maximum / multiplier) return false;
|
||||
quote = price * multiplier;
|
||||
return true;
|
||||
}
|
||||
inline bool PortShopSettlement(int64_t price, int rate, int64_t maximum, int64_t& tax, int64_t& proceeds) {
|
||||
if (price < 0 || price > maximum || rate < 0 || rate > 100) return false;
|
||||
// Quotient/remainder also keeps this valid if the configured maximum grows.
|
||||
tax = (price / 100) * rate + (price % 100) * rate / 100;
|
||||
proceeds = price - tax;
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
#pragma once
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <cstddef>
|
||||
#include <deque>
|
||||
#include <map>
|
||||
|
||||
// DB-main-thread-only ownership router for results from the SAME player async
|
||||
// FIFO. SQL worker threads never access this registry. Tokens are opaque integers
|
||||
// in pvUserData, never pointers to an actor, ticket object or reclaimed memory.
|
||||
namespace PortSQLFence {
|
||||
enum Kind : unsigned { Economy=0, Cube=1 };
|
||||
template<class Message> class Router {
|
||||
struct Ticket {Kind kind;uint32_t logical;};
|
||||
uint32_t next=0,maximum;
|
||||
std::size_t capacity;
|
||||
uint64_t failures=0;
|
||||
std::map<uint32_t,Ticket> pending;
|
||||
std::array<std::deque<Message*>,2> ready;
|
||||
void Fault(){if(failures!=UINT64_MAX)++failures;}
|
||||
public:
|
||||
explicit Router(uint32_t maxToken=UINT32_MAX,std::size_t limit=8192):maximum(maxToken),capacity(limit){}
|
||||
~Router(){Clear();}
|
||||
Router(const Router&)=delete;Router& operator=(const Router&)=delete;
|
||||
uint32_t Reserve(Kind kind,uint32_t logical) {
|
||||
if(unsigned(kind)>1||!logical||next>=maximum||pending.size()+ready[0].size()+ready[1].size()>=capacity)return 0;
|
||||
const auto token=++next;pending.emplace(token,Ticket{kind,logical});return token;
|
||||
}
|
||||
bool Complete(Message* message) {
|
||||
if(!message){Fault();return false;}
|
||||
const auto raw=reinterpret_cast<uintptr_t>(message->pvUserData);
|
||||
auto it=raw<=UINT32_MAX?pending.find(uint32_t(raw)):pending.end();
|
||||
if(it==pending.end()){delete message;Fault();return false;}
|
||||
const auto ticket=it->second;pending.erase(it);
|
||||
message->pvUserData=reinterpret_cast<void*>(uintptr_t(ticket.logical));
|
||||
ready[unsigned(ticket.kind)].push_back(message);return true;
|
||||
}
|
||||
Message* Pop(Kind kind) {
|
||||
if(unsigned(kind)>1||ready[unsigned(kind)].empty())return nullptr;
|
||||
auto* message=ready[unsigned(kind)].front();ready[unsigned(kind)].pop_front();return message;
|
||||
}
|
||||
uint64_t Failures()const{return failures;}
|
||||
void Clear() {
|
||||
pending.clear();for(auto& queue:ready){for(auto* message:queue)delete message;queue.clear();}
|
||||
// Never recycle a token during this DB process, even on connection reset.
|
||||
Fault();
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
#ifndef __INC_METIN_II_STL_H__
|
||||
#define __INC_METIN_II_STL_H__
|
||||
|
||||
#include <cctype>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <map>
|
||||
@@ -19,7 +20,7 @@
|
||||
inline void stl_lowers(std::string& rstRet)
|
||||
{
|
||||
for (size_t i = 0; i < rstRet.length(); ++i)
|
||||
rstRet[i] = tolower(rstRet[i]);
|
||||
rstRet[i] = static_cast<char>(std::tolower(static_cast<unsigned char>(rstRet[i])));
|
||||
}
|
||||
|
||||
struct stringhash
|
||||
|
||||
+326
-85
@@ -7,7 +7,7 @@
|
||||
typedef DWORD IDENT;
|
||||
|
||||
/**
|
||||
* @version 05/06/10 Bang2ni - Myshop Pricelist 관련 패킷 HEADER_XX_MYSHOP_PRICELIST_XXX 추가
|
||||
* @version 05/06/10 Bang2ni - Myshop Pricelist 관련 패킷 HEADER_XX_MYSHOP_PRICELIST_XXX 추가
|
||||
*/
|
||||
enum
|
||||
{
|
||||
@@ -105,8 +105,8 @@ enum
|
||||
HEADER_GD_BILLING_CHECK = 106,
|
||||
HEADER_GD_MALL_LOAD = 107,
|
||||
|
||||
HEADER_GD_MYSHOP_PRICELIST_UPDATE = 108, ///< 가격정보 갱신 요청
|
||||
HEADER_GD_MYSHOP_PRICELIST_REQ = 109, ///< 가격정보 리스트 요청
|
||||
HEADER_GD_MYSHOP_PRICELIST_UPDATE = 108, ///< 가격정보 갱신 요청
|
||||
HEADER_GD_MYSHOP_PRICELIST_REQ = 109, ///< 가격정보 리스트 요청
|
||||
|
||||
HEADER_GD_BLOCK_CHAT = 110,
|
||||
|
||||
@@ -117,21 +117,21 @@ enum
|
||||
// END_OF_PCBANG_IP_LIST_BY_AUTH
|
||||
|
||||
HEADER_GD_HAMMER_OF_TOR = 114,
|
||||
HEADER_GD_RELOAD_ADMIN = 115, ///<운영자 정보 요청
|
||||
HEADER_GD_BREAK_MARRIAGE = 116, ///< 결혼 파기
|
||||
HEADER_GD_ELECT_MONARCH = 117, ///< 군주 투표
|
||||
HEADER_GD_CANDIDACY = 118, ///< 군주 등록
|
||||
HEADER_GD_ADD_MONARCH_MONEY = 119, ///< 군주 돈 증가
|
||||
HEADER_GD_TAKE_MONARCH_MONEY = 120, ///< 군주 돈 감소
|
||||
HEADER_GD_COME_TO_VOTE = 121, ///< 표결
|
||||
HEADER_GD_RMCANDIDACY = 122, ///< 후보 제거 (운영자)
|
||||
HEADER_GD_SETMONARCH = 123, ///<군주설정 (운영자)
|
||||
HEADER_GD_RMMONARCH = 124, ///<군주삭제
|
||||
HEADER_GD_RELOAD_ADMIN = 115, ///<운영자 정보 요청
|
||||
HEADER_GD_BREAK_MARRIAGE = 116, ///< 결혼 파기
|
||||
HEADER_GD_ELECT_MONARCH = 117, ///< 군주 투표
|
||||
HEADER_GD_CANDIDACY = 118, ///< 군주 등록
|
||||
HEADER_GD_ADD_MONARCH_MONEY = 119, ///< 군주 돈 증가
|
||||
HEADER_GD_TAKE_MONARCH_MONEY = 120, ///< 군주 돈 감소
|
||||
HEADER_GD_COME_TO_VOTE = 121, ///< 표결
|
||||
HEADER_GD_RMCANDIDACY = 122, ///< 후보 제거 (운영자)
|
||||
HEADER_GD_SETMONARCH = 123, ///<군주설정 (운영자)
|
||||
HEADER_GD_RMMONARCH = 124, ///<군주삭제
|
||||
HEADER_GD_DEC_MONARCH_MONEY = 125,
|
||||
|
||||
HEADER_GD_CHANGE_MONARCH_LORD = 126,
|
||||
HEADER_GD_BLOCK_COUNTRY_IP = 127, // 광대역 IP-Block
|
||||
HEADER_GD_BLOCK_EXCEPTION = 128, // 광대역 IP-Block 예외
|
||||
HEADER_GD_BLOCK_COUNTRY_IP = 127, // 광대역 IP-Block
|
||||
HEADER_GD_BLOCK_EXCEPTION = 128, // 광대역 IP-Block 예외
|
||||
|
||||
HEADER_GD_REQ_CHANGE_GUILD_MASTER = 129,
|
||||
|
||||
@@ -140,7 +140,7 @@ enum
|
||||
HEADER_GD_UPDATE_HORSE_NAME = 131,
|
||||
HEADER_GD_REQ_HORSE_NAME = 132,
|
||||
|
||||
HEADER_GD_DC = 133, // Login Key를 지움
|
||||
HEADER_GD_DC = 133, // Login Key를 지움
|
||||
|
||||
HEADER_GD_VALID_LOGOUT = 134,
|
||||
|
||||
@@ -156,6 +156,9 @@ enum
|
||||
|
||||
HEADER_GD_UPDATE_CHANNELSTATUS = 139,
|
||||
HEADER_GD_REQUEST_CHANNELSTATUS = 140,
|
||||
#ifdef ENABLE_OFFLINESHOP_SYSTEM
|
||||
HEADER_GD_OFFLINESHOP = 146,
|
||||
#endif
|
||||
|
||||
HEADER_GD_SETUP = 0xff,
|
||||
|
||||
@@ -203,6 +206,9 @@ enum
|
||||
HEADER_DG_PARTY_STATE_CHANGE = 63,
|
||||
HEADER_DG_PARTY_HEAL_USE = 64,
|
||||
HEADER_DG_PARTY_SET_MEMBER_LEVEL = 65,
|
||||
#ifdef ENABLE_OFFLINESHOP_SYSTEM
|
||||
HEADER_DG_OFFLINESHOP = 66,
|
||||
#endif
|
||||
|
||||
HEADER_DG_TIME = 90,
|
||||
HEADER_DG_ITEM_ID_RANGE = 91,
|
||||
@@ -258,23 +264,23 @@ enum
|
||||
HEADER_DG_WEDDING_START = 155,
|
||||
HEADER_DG_WEDDING_END = 156,
|
||||
|
||||
HEADER_DG_MYSHOP_PRICELIST_RES = 157, ///< 가격정보 리스트 응답
|
||||
HEADER_DG_RELOAD_ADMIN = 158, ///< 운영자 정보 리로드
|
||||
HEADER_DG_BREAK_MARRIAGE = 159, ///< 결혼 파기
|
||||
HEADER_DG_ELECT_MONARCH = 160, ///< 군주 투표
|
||||
HEADER_DG_CANDIDACY = 161, ///< 군주 등록
|
||||
HEADER_DG_ADD_MONARCH_MONEY = 162, ///< 군주 돈 증가
|
||||
HEADER_DG_TAKE_MONARCH_MONEY = 163, ///< 군주 돈 감소
|
||||
HEADER_DG_COME_TO_VOTE = 164, ///< 표결
|
||||
HEADER_DG_RMCANDIDACY = 165, ///< 후보 제거 (운영자)
|
||||
HEADER_DG_SETMONARCH = 166, ///<군주설정 (운영자)
|
||||
HEADER_DG_RMMONARCH = 167, ///<군주삭제
|
||||
HEADER_DG_MYSHOP_PRICELIST_RES = 157, ///< 가격정보 리스트 응답
|
||||
HEADER_DG_RELOAD_ADMIN = 158, ///< 운영자 정보 리로드
|
||||
HEADER_DG_BREAK_MARRIAGE = 159, ///< 결혼 파기
|
||||
HEADER_DG_ELECT_MONARCH = 160, ///< 군주 투표
|
||||
HEADER_DG_CANDIDACY = 161, ///< 군주 등록
|
||||
HEADER_DG_ADD_MONARCH_MONEY = 162, ///< 군주 돈 증가
|
||||
HEADER_DG_TAKE_MONARCH_MONEY = 163, ///< 군주 돈 감소
|
||||
HEADER_DG_COME_TO_VOTE = 164, ///< 표결
|
||||
HEADER_DG_RMCANDIDACY = 165, ///< 후보 제거 (운영자)
|
||||
HEADER_DG_SETMONARCH = 166, ///<군주설정 (운영자)
|
||||
HEADER_DG_RMMONARCH = 167, ///<군주삭제
|
||||
HEADER_DG_DEC_MONARCH_MONEY = 168,
|
||||
|
||||
HEADER_DG_CHANGE_MONARCH_LORD_ACK = 169,
|
||||
HEADER_DG_UPDATE_MONARCH_INFO = 170,
|
||||
HEADER_DG_BLOCK_COUNTRY_IP = 171, // 광대역 IP-Block
|
||||
HEADER_DG_BLOCK_EXCEPTION = 172, // 광대역 IP-Block 예외 account
|
||||
HEADER_DG_BLOCK_COUNTRY_IP = 171, // 광대역 IP-Block
|
||||
HEADER_DG_BLOCK_EXCEPTION = 172, // 광대역 IP-Block 예외 account
|
||||
|
||||
HEADER_DG_ACK_CHANGE_GUILD_MASTER = 173,
|
||||
|
||||
@@ -394,7 +400,7 @@ typedef struct SPlayerItem
|
||||
DWORD count;
|
||||
|
||||
DWORD vnum;
|
||||
long alSockets[ITEM_SOCKET_MAX_NUM]; // 소켓번호
|
||||
long alSockets[ITEM_SOCKET_MAX_NUM]; // 소켓번호
|
||||
|
||||
TPlayerItemAttribute aAttr[ITEM_ATTRIBUTE_MAX_NUM];
|
||||
|
||||
@@ -439,7 +445,7 @@ typedef struct SPlayerTable
|
||||
short st, ht, dx, iq;
|
||||
|
||||
DWORD exp;
|
||||
INT gold;
|
||||
int64_t gold;
|
||||
|
||||
BYTE dir;
|
||||
INT x, y, z;
|
||||
@@ -488,6 +494,13 @@ typedef struct SPlayerTable
|
||||
DWORD logoff_interval;
|
||||
|
||||
int aiPremiumTimes[PREMIUM_MAX_NUM];
|
||||
|
||||
#ifdef UNLOCK_INVENTORY_WORLDARD
|
||||
DWORD inventory_unlock[UNLOCK_INVENTORY_MAX];
|
||||
#endif
|
||||
#ifdef ENABLE_OFFLINESHOP_SYSTEM
|
||||
unsigned long long shopFlag;
|
||||
#endif
|
||||
} TPlayerTable;
|
||||
|
||||
typedef struct SMobSkillLevel
|
||||
@@ -610,10 +623,11 @@ typedef struct SShopItemTable
|
||||
DWORD vnum;
|
||||
BYTE count;
|
||||
|
||||
TItemPos pos; // PC 상점에만 이용
|
||||
DWORD price; // PC, shop_table_ex.txt 상점에만 이용
|
||||
BYTE display_pos; // PC, shop_table_ex.txt 상점에만 이용, 보일 위치.
|
||||
TItemPos pos; // PC 상점에만 이용
|
||||
int64_t price; // PC, shop_table_ex.txt 상점에만 이용
|
||||
BYTE display_pos; // PC, shop_table_ex.txt 상점에만 이용, 보일 위치.
|
||||
} TShopItemTable;
|
||||
static_assert(sizeof(TShopItemTable)==17,"gold64 private shop wire size");
|
||||
|
||||
typedef struct SShopTable
|
||||
{
|
||||
@@ -676,12 +690,12 @@ typedef struct SItemTable : public SEntityTable
|
||||
BYTE bSpecular;
|
||||
BYTE bGainSocketPct;
|
||||
|
||||
short int sAddonType; // 기본 속성
|
||||
short int sAddonType; // 기본 속성
|
||||
|
||||
// 아래 limit flag들은 realtime에 체크 할 일이 많고, 아이템 VNUM당 고정된 값인데,
|
||||
// 현재 구조대로 매번 아이템마다 필요한 경우에 LIMIT_MAX_NUM까지 루프돌면서 체크하는 부하가 커서 미리 저장 해 둠.
|
||||
char cLimitRealTimeFirstUseIndex; // 아이템 limit 필드값 중에서 LIMIT_REAL_TIME_FIRST_USE 플래그의 위치 (없으면 -1)
|
||||
char cLimitTimerBasedOnWearIndex; // 아이템 limit 필드값 중에서 LIMIT_TIMER_BASED_ON_WEAR 플래그의 위치 (없으면 -1)
|
||||
// 아래 limit flag들은 realtime에 체크 할 일이 많고, 아이템 VNUM당 고정된 값인데,
|
||||
// 현재 구조대로 매번 아이템마다 필요한 경우에 LIMIT_MAX_NUM까지 루프돌면서 체크하는 부하가 커서 미리 저장 해 둠.
|
||||
char cLimitRealTimeFirstUseIndex; // 아이템 limit 필드값 중에서 LIMIT_REAL_TIME_FIRST_USE 플래그의 위치 (없으면 -1)
|
||||
char cLimitTimerBasedOnWearIndex; // 아이템 limit 필드값 중에서 LIMIT_TIMER_BASED_ON_WEAR 플래그의 위치 (없으면 -1)
|
||||
|
||||
} TItemTable;
|
||||
|
||||
@@ -719,7 +733,7 @@ typedef struct SPlayerLoadPacket
|
||||
{
|
||||
DWORD account_id;
|
||||
DWORD player_id;
|
||||
BYTE account_index; /* account 에서의 위치 */
|
||||
BYTE account_index; /* account 에서의 위치 */
|
||||
} TPlayerLoadPacket;
|
||||
|
||||
typedef struct SPlayerCreatePacket
|
||||
@@ -758,7 +772,7 @@ typedef struct SSafeboxTable
|
||||
{
|
||||
DWORD dwID;
|
||||
BYTE bSize;
|
||||
DWORD dwGold;
|
||||
int64_t dwGold;
|
||||
WORD wItemCount;
|
||||
} TSafeboxTable;
|
||||
|
||||
@@ -796,9 +810,9 @@ typedef struct SEmpireSelectPacket
|
||||
typedef struct SPacketGDSetup
|
||||
{
|
||||
char szPublicIP[16]; // Public IP which listen to users
|
||||
BYTE bChannel; // 채널
|
||||
WORD wListenPort; // 클라이언트가 접속하는 포트 번호
|
||||
WORD wP2PPort; // 서버끼리 연결 시키는 P2P 포트 번호
|
||||
BYTE bChannel; // 채널
|
||||
WORD wListenPort; // 클라이언트가 접속하는 포트 번호
|
||||
WORD wP2PPort; // 서버끼리 연결 시키는 P2P 포트 번호
|
||||
long alMaps[32];
|
||||
DWORD dwLoginCount;
|
||||
BYTE bAuthServer;
|
||||
@@ -976,8 +990,8 @@ typedef struct SPacketGuildWar
|
||||
long lInitialScore;
|
||||
} TPacketGuildWar;
|
||||
|
||||
// Game -> DB : 상대적 변화값
|
||||
// DB -> Game : 토탈된 최종값
|
||||
// Game -> DB : 상대적 변화값
|
||||
// DB -> Game : 토탈된 최종값
|
||||
typedef struct SPacketGuildWarScore
|
||||
{
|
||||
DWORD dwGuildGainPoint;
|
||||
@@ -998,8 +1012,8 @@ typedef struct SRefineTable
|
||||
//DWORD result_vnum;
|
||||
DWORD id;
|
||||
BYTE material_count;
|
||||
int cost; // 소요 비용
|
||||
int prob; // 확률
|
||||
int cost; // 소요 비용
|
||||
int prob; // 확률
|
||||
TRefineMaterial materials[REFINE_MATERIAL_MAX_NUM];
|
||||
} TRefineTable;
|
||||
|
||||
@@ -1084,14 +1098,14 @@ typedef struct SPacketGDLoginByKey
|
||||
} TPacketGDLoginByKey;
|
||||
|
||||
/**
|
||||
* @version 05/06/08 Bang2ni - 지속시간 추가
|
||||
* @version 05/06/08 Bang2ni - 지속시간 추가
|
||||
*/
|
||||
typedef struct SPacketGiveGuildPriv
|
||||
{
|
||||
BYTE type;
|
||||
int value;
|
||||
DWORD guild_id;
|
||||
time_t duration_sec; ///< 지속시간
|
||||
time_t duration_sec; ///< 지속시간
|
||||
} TPacketGiveGuildPriv;
|
||||
typedef struct SPacketGiveEmpirePriv
|
||||
{
|
||||
@@ -1126,7 +1140,7 @@ typedef struct SPacketDGChangeCharacterPriv
|
||||
} TPacketDGChangeCharacterPriv;
|
||||
|
||||
/**
|
||||
* @version 05/06/08 Bang2ni - 지속시간 추가
|
||||
* @version 05/06/08 Bang2ni - 지속시간 추가
|
||||
*/
|
||||
typedef struct SPacketDGChangeGuildPriv
|
||||
{
|
||||
@@ -1134,7 +1148,7 @@ typedef struct SPacketDGChangeGuildPriv
|
||||
int value;
|
||||
DWORD guild_id;
|
||||
BYTE bLog;
|
||||
time_t end_time_sec; ///< 지속시간
|
||||
time_t end_time_sec; ///< 지속시간
|
||||
} TPacketDGChangeGuildPriv;
|
||||
|
||||
typedef struct SPacketDGChangeEmpirePriv
|
||||
@@ -1150,31 +1164,31 @@ typedef struct SPacketMoneyLog
|
||||
{
|
||||
BYTE type;
|
||||
DWORD vnum;
|
||||
INT gold;
|
||||
int64_t gold;
|
||||
} TPacketMoneyLog;
|
||||
|
||||
typedef struct SPacketGDGuildMoney
|
||||
{
|
||||
DWORD dwGuild;
|
||||
INT iGold;
|
||||
int64_t iGold;
|
||||
} TPacketGDGuildMoney;
|
||||
|
||||
typedef struct SPacketDGGuildMoneyChange
|
||||
{
|
||||
DWORD dwGuild;
|
||||
INT iTotalGold;
|
||||
int64_t iTotalGold;
|
||||
} TPacketDGGuildMoneyChange;
|
||||
|
||||
typedef struct SPacketDGGuildMoneyWithdraw
|
||||
{
|
||||
DWORD dwGuild;
|
||||
INT iChangeGold;
|
||||
int64_t iChangeGold;
|
||||
} TPacketDGGuildMoneyWithdraw;
|
||||
|
||||
typedef struct SPacketGDGuildMoneyWithdrawGiveReply
|
||||
{
|
||||
DWORD dwGuild;
|
||||
INT iChangeGold;
|
||||
int64_t iChangeGold;
|
||||
BYTE bGiveSuccess;
|
||||
} TPacketGDGuildMoneyWithdrawGiveReply;
|
||||
|
||||
@@ -1315,27 +1329,27 @@ typedef struct
|
||||
DWORD dwPID2;
|
||||
} TPacketWeddingEnd;
|
||||
|
||||
/// 개인상점 가격정보의 헤더. 가변 패킷으로 이 뒤에 byCount 만큼의 TItemPriceInfo 가 온다.
|
||||
/// 개인상점 가격정보의 헤더. 가변 패킷으로 이 뒤에 byCount 만큼의 TItemPriceInfo 가 온다.
|
||||
typedef struct SPacketMyshopPricelistHeader
|
||||
{
|
||||
DWORD dwOwnerID; ///< 가격정보를 가진 플레이어 ID
|
||||
BYTE byCount; ///< 가격정보 갯수
|
||||
DWORD dwOwnerID; ///< 가격정보를 가진 플레이어 ID
|
||||
BYTE byCount; ///< 가격정보 갯수
|
||||
} TPacketMyshopPricelistHeader;
|
||||
|
||||
/// 개인상점의 단일 아이템에 대한 가격정보
|
||||
/// 개인상점의 단일 아이템에 대한 가격정보
|
||||
typedef struct SItemPriceInfo
|
||||
{
|
||||
DWORD dwVnum; ///< 아이템 vnum
|
||||
DWORD dwPrice; ///< 가격
|
||||
DWORD dwVnum; ///< 아이템 vnum
|
||||
DWORD dwPrice; ///< 가격
|
||||
} TItemPriceInfo;
|
||||
|
||||
/// 개인상점 아이템 가격정보 리스트 테이블
|
||||
/// 개인상점 아이템 가격정보 리스트 테이블
|
||||
typedef struct SItemPriceListTable
|
||||
{
|
||||
DWORD dwOwnerID; ///< 가격정보를 가진 플레이어 ID
|
||||
BYTE byCount; ///< 가격정보 리스트의 갯수
|
||||
DWORD dwOwnerID; ///< 가격정보를 가진 플레이어 ID
|
||||
BYTE byCount; ///< 가격정보 리스트의 갯수
|
||||
|
||||
TItemPriceInfo aPriceInfo[SHOP_PRICELIST_MAX_NUM]; ///< 가격정보 리스트
|
||||
TItemPriceInfo aPriceInfo[SHOP_PRICELIST_MAX_NUM]; ///< 가격정보 리스트
|
||||
} TItemPriceListTable;
|
||||
|
||||
typedef struct
|
||||
@@ -1356,12 +1370,12 @@ typedef struct SPacketPCBangIP
|
||||
//ADMIN_MANAGER
|
||||
typedef struct TAdminInfo
|
||||
{
|
||||
int m_ID; //고유ID
|
||||
char m_szAccount[32]; //계정
|
||||
char m_szName[32]; //캐릭터이름
|
||||
char m_szContactIP[16]; //접근아이피
|
||||
char m_szServerIP[16]; //서버아이피
|
||||
int m_Authority; //권한
|
||||
int m_ID; //고유ID
|
||||
char m_szAccount[32]; //계정
|
||||
char m_szName[32]; //캐릭터이름
|
||||
char m_szContactIP[16]; //접근아이피
|
||||
char m_szServerIP[16]; //서버아이피
|
||||
int m_Authority; //권한
|
||||
} tAdminInfo;
|
||||
//END_ADMIN_MANAGER
|
||||
|
||||
@@ -1382,20 +1396,20 @@ typedef struct SPacketReloadAdmin
|
||||
|
||||
typedef struct TMonarchInfo
|
||||
{
|
||||
DWORD pid[4]; // 군주의 PID
|
||||
int64_t money[4]; // 군주의 별개 돈
|
||||
char name[4][32]; // 군주의 이름
|
||||
char date[4][32]; // 군주 등록 날짜
|
||||
DWORD pid[4]; // 군주의 PID
|
||||
int64_t money[4]; // 군주의 별개 돈
|
||||
char name[4][32]; // 군주의 이름
|
||||
char date[4][32]; // 군주 등록 날짜
|
||||
} MonarchInfo;
|
||||
|
||||
typedef struct TMonarchElectionInfo
|
||||
{
|
||||
DWORD pid; // 투표 한사람 PID
|
||||
DWORD selectedpid; // 투표 당한 PID ( 군주 참가자 )
|
||||
char date[32]; // 투표 날짜
|
||||
DWORD pid; // 투표 한사람 PID
|
||||
DWORD selectedpid; // 투표 당한 PID ( 군주 참가자 )
|
||||
char date[32]; // 투표 날짜
|
||||
} MonarchElectionInfo;
|
||||
|
||||
// 군주 출마자
|
||||
// 군주 출마자
|
||||
typedef struct tMonarchCandidacy
|
||||
{
|
||||
DWORD pid;
|
||||
@@ -1467,14 +1481,14 @@ typedef struct tNeedLoginLogInfo
|
||||
DWORD dwPlayerID;
|
||||
} TPacketNeedLoginLogInfo;
|
||||
|
||||
//독일 선물 알림 기능 테스트용 패킷 정보
|
||||
//독일 선물 알림 기능 테스트용 패킷 정보
|
||||
typedef struct tItemAwardInformer
|
||||
{
|
||||
char login[LOGIN_MAX_LEN + 1];
|
||||
char command[20]; //명령어
|
||||
unsigned int vnum; //아이템
|
||||
char command[20]; //명령어
|
||||
unsigned int vnum; //아이템
|
||||
} TPacketItemAwardInfromer;
|
||||
// 선물 알림 기능 삭제용 패킷 정보
|
||||
// 선물 알림 기능 삭제용 패킷 정보
|
||||
typedef struct tDeleteAwardID
|
||||
{
|
||||
DWORD dwID;
|
||||
@@ -1532,5 +1546,232 @@ struct TSwitchbottAttributeTable
|
||||
int max_value;
|
||||
};
|
||||
|
||||
#ifdef ENABLE_NEW_PET_SYSTEM
|
||||
enum EPetOptions
|
||||
{
|
||||
EPetOption_Followable = 1 << 0,
|
||||
EPetOption_Mountable = 1 << 1,
|
||||
EPetOption_Summonable = 1 << 2,
|
||||
EPetOption_Combatable = 1 << 3,
|
||||
};
|
||||
|
||||
enum m_petMisc
|
||||
{
|
||||
NORMAL_PET = 0,
|
||||
NORMAL_LEVEL_PET = 1,
|
||||
};
|
||||
|
||||
enum EPetPointTypes
|
||||
{
|
||||
POINT_PET_DURATION = 0,
|
||||
POINT_PET_LEVEL = 1,
|
||||
POINT_PET_EXP = 2,
|
||||
POINT_PET_EVOLVE = 3,
|
||||
POINT_PET_SKILLCOUNT = 4,
|
||||
|
||||
POINT_PET_BONUS_1 = 5,
|
||||
POINT_PET_BONUS_2 = 6,
|
||||
POINT_PET_BONUS_3 = 7,
|
||||
|
||||
POINT_PET_SKILL_INDEX_1 = 100,
|
||||
POINT_PET_SKILL_INDEX_2,
|
||||
POINT_PET_SKILL_INDEX_3,
|
||||
POINT_PET_SKILL_INDEX_4,
|
||||
POINT_PET_SKILL_INDEX_5,
|
||||
POINT_PET_SKILL_INDEX_6,
|
||||
POINT_PET_SKILL_INDEX_7,
|
||||
POINT_PET_SKILL_INDEX_8,
|
||||
POINT_PET_SKILL_INDEX_9,
|
||||
POINT_PET_SKILL_INDEX_10,
|
||||
POINT_PET_SKILL_INDEX_11,
|
||||
POINT_PET_SKILL_INDEX_12,
|
||||
POINT_PET_SKILL_INDEX_13,
|
||||
POINT_PET_SKILL_INDEX_14,
|
||||
POINT_PET_SKILL_INDEX_15 = 114,
|
||||
|
||||
POINT_PET_SKILL_LEVEL_1 = 150,
|
||||
POINT_PET_SKILL_LEVEL_2,
|
||||
POINT_PET_SKILL_LEVEL_3,
|
||||
POINT_PET_SKILL_LEVEL_4,
|
||||
POINT_PET_SKILL_LEVEL_5,
|
||||
POINT_PET_SKILL_LEVEL_6,
|
||||
POINT_PET_SKILL_LEVEL_7,
|
||||
POINT_PET_SKILL_LEVEL_8,
|
||||
POINT_PET_SKILL_LEVEL_9,
|
||||
POINT_PET_SKILL_LEVEL_10,
|
||||
POINT_PET_SKILL_LEVEL_11,
|
||||
POINT_PET_SKILL_LEVEL_12,
|
||||
POINT_PET_SKILL_LEVEL_13,
|
||||
POINT_PET_SKILL_LEVEL_14,
|
||||
POINT_PET_SKILL_LEVEL_15 = 164,
|
||||
};
|
||||
|
||||
typedef struct SPetApply
|
||||
{
|
||||
BYTE bType;
|
||||
long lValue;
|
||||
} TPetApply;
|
||||
|
||||
typedef struct SPetSkill
|
||||
{
|
||||
BYTE bType;
|
||||
short sLevel;
|
||||
} TPetSkill;
|
||||
#endif
|
||||
|
||||
#ifdef ENABLE_OFFLINESHOP_SYSTEM
|
||||
typedef struct offline_shop_item
|
||||
{
|
||||
DWORD id;
|
||||
DWORD owner_id;
|
||||
BYTE pos;
|
||||
int count;
|
||||
long long price;
|
||||
DWORD vnum;
|
||||
long alSockets[ITEM_SOCKET_MAX_NUM];
|
||||
TPlayerItemAttribute aAttr[ITEM_ATTRIBUTE_MAX_NUM];
|
||||
BYTE status;
|
||||
char szBuyerName[CHARACTER_NAME_MAX_LEN+1];
|
||||
#ifdef ENABLE_CHANGELOOK_SYSTEM
|
||||
DWORD transmutation;
|
||||
#endif
|
||||
char szOwnerName[CHARACTER_NAME_MAX_LEN+1];
|
||||
PortItemExtra extra;
|
||||
} OFFLINE_SHOP_ITEM;
|
||||
|
||||
typedef struct ShopLog {
|
||||
char name[CHARACTER_NAME_MAX_LEN+1];
|
||||
char date[25];
|
||||
DWORD itemVnum;
|
||||
DWORD itemCount;
|
||||
long long price;
|
||||
} TShopLog;
|
||||
|
||||
typedef struct SShopDecoration {
|
||||
char sign[SHOP_SIGN_MAX_LEN + 1];
|
||||
DWORD owner_id;
|
||||
BYTE vnum;
|
||||
BYTE type;
|
||||
} TShopDecoration;
|
||||
|
||||
typedef struct SGDOfflineShopCreate
|
||||
{
|
||||
DWORD owner_id;
|
||||
char owner_name[CHARACTER_NAME_MAX_LEN+1];
|
||||
char sign[SHOP_SIGN_MAX_LEN + 1];
|
||||
long x;
|
||||
long y;
|
||||
long z;
|
||||
DWORD mapindex;
|
||||
DWORD type;
|
||||
BYTE channel;
|
||||
unsigned long long slotflag;
|
||||
OFFLINE_SHOP_ITEM items[OFFLINE_SHOP_HOST_ITEM_MAX_NUM];
|
||||
long long price;
|
||||
ShopLog log[OFFLINE_SHOP_HOST_ITEM_MAX_NUM];
|
||||
int time;
|
||||
} TOfflineShop;
|
||||
|
||||
typedef struct SOfflineShopBuy
|
||||
{
|
||||
OFFLINE_SHOP_ITEM item;
|
||||
DWORD customer_id;
|
||||
char customer_name[CHARACTER_NAME_MAX_LEN + 1];
|
||||
ShopLog log;
|
||||
int log_index;
|
||||
} TOfflineShopBuy;
|
||||
|
||||
typedef struct SOfflineShopChangeTitle
|
||||
{
|
||||
DWORD owner_id;
|
||||
char sign[SHOP_SIGN_MAX_LEN + 1];
|
||||
} TOfflineShopChangeTitle;
|
||||
|
||||
typedef struct SOfflineShopItemTable
|
||||
{
|
||||
DWORD vnum;
|
||||
int count;
|
||||
TItemPos pos;
|
||||
long long price;
|
||||
BYTE display_pos;
|
||||
} TOfflineShopItemTable;
|
||||
|
||||
typedef struct SOfflineShopAddItem
|
||||
{
|
||||
TItemPos bPos;
|
||||
BYTE bDisplayPos;
|
||||
long long lPrice;
|
||||
} TOfflineShopAddItem;
|
||||
|
||||
typedef struct SOfflineShopOpenSlot
|
||||
{
|
||||
DWORD owner_id;
|
||||
unsigned long long flag;
|
||||
} TOfflineShopOpenSlot;
|
||||
|
||||
typedef struct SOfflineShopBackItem
|
||||
{
|
||||
DWORD owner_id;
|
||||
OFFLINE_SHOP_ITEM items[OFFLINE_SHOP_HOST_ITEM_MAX_NUM];
|
||||
} TOfflineShopBackItem;
|
||||
|
||||
enum {
|
||||
// db
|
||||
CREATE_OFFLINESHOP,
|
||||
DESTROY_OFFLINESHOP,
|
||||
REMOVE_ITEM,
|
||||
ADD_ITEM,
|
||||
BUY_ITEM,
|
||||
WITHDRAW_MONEY,
|
||||
CHANGE_TITLE,
|
||||
CLEAR_LOG,
|
||||
CHANGE_DECORATION,
|
||||
CHANGE_OPEN_SLOT,
|
||||
TIME_DONE,
|
||||
GET_BACK_ITEM,
|
||||
ADD_TIME,
|
||||
};
|
||||
|
||||
struct shop_decoration {
|
||||
BYTE subheader;
|
||||
TShopDecoration decoration;
|
||||
};
|
||||
|
||||
struct shop_create {
|
||||
BYTE subheader;
|
||||
TOfflineShop offlineshop;
|
||||
};
|
||||
|
||||
struct shop_buy {
|
||||
BYTE subheader;
|
||||
TOfflineShopBuy buyItem;
|
||||
};
|
||||
|
||||
struct shop_title {
|
||||
BYTE subheader;
|
||||
TOfflineShopChangeTitle title;
|
||||
};
|
||||
|
||||
struct shop_owner {
|
||||
BYTE subheader;
|
||||
DWORD owner_id;
|
||||
};
|
||||
|
||||
struct shop_item {
|
||||
BYTE subheader;
|
||||
OFFLINE_SHOP_ITEM item;
|
||||
};
|
||||
|
||||
struct shop_slot {
|
||||
BYTE subheader;
|
||||
TOfflineShopOpenSlot ch;
|
||||
};
|
||||
|
||||
struct shop_back {
|
||||
BYTE subheader;
|
||||
TOfflineShopBackItem back;
|
||||
};
|
||||
#endif
|
||||
|
||||
#pragma pack()
|
||||
#endif
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#include <cerrno>
|
||||
#include <cstdlib>
|
||||
/*----- atoi function -----*/
|
||||
inline bool str_to_number (bool& out, const char *in)
|
||||
{
|
||||
@@ -73,10 +75,17 @@ inline bool str_to_number (unsigned long& out, const char *in)
|
||||
|
||||
inline bool str_to_number (long long& out, const char *in)
|
||||
{
|
||||
if (0==in || 0==in[0]) return false;
|
||||
|
||||
out = (long long) strtoull(in, NULL, 10);
|
||||
return true;
|
||||
if(!in || !*in)return false;
|
||||
errno=0;char* end=NULL;const long long value=strtoll(in,&end,10);
|
||||
if(errno==ERANGE || end==in || *end)return false;
|
||||
out=value;return true;
|
||||
}
|
||||
inline bool str_to_number (unsigned long long& out, const char *in)
|
||||
{
|
||||
if(!in || !*in || ((*in<'0'||*in>'9')&&*in!='+'))return false;
|
||||
errno=0;char* end=NULL;const unsigned long long value=strtoull(in,&end,10);
|
||||
if(errno==ERANGE || end==in || *end)return false;
|
||||
out=value;return true;
|
||||
}
|
||||
|
||||
inline bool str_to_number (float& out, const char *in)
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
|
||||
// The DB boot stream prefixes each table with two WORDs. Its transport accepts
|
||||
// an int byte length, so validate every count/product before emitting any bytes.
|
||||
class PortBootSizer {
|
||||
uint64_t bytes_;
|
||||
bool valid_;
|
||||
public:
|
||||
explicit PortBootSizer(uint64_t fixed):bytes_(fixed),valid_(fixed<=INT32_MAX){}
|
||||
bool Add(uint64_t count,uint64_t stride) {
|
||||
if(!valid_ || count>UINT16_MAX || stride>UINT16_MAX ||
|
||||
bytes_>INT32_MAX-4 || (count && stride>(INT32_MAX-4-bytes_)/count)) {
|
||||
valid_=false;return false;
|
||||
}
|
||||
bytes_+=4+count*stride;return true;
|
||||
}
|
||||
bool Valid()const{return valid_;}
|
||||
uint32_t Bytes()const{return valid_?static_cast<uint32_t>(bytes_):0;}
|
||||
};
|
||||
@@ -6,6 +6,7 @@
|
||||
#include "ItemAwardManager.h"
|
||||
#include "../../common/ava2_itemshop.h"
|
||||
#include "../../common/point_drop.h"
|
||||
#include <cerrno>
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
#include <cctype>
|
||||
@@ -57,8 +58,21 @@ void reply(CPeer* peer,DWORD handle,const Ava2ShopRequest& request,const std::ve
|
||||
Ava2ShopReply h={request.account,request.player,uint32_t(out.size())};
|
||||
peer->EncodeHeader(76,handle,sizeof(h)+out.size());peer->Encode(&h,sizeof(h));peer->Encode(out.data(),out.size());
|
||||
}
|
||||
bool productNumber(const char* text,int64_t& value,int64_t minimum,int64_t maximum) {
|
||||
if(!text || !*text)return false;
|
||||
const char* digits=text;if(*digits=='-' && minimum<0)++digits;
|
||||
if(!*digits)return false;for(const char* p=digits;*p;++p)if(*p<'0'||*p>'9')return false;
|
||||
errno=0;char* end=nullptr;const long long parsed=strtoll(text,&end,10);
|
||||
if(errno==ERANGE || *end || parsed<minimum || parsed>maximum)return false;
|
||||
value=parsed;return true;
|
||||
}
|
||||
Ava2ShopProduct product(MYSQL_ROW r) {
|
||||
Ava2ShopProduct p={};p.id=strtoul(r[0],0,10);p.vnum=strtoul(r[1],0,10);p.price=strtoll(r[2],0,10);p.discount=atoi(r[3]);p.expiry=atoi(r[4]);p.added=atoi(r[5]);p.sold=strtoll(r[6],0,10);p.weekly=atoi(r[7]);p.monthly=atoi(r[8]);p.stock=atoi(r[9]);return p;
|
||||
Ava2ShopProduct p={};int64_t n[10]={};
|
||||
const int64_t minimum[10]={1,1,0,0,0,0,0,0,0,-1};
|
||||
const int64_t maximum[10]={UINT32_MAX,UINT32_MAX,1000000000000LL,100,INT32_MAX,INT32_MAX,INT64_MAX,INT32_MAX,INT32_MAX,INT32_MAX};
|
||||
if(!r)return p;
|
||||
for(unsigned i=0;i<10;++i)if(!productNumber(r[i],n[i],minimum[i],maximum[i]))return p;
|
||||
p.id=static_cast<uint32_t>(n[0]);p.vnum=static_cast<uint32_t>(n[1]);p.price=n[2];p.discount=static_cast<uint8_t>(n[3]);p.expiry=static_cast<int32_t>(n[4]);p.added=static_cast<int32_t>(n[5]);p.sold=n[6];p.weekly=static_cast<int32_t>(n[7]);p.monthly=static_cast<int32_t>(n[8]);p.stock=static_cast<int32_t>(n[9]);return p;
|
||||
}
|
||||
const char* fields="id,itemVnum,itemPrice,discount,IFNULL(UNIX_TIMESTAMP(offerTime),0),IFNULL(UNIX_TIMESTAMP(addedTime),0),sellCount,week_limit,month_limit,maxSellCount";
|
||||
bool valid(const Ava2ShopProduct& p) {return p.id && p.vnum && p.price>=0 && p.price<=1000000000000LL && p.discount<=100 && p.weekly>=0 && p.monthly>=0 && p.stock>=-1;}
|
||||
@@ -76,29 +90,41 @@ void CClientManager::Ava2ItemShop(CPeer* peer,DWORD handle,const char* data,DWOR
|
||||
auto mob=std::find_if(m_vec_mobTable.begin(),m_vec_mobTable.end(),[&](const TMobTable& m){return m.dwVnum==r.product;});
|
||||
const bool validMob=mob!=m_vec_mobTable.end() && (mob->bType==0 || mob->bType==2);
|
||||
const auto rule=PortPointRule([&](const std::string& key){auto it=m_map_lEventFlag.find(key);return it==m_map_lEventFlag.end()?0:int(it->second);},validMob && mob->bType==2);
|
||||
auto engine=query("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='port_point_rewards' AND ENGINE='InnoDB'");
|
||||
if(validMob && !adb.empty() && transactional(adb) && ok(engine) && engine->Get()->uiNumRows==1 && atoi(mysql_fetch_row(engine->Get()->pSQLResult)[0])==1) {
|
||||
// Reward replay must remain available after catalogue/mob/rule changes. Only
|
||||
// the two tables participating in this economic transaction are prerequisites.
|
||||
auto engine=adb.empty()?Query():query("SELECT COUNT(*) FROM information_schema.tables WHERE ENGINE='InnoDB' AND ((TABLE_SCHEMA=DATABASE() AND TABLE_NAME='port_point_rewards') OR (TABLE_SCHEMA='"+adb.substr(1,adb.size()-2)+"' AND TABLE_NAME='account'))");
|
||||
if(!adb.empty() && ok(engine) && engine->Get()->uiNumRows==1 && atoi(mysql_fetch_row(engine->Get()->pSQLResult)[0])==2) {
|
||||
Transaction tx;
|
||||
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) {
|
||||
if(ok(wallet) && wallet->Get()->uiNumRows==0)status=2; // Deleted account: terminal, never retry a new award.
|
||||
else if(ok(wallet) && wallet->Get()->uiNumRows==1) {
|
||||
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)+"'");
|
||||
auto previous=query("SELECT account_id,vnum,requested,amount,player_id FROM port_point_rewards WHERE token='"+std::string(r.token)+"'");
|
||||
if(ok(previous) && previous->Get()->uiNumRows==1) {
|
||||
auto row=mysql_fetch_row(previous->Get()->pSQLResult);
|
||||
if(strtoul(row[0],0,10)==r.account && strtoul(row[1],0,10)==r.product && strtoul(row[2],0,10)==r.count){granted=strtoul(row[3],0,10);status=0;}else status=7;
|
||||
if(strtoul(row[0],0,10)==r.account && strtoul(row[1],0,10)==r.product && strtoul(row[2],0,10)==r.count && strtoul(row[4],0,10)==r.player){granted=strtoul(row[3],0,10);status=0;}else status=7;
|
||||
} else if(ok(previous)) {
|
||||
if(!rule.eligible(mob->bLevel,r.expectedVnum) || r.count<uint32_t(rule.minimum) || r.count>uint32_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()");
|
||||
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())");
|
||||
if(success){if(tx.commit()){balance+=granted;status=0;}else status=8;}
|
||||
// Ownership/rules apply to new awards. They must not hide a committed token
|
||||
// after a character deletion/transfer or a live configuration change.
|
||||
auto owner=query("SELECT account_id FROM player WHERE id="+decimal(r.player));
|
||||
if(ok(owner) && (owner->Get()->uiNumRows!=1 || strtoul(mysql_fetch_row(owner->Get()->pSQLResult)[0],0,10)!=r.account))status=2;
|
||||
else if(ok(owner)) {
|
||||
if(!validMob || !rule.eligible(mob->bLevel,r.expectedVnum) || r.count<uint32_t(rule.minimum) || r.count>uint32_t(rule.maximum))status=1;
|
||||
else {
|
||||
auto dateQ=query("SELECT CURDATE()");
|
||||
if(ok(dateQ) && dateQ->Get()->uiNumRows==1) {
|
||||
const std::string rewardDay = mysql_fetch_row(dateQ->Get()->pSQLResult)[0];
|
||||
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)+",'"+rewardDay+"')");
|
||||
if(success){if(tx.commit()){balance+=granted;status=0;}else status=8;}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -127,9 +153,10 @@ void CClientManager::Ava2ItemShop(CPeer* peer,DWORD handle,const char* data,DWOR
|
||||
std::map<uint8_t,std::map<uint8_t,std::vector<Ava2ShopProduct>>> catalogue;
|
||||
MYSQL_ROW row;
|
||||
while((row=mysql_fetch_row(rows->Get()->pSQLResult))) {
|
||||
auto p=product(row);int cat=atoi(row[10]),sub=atoi(row[11]);
|
||||
auto p=product(row);int64_t cat=0,sub=0;
|
||||
if(!productNumber(row[10],cat,0,7) || !productNumber(row[11],sub,0,9))continue;
|
||||
if(!valid(p) || cat<0 || cat>7 || sub<0 || sub>9 || (!m_map_itemTableByVnum.count(p.vnum) || m_map_itemTableByVnum.at(p.vnum)->bType==ITEM_NONE))continue;
|
||||
catalogue[cat][sub].push_back(p);
|
||||
catalogue[static_cast<uint8_t>(cat)][static_cast<uint8_t>(sub)].push_back(p);
|
||||
}
|
||||
std::vector<Ava2ShopProduct*> ranked;
|
||||
for(auto& cat:catalogue)for(auto& sub:cat.second)for(auto& p:sub.second)ranked.push_back(&p);
|
||||
|
||||
+274
-211
File diff suppressed because it is too large
Load Diff
@@ -12,6 +12,7 @@
|
||||
#include "Peer.h"
|
||||
#include "DBManager.h"
|
||||
#include "LoginData.h"
|
||||
#include "CubeRuntime.h"
|
||||
|
||||
class CPlayerTableCache;
|
||||
class CItemCache;
|
||||
@@ -30,7 +31,50 @@ size_t CreatePlayerSaveQuery(char * pszQuery, size_t querySize, TPlayerTable * p
|
||||
|
||||
class CClientManager : public CNetBase, public singleton<CClientManager>
|
||||
{
|
||||
struct EconomyFence { DWORD account=0; bool primed=false,mainDone=false,asyncDone=false,asyncQueued=false,failed=false; uint64_t mainFailures=0,asyncFailures=0,routerFailures=0; time_t nextAttempt=0; DWORD peer=0,handle=0; TPlayerLoadPacket load={}; };
|
||||
std::map<DWORD,std::pair<uint64_t,uint64_t>> m_economyEnqueueEpoch;
|
||||
std::map<DWORD,EconomyFence> m_economyFences;
|
||||
std::map<DWORD,DWORD> m_economyOwners;
|
||||
std::set<DWORD> m_economyClosed;
|
||||
DWORD m_cubeCookie=0;
|
||||
uint64_t m_cubeWorkCursor=0;
|
||||
std::map<DWORD,PortCube::RuntimeDrain> m_cubeDrains;
|
||||
std::string m_cubeOwnerBoot;
|
||||
bool CubeDrainOwner(const PortCube::RuntimeDrain&,bool=false);
|
||||
bool CubeAuthorityCheck(const PortCube::RuntimeDrain&,bool);
|
||||
void CubeAuthorityRevoke(PortCube::RuntimeDrain&,unsigned);
|
||||
void CubeDrainFinalize(PortCube::RuntimeDrain&);
|
||||
public:
|
||||
void EconomyRequest(CPeer*,DWORD,const char*,DWORD);
|
||||
bool EconomyBeforeLoad(CPeer*,DWORD,TPlayerLoadPacket*);
|
||||
void EconomyTick();
|
||||
void EconomyMainFence(DWORD,bool);
|
||||
bool EconomySaveAllowed(CPeer*,DWORD);
|
||||
bool EconomyItemWritable(DWORD);
|
||||
bool EconomyCanDelete(DWORD);
|
||||
bool CubePlayerWritable(DWORD);
|
||||
bool CubeAccountLoadable(DWORD,DWORD);
|
||||
bool CubeItemWritable(DWORD);
|
||||
bool CubePeerMayWriteItem(CPeer*,DWORD);
|
||||
DWORD CubeDrainArm(CPeer*,DWORD,uint64_t,const PortCube::Batch&);
|
||||
bool CubeDrainSubmit(CPeer*,DWORD,uint64_t,DWORD);
|
||||
void CubeMainFence(DWORD,unsigned,bool);
|
||||
void CubeDrainTick();
|
||||
bool CubeMemoryLoadable(DWORD,DWORD);
|
||||
bool CubePeerMaySave(CPeer*,DWORD);
|
||||
void CubePeerGone(DWORD);
|
||||
void CubeAccountLogout(CPeer*,const char*,DWORD);
|
||||
void CubeAccountGone(DWORD,DWORD);
|
||||
void CubeHandshakeRequest(CPeer*,DWORD,const char*,DWORD);
|
||||
void CubeHandshakeRoute(CPeer*,DWORD,const PortCube::Handshake&);
|
||||
void CubeLiveResumeCheckRoute(CPeer*,DWORD,const PortCube::Handshake&);
|
||||
bool CubeRecoveryClaim(CPeer*,DWORD,DWORD,DWORD,uint64_t,PortCube::OwnerGrant&);
|
||||
void CubeRecoveryRoute(CPeer*,DWORD,const PortCube::Handshake&);
|
||||
void CubeRecoveryImageRoute(CPeer*,DWORD,const PortCube::Handshake&);
|
||||
void CubeCraftRoute(CPeer*,DWORD,const PortCube::Handshake&);
|
||||
void CubeLiveImageRoute(CPeer*,DWORD,const PortCube::Handshake&);
|
||||
void CubeLiveImageAckRoute(CPeer*,DWORD,const PortCube::Handshake&);
|
||||
void CubeLiveReleaseRoute(CPeer*,DWORD,const PortCube::Handshake&);
|
||||
typedef std::list<CPeer *> TPeerList;
|
||||
typedef std::unordered_map<DWORD, CPlayerTableCache *> TPlayerTableCacheMap;
|
||||
typedef std::unordered_map<DWORD, CItemCache *> TItemCacheMap;
|
||||
@@ -40,10 +84,10 @@ class CClientManager : public CNetBase, public singleton<CClientManager>
|
||||
typedef std::unordered_map<short, BYTE> TChannelStatusMap;
|
||||
|
||||
// MYSHOP_PRICE_LIST
|
||||
/// 아이템 가격정보 리스트 요청 정보
|
||||
/// 아이템 가격정보 리스트 요청 정보
|
||||
/**
|
||||
* first: Peer handle
|
||||
* second: 요청한 플레이어의 ID
|
||||
* second: 요청한 플레이어의 ID
|
||||
*/
|
||||
typedef std::pair< DWORD, DWORD > TItemPricelistReqInfo;
|
||||
// END_OF_MYSHOP_PRICE_LIST
|
||||
@@ -69,7 +113,7 @@ class CClientManager : public CNetBase, public singleton<CClientManager>
|
||||
pAccountTable = NULL;
|
||||
player_id = dwPID;
|
||||
};
|
||||
//독일선물기능용 생성자
|
||||
//독일선물기능용 생성자
|
||||
ClientHandleInfo(DWORD argHandle, DWORD dwPID, DWORD accountId)
|
||||
{
|
||||
dwHandle = argHandle;
|
||||
@@ -108,7 +152,7 @@ class CClientManager : public CNetBase, public singleton<CClientManager>
|
||||
void SetChinaEventServer(bool flag) { m_bChinaEventServer = flag; }
|
||||
bool IsChinaEventServer() { return m_bChinaEventServer; }
|
||||
|
||||
DWORD GetUserCount(); // 접속된 사용자 수를 리턴 한다.
|
||||
DWORD GetUserCount(); // 접속된 사용자 수를 리턴 한다.
|
||||
|
||||
void SendAllGuildSkillRechargePacket();
|
||||
void SendTime();
|
||||
@@ -122,29 +166,30 @@ class CClientManager : public CNetBase, public singleton<CClientManager>
|
||||
|
||||
CItemCache * GetItemCache(DWORD id);
|
||||
void PutItemCache(TPlayerItem * pNew, bool bSkipQuery = false);
|
||||
bool ValidateLoadedExtra(const TPlayerItem& item,const char* hex) const;
|
||||
bool DeleteItemCache(DWORD id);
|
||||
|
||||
void UpdatePlayerCache();
|
||||
void UpdateItemCache();
|
||||
|
||||
// MYSHOP_PRICE_LIST
|
||||
/// 가격정보 리스트 캐시를 가져온다.
|
||||
/// 가격정보 리스트 캐시를 가져온다.
|
||||
/**
|
||||
* @param [in] dwID 가격정보 리스트의 소유자.(플레이어 ID)
|
||||
* @return 가격정보 리스트 캐시의 포인터
|
||||
* @param [in] dwID 가격정보 리스트의 소유자.(플레이어 ID)
|
||||
* @return 가격정보 리스트 캐시의 포인터
|
||||
*/
|
||||
CItemPriceListTableCache* GetItemPriceListCache(DWORD dwID);
|
||||
|
||||
/// 가격정보 리스트 캐시를 넣는다.
|
||||
/// 가격정보 리스트 캐시를 넣는다.
|
||||
/**
|
||||
* @param [in] pItemPriceList 캐시에 넣을 아이템 가격정보 리스트
|
||||
* @param [in] pItemPriceList 캐시에 넣을 아이템 가격정보 리스트
|
||||
*
|
||||
* 캐시가 이미 있으면 Update 가 아닌 replace 한다.
|
||||
* 캐시가 이미 있으면 Update 가 아닌 replace 한다.
|
||||
*/
|
||||
void PutItemPriceListCache(const TItemPriceListTable* pItemPriceList);
|
||||
|
||||
|
||||
/// Flush 시간이 만료된 아이템 가격정보 리스트 캐시를 Flush 해주고 캐시에서 삭제한다.
|
||||
/// Flush 시간이 만료된 아이템 가격정보 리스트 캐시를 Flush 해주고 캐시에서 삭제한다.
|
||||
void UpdateItemPriceListCache(void);
|
||||
// END_OF_MYSHOP_PRICE_LIST
|
||||
|
||||
@@ -162,8 +207,8 @@ class CClientManager : public CNetBase, public singleton<CClientManager>
|
||||
|
||||
void SendNotice(const char * c_pszFormat, ...);
|
||||
|
||||
char* GetCommand(char* str); //독일선물기능에서 명령어 얻는 함수
|
||||
void ItemAward(CPeer * peer, char* login); //독일 선물 기능
|
||||
char* GetCommand(char* str); //독일선물기능에서 명령어 얻는 함수
|
||||
void ItemAward(CPeer * peer, char* login); //독일 선물 기능
|
||||
|
||||
protected:
|
||||
void Destroy();
|
||||
@@ -184,9 +229,9 @@ class CClientManager : public CNetBase, public singleton<CClientManager>
|
||||
bool InitializeObjectTable();
|
||||
bool InitializeMonarch();
|
||||
|
||||
// mob_proto.txt, item_proto.txt에서 읽은 mob_proto, item_proto를 real db에 반영.
|
||||
// item_proto, mob_proto를 db에 반영하지 않아도, 게임 돌아가는데는 문제가 없지만,
|
||||
// 운영툴 등에서 db의 item_proto, mob_proto를 읽어 쓰기 때문에 문제가 발생한다.
|
||||
// mob_proto.txt, item_proto.txt에서 읽은 mob_proto, item_proto를 real db에 반영.
|
||||
// item_proto, mob_proto를 db에 반영하지 않아도, 게임 돌아가는데는 문제가 없지만,
|
||||
// 운영툴 등에서 db의 item_proto, mob_proto를 읽어 쓰기 때문에 문제가 발생한다.
|
||||
bool MirrorMobTableIntoDB();
|
||||
bool MirrorItemTableIntoDB();
|
||||
|
||||
@@ -252,20 +297,20 @@ class CClientManager : public CNetBase, public singleton<CClientManager>
|
||||
// END_PLAYER_INDEX_CREATE_BUG_FIX
|
||||
|
||||
// MYSHOP_PRICE_LIST
|
||||
/// 가격정보 로드 쿼리에 대한 Result 처리
|
||||
/// 가격정보 로드 쿼리에 대한 Result 처리
|
||||
/**
|
||||
* @param peer 가격정보를 요청한 Game server 의 peer 객체 포인터
|
||||
* @param pMsg 쿼리의 Result 로 받은 객체의 포인터
|
||||
* @param peer 가격정보를 요청한 Game server 의 peer 객체 포인터
|
||||
* @param pMsg 쿼리의 Result 로 받은 객체의 포인터
|
||||
*
|
||||
* 로드된 가격정보 리스트를 캐시에 저장하고 peer 에게 리스트를 보내준다.
|
||||
* 로드된 가격정보 리스트를 캐시에 저장하고 peer 에게 리스트를 보내준다.
|
||||
*/
|
||||
void RESULT_PRICELIST_LOAD(CPeer* peer, SQLMsg* pMsg);
|
||||
|
||||
/// 가격정보 업데이트를 위한 로드 쿼리에 대한 Result 처리
|
||||
/// 가격정보 업데이트를 위한 로드 쿼리에 대한 Result 처리
|
||||
/**
|
||||
* @param pMsg 쿼리의 Result 로 받은 객체의 포인터
|
||||
* @param pMsg 쿼리의 Result 로 받은 객체의 포인터
|
||||
*
|
||||
* 로드된 정보로 가격정보 리스트 캐시를 만들고 업데이트 받은 가격정보로 업데이트 한다.
|
||||
* 로드된 정보로 가격정보 리스트 캐시를 만들고 업데이트 받은 가격정보로 업데이트 한다.
|
||||
*/
|
||||
void RESULT_PRICELIST_LOAD_FOR_UPDATE(SQLMsg* pMsg);
|
||||
// END_OF_MYSHOP_PRICE_LIST
|
||||
@@ -345,7 +390,7 @@ class CClientManager : public CNetBase, public singleton<CClientManager>
|
||||
void SendAllLoginToBilling();
|
||||
void SendLoginToBilling(CLoginData * pkLD, bool bLogin);
|
||||
|
||||
// 결혼
|
||||
// 결혼
|
||||
void MarriageAdd(TPacketMarriageAdd * p);
|
||||
void MarriageUpdate(TPacketMarriageUpdate * p);
|
||||
void MarriageRemove(TPacketMarriageRemove * p);
|
||||
@@ -355,20 +400,20 @@ class CClientManager : public CNetBase, public singleton<CClientManager>
|
||||
void WeddingEnd(TPacketWeddingEnd * p);
|
||||
|
||||
// MYSHOP_PRICE_LIST
|
||||
// 개인상점 가격정보
|
||||
// 개인상점 가격정보
|
||||
|
||||
/// 아이템 가격정보 리스트 업데이트 패킷(HEADER_GD_MYSHOP_PRICELIST_UPDATE) 처리함수
|
||||
/// 아이템 가격정보 리스트 업데이트 패킷(HEADER_GD_MYSHOP_PRICELIST_UPDATE) 처리함수
|
||||
/**
|
||||
* @param [in] pPacket 패킷 데이터의 포인터
|
||||
* @param [in] pPacket 패킷 데이터의 포인터
|
||||
*/
|
||||
// void MyshopPricelistUpdate(const TPacketMyshopPricelistHeader* pPacket);
|
||||
void MyshopPricelistUpdate(const TItemPriceListTable* pPacket);
|
||||
|
||||
/// 아이템 가격정보 리스트 요청 패킷(HEADER_GD_MYSHOP_PRICELIST_REQ) 처리함수
|
||||
/// 아이템 가격정보 리스트 요청 패킷(HEADER_GD_MYSHOP_PRICELIST_REQ) 처리함수
|
||||
/**
|
||||
* @param peer 패킷을 보낸 Game server 의 peer 객체의 포인터
|
||||
* @param [in] dwHandle 가격정보를 요청한 peer 의 핸들
|
||||
* @param [in] dwPlayerID 가격정보 리스트를 요청한 플레이어의 ID
|
||||
* @param peer 패킷을 보낸 Game server 의 peer 객체의 포인터
|
||||
* @param [in] dwHandle 가격정보를 요청한 peer 의 핸들
|
||||
* @param [in] dwPlayerID 가격정보 리스트를 요청한 플레이어의 ID
|
||||
*/
|
||||
void MyshopPricelistRequest(CPeer* peer, DWORD dwHandle, DWORD dwPlayerID);
|
||||
// END_OF_MYSHOP_PRICE_LIST
|
||||
@@ -388,7 +433,7 @@ class CClientManager : public CNetBase, public singleton<CClientManager>
|
||||
|
||||
private:
|
||||
int m_looping;
|
||||
socket_t m_fdAccept; // 접속 받는 소켓
|
||||
socket_t m_fdAccept; // 접속 받는 소켓
|
||||
TPeerList m_peerList;
|
||||
|
||||
CPeer * m_pkAuthPeer;
|
||||
@@ -405,7 +450,7 @@ class CClientManager : public CNetBase, public singleton<CClientManager>
|
||||
typedef std::unordered_map<DWORD, CLoginData *> TLoginDataByAID;
|
||||
TLoginDataByAID m_map_pkLoginDataByAID;
|
||||
|
||||
// Login LoginData pair (실제 로그인 되어있는 계정)
|
||||
// Login LoginData pair (실제 로그인 되어있는 계정)
|
||||
typedef std::unordered_map<std::string, CLoginData *> TLogonAccountMap;
|
||||
TLogonAccountMap m_map_kLogonAccount;
|
||||
|
||||
@@ -437,14 +482,14 @@ class CClientManager : public CNetBase, public singleton<CClientManager>
|
||||
|
||||
bool m_bShutdowned;
|
||||
|
||||
TPlayerTableCacheMap m_map_playerCache; // 플레이어 id가 key
|
||||
TPlayerTableCacheMap m_map_playerCache; // 플레이어 id가 key
|
||||
|
||||
TItemCacheMap m_map_itemCache; // 아이템 id가 key
|
||||
TItemCacheSetPtrMap m_map_pkItemCacheSetPtr; // 플레이어 id가 key, 이 플레이어가 어떤 아이템 캐쉬를 가지고 있나?
|
||||
TItemCacheMap m_map_itemCache; // 아이템 id가 key
|
||||
TItemCacheSetPtrMap m_map_pkItemCacheSetPtr; // 플레이어 id가 key, 이 플레이어가 어떤 아이템 캐쉬를 가지고 있나?
|
||||
|
||||
// MYSHOP_PRICE_LIST
|
||||
/// 플레이어별 아이템 가격정보 리스트 map. key: 플레이어 ID, value: 가격정보 리스트 캐시
|
||||
TItemPriceListCacheMap m_mapItemPriceListCache; ///< 플레이어별 아이템 가격정보 리스트
|
||||
/// 플레이어별 아이템 가격정보 리스트 map. key: 플레이어 ID, value: 가격정보 리스트 캐시
|
||||
TItemPriceListCacheMap m_mapItemPriceListCache; ///< 플레이어별 아이템 가격정보 리스트
|
||||
// END_OF_MYSHOP_PRICE_LIST
|
||||
|
||||
TChannelStatusMap m_mChannelStatus;
|
||||
@@ -482,7 +527,7 @@ class CClientManager : public CNetBase, public singleton<CClientManager>
|
||||
|
||||
//BOOT_LOCALIZATION
|
||||
public:
|
||||
/* 로컬 정보 초기화
|
||||
/* 로컬 정보 초기화
|
||||
**/
|
||||
bool InitializeLocalization();
|
||||
|
||||
@@ -549,6 +594,25 @@ class CClientManager : public CNetBase, public singleton<CClientManager>
|
||||
void DeleteAwardId(TPacketDeleteAwardID* data);
|
||||
void UpdateChannelStatus(TChannelStatus* pData);
|
||||
void RequestChannelStatus(CPeer* peer, DWORD dwHandle);
|
||||
#ifdef ENABLE_OFFLINESHOP_SYSTEM
|
||||
std::map<DWORD, TOfflineShop*> m_Offlineshop;
|
||||
void OfflineShopAssert(TOfflineShop* p);
|
||||
void CreateOfflineShop(TOfflineShop* p);
|
||||
void DeleteOfflineShop(DWORD ownerid);
|
||||
void RemoveItem(OFFLINE_SHOP_ITEM* item);
|
||||
void AddItem(OFFLINE_SHOP_ITEM* item);
|
||||
void BuyItem(TOfflineShopBuy* item);
|
||||
void WithdrawMoney(DWORD ch);
|
||||
void ClearLog(DWORD ch);
|
||||
void ChangeDecoration(TShopDecoration* ch);
|
||||
void ChangeTitle(TOfflineShopChangeTitle* p);
|
||||
void OpenSlot(TOfflineShopOpenSlot* p);
|
||||
void TimeDone(DWORD ch);
|
||||
void GetBackItem(DWORD p);
|
||||
void AddTime(DWORD p);
|
||||
void RecvPackets(const char* data);
|
||||
bool InitializeOfflineShop();
|
||||
#endif
|
||||
#ifdef __AUCTION__
|
||||
void EnrollInAuction (CPeer * peer, DWORD owner_id, AuctionEnrollProductInfo* data);
|
||||
void EnrollInSale (CPeer * peer, DWORD owner_id, AuctionEnrollSaleInfo* data);
|
||||
|
||||
@@ -97,6 +97,13 @@ bool CClientManager::InitializeTables()
|
||||
return false;
|
||||
}
|
||||
|
||||
#ifdef ENABLE_OFFLINESHOP_SYSTEM
|
||||
if (!InitializeOfflineShop())
|
||||
{
|
||||
sys_err("InitializeOfflineShop FAILED");
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -111,6 +118,7 @@ bool CClientManager::InitializeRefineTable()
|
||||
|
||||
std::unique_ptr<SQLMsg> pkMsg(CDBManager::instance().DirectQuery(query));
|
||||
SQLResult * pRes = pkMsg->Get();
|
||||
if (pkMsg->uiSQLErrno || !pRes || pRes->uiNumRows > UINT16_MAX) { sys_err("boot table query failed or exceeds 16-bit wire count"); return false; }
|
||||
|
||||
if (!pRes->uiNumRows)
|
||||
return true;
|
||||
@@ -122,7 +130,7 @@ bool CClientManager::InitializeRefineTable()
|
||||
m_pRefineTable = NULL;
|
||||
}
|
||||
|
||||
m_iRefineTableSize = pRes->uiNumRows;
|
||||
m_iRefineTableSize = static_cast<int>(pRes->uiNumRows);
|
||||
|
||||
m_pRefineTable = new TRefineTable[m_iRefineTableSize];
|
||||
memset(m_pRefineTable, 0, sizeof(TRefineTable) * m_iRefineTableSize);
|
||||
@@ -171,42 +179,42 @@ class FCompareVnum
|
||||
|
||||
bool CClientManager::InitializeMobTable()
|
||||
{
|
||||
//================== 함수 설명 ==================//
|
||||
//1. 요약 : 'mob_proto.txt', 'mob_proto_test.txt', 'mob_names.txt' 파일을 읽고,
|
||||
// (!)[mob_table] 테이블 오브젝트를 생성한다. (타입 : TMobTable)
|
||||
//2. 순서
|
||||
// 1) 'mob_names.txt' 파일을 읽어서 (a)[localMap](vnum:name) 맵을 만든다.
|
||||
// 2) 'mob_proto_test.txt'파일과 (a)[localMap] 맵으로
|
||||
// (b)[test_map_mobTableByVnum](vnum:TMobTable) 맵을 생성한다.
|
||||
// 3) 'mob_proto.txt' 파일과 (a)[localMap] 맵으로
|
||||
// (!)[mob_table] 테이블을 만든다.
|
||||
// <참고>
|
||||
// 각 row 들 중,
|
||||
// (b)[test_map_mobTableByVnum],(!)[mob_table] 모두에 있는 row는
|
||||
// (b)[test_map_mobTableByVnum]의 것을 사용한다.
|
||||
// 4) (b)[test_map_mobTableByVnum]의 row중, (!)[mob_table]에 없는 것을 추가한다.
|
||||
//3. 테스트
|
||||
// 1)'mob_proto.txt' 정보가 mob_table에 잘 들어갔는지. -> 완료
|
||||
// 2)'mob_names.txt' 정보가 mob_table에 잘 들어갔는지.
|
||||
// 3)'mob_proto_test.txt' 에서 [겹치는] 정보가 mob_table 에 잘 들어갔는지.
|
||||
// 4)'mob_proto_test.txt' 에서 [새로운] 정보가 mob_table 에 잘 들어갔는지.
|
||||
// 5) (최종) 게임 클라이언트에서 제대로 작동 하는지.
|
||||
//================== 함수 설명 ==================//
|
||||
//1. 요약 : 'mob_proto.txt', 'mob_proto_test.txt', 'mob_names.txt' 파일을 읽고,
|
||||
// (!)[mob_table] 테이블 오브젝트를 생성한다. (타입 : TMobTable)
|
||||
//2. 순서
|
||||
// 1) 'mob_names.txt' 파일을 읽어서 (a)[localMap](vnum:name) 맵을 만든다.
|
||||
// 2) 'mob_proto_test.txt'파일과 (a)[localMap] 맵으로
|
||||
// (b)[test_map_mobTableByVnum](vnum:TMobTable) 맵을 생성한다.
|
||||
// 3) 'mob_proto.txt' 파일과 (a)[localMap] 맵으로
|
||||
// (!)[mob_table] 테이블을 만든다.
|
||||
// <참고>
|
||||
// 각 row 들 중,
|
||||
// (b)[test_map_mobTableByVnum],(!)[mob_table] 모두에 있는 row는
|
||||
// (b)[test_map_mobTableByVnum]의 것을 사용한다.
|
||||
// 4) (b)[test_map_mobTableByVnum]의 row중, (!)[mob_table]에 없는 것을 추가한다.
|
||||
//3. 테스트
|
||||
// 1)'mob_proto.txt' 정보가 mob_table에 잘 들어갔는지. -> 완료
|
||||
// 2)'mob_names.txt' 정보가 mob_table에 잘 들어갔는지.
|
||||
// 3)'mob_proto_test.txt' 에서 [겹치는] 정보가 mob_table 에 잘 들어갔는지.
|
||||
// 4)'mob_proto_test.txt' 에서 [새로운] 정보가 mob_table 에 잘 들어갔는지.
|
||||
// 5) (최종) 게임 클라이언트에서 제대로 작동 하는지.
|
||||
//_______________________________________________//
|
||||
|
||||
|
||||
//===============================================//
|
||||
// 1) 'mob_names.txt' 파일을 읽어서 (a)[localMap] 맵을 만든다.
|
||||
//<(a)localMap 맵 생성>
|
||||
// 1) 'mob_names.txt' 파일을 읽어서 (a)[localMap] 맵을 만든다.
|
||||
//<(a)localMap 맵 생성>
|
||||
map<int,const char*> localMap;
|
||||
bool isNameFile = true;
|
||||
//<파일 읽기>
|
||||
//<파일 읽기>
|
||||
cCsvTable nameData;
|
||||
if(!nameData.Load("mob_names.txt",'\t'))
|
||||
{
|
||||
fprintf(stderr, "mob_names.txt 파일을 읽어오지 못했습니다\n");
|
||||
fprintf(stderr, "mob_names.txt 파일을 읽어오지 못했습니다\n");
|
||||
isNameFile = false;
|
||||
} else {
|
||||
nameData.Next(); //설명row 생략.
|
||||
nameData.Next(); //설명row 생략.
|
||||
while(nameData.Next()) {
|
||||
localMap[atoi(nameData.AsStringByIndex(0))] = nameData.AsStringByIndex(1);
|
||||
}
|
||||
@@ -215,35 +223,35 @@ bool CClientManager::InitializeMobTable()
|
||||
|
||||
|
||||
//===============================================//
|
||||
// 2) 'mob_proto_test.txt'파일과 (a)localMap 맵으로
|
||||
// (b)[test_map_mobTableByVnum](vnum:TMobTable) 맵을 생성한다.
|
||||
// 2) 'mob_proto_test.txt'파일과 (a)localMap 맵으로
|
||||
// (b)[test_map_mobTableByVnum](vnum:TMobTable) 맵을 생성한다.
|
||||
//0.
|
||||
set<int> vnumSet; //테스트용 파일 데이터중, 신규여부 확인에 사용.
|
||||
//1. 파일 읽어오기
|
||||
set<int> vnumSet; //테스트용 파일 데이터중, 신규여부 확인에 사용.
|
||||
//1. 파일 읽어오기
|
||||
bool isTestFile = true;
|
||||
cCsvTable test_data;
|
||||
if(!test_data.Load("mob_proto_test.txt",'\t'))
|
||||
{
|
||||
fprintf(stderr, "테스트 파일이 없습니다. 그대로 진행합니다.\n");
|
||||
fprintf(stderr, "테스트 파일이 없습니다. 그대로 진행합니다.\n");
|
||||
isTestFile = false;
|
||||
}
|
||||
//2. (c)[test_map_mobTableByVnum](vnum:TMobTable) 맵 생성.
|
||||
//2. (c)[test_map_mobTableByVnum](vnum:TMobTable) 맵 생성.
|
||||
map<DWORD, TMobTable *> test_map_mobTableByVnum;
|
||||
if (isTestFile) {
|
||||
test_data.Next(); //설명 로우 넘어가기.
|
||||
test_data.Next(); //설명 로우 넘어가기.
|
||||
|
||||
//ㄱ. 테스트 몬스터 테이블 생성.
|
||||
//ㄱ. 테스트 몬스터 테이블 생성.
|
||||
TMobTable * test_mob_table = NULL;
|
||||
int test_MobTableSize = test_data.m_File.GetRowCount()-1;
|
||||
test_mob_table = new TMobTable[test_MobTableSize];
|
||||
memset(test_mob_table, 0, sizeof(TMobTable) * test_MobTableSize);
|
||||
|
||||
//ㄴ. 테스트 몬스터 테이블에 값을 넣고, 맵에까지 넣기.
|
||||
//ㄴ. 테스트 몬스터 테이블에 값을 넣고, 맵에까지 넣기.
|
||||
while(test_data.Next()) {
|
||||
|
||||
if (!Set_Proto_Mob_Table(test_mob_table, test_data, localMap))
|
||||
{
|
||||
fprintf(stderr, "몹 프로토 테이블 셋팅 실패.\n");
|
||||
fprintf(stderr, "몹 프로토 테이블 셋팅 실패.\n");
|
||||
}
|
||||
|
||||
test_map_mobTableByVnum.insert(std::map<DWORD, TMobTable *>::value_type(test_mob_table->dwVnum, test_mob_table));
|
||||
@@ -254,22 +262,22 @@ bool CClientManager::InitializeMobTable()
|
||||
|
||||
}
|
||||
|
||||
// 3) 'mob_proto.txt' 파일과 (a)[localMap] 맵으로
|
||||
// (!)[mob_table] 테이블을 만든다.
|
||||
// <참고>
|
||||
// 각 row 들 중,
|
||||
// (b)[test_map_mobTableByVnum],(!)[mob_table] 모두에 있는 row는
|
||||
// (b)[test_map_mobTableByVnum]의 것을 사용한다.
|
||||
// 3) 'mob_proto.txt' 파일과 (a)[localMap] 맵으로
|
||||
// (!)[mob_table] 테이블을 만든다.
|
||||
// <참고>
|
||||
// 각 row 들 중,
|
||||
// (b)[test_map_mobTableByVnum],(!)[mob_table] 모두에 있는 row는
|
||||
// (b)[test_map_mobTableByVnum]의 것을 사용한다.
|
||||
|
||||
//1. 파일 읽기.
|
||||
//1. 파일 읽기.
|
||||
cCsvTable data;
|
||||
if(!data.Load("mob_proto.txt",'\t')) {
|
||||
fprintf(stderr, "mob_proto.txt 파일을 읽어오지 못했습니다\n");
|
||||
fprintf(stderr, "mob_proto.txt 파일을 읽어오지 못했습니다\n");
|
||||
return false;
|
||||
}
|
||||
data.Next(); //설명 row 넘어가기
|
||||
//2. (!)[mob_table] 생성하기
|
||||
//2.1 새로 추가되는 갯수를 파악
|
||||
data.Next(); //설명 row 넘어가기
|
||||
//2. (!)[mob_table] 생성하기
|
||||
//2.1 새로 추가되는 갯수를 파악
|
||||
int addNumber = 0;
|
||||
while(data.Next()) {
|
||||
int vnum = atoi(data.AsStringByIndex(0));
|
||||
@@ -279,15 +287,15 @@ bool CClientManager::InitializeMobTable()
|
||||
addNumber++;
|
||||
}
|
||||
}
|
||||
//data를 다시 첫줄로 옮긴다.(다시 읽어온다;;)
|
||||
//data를 다시 첫줄로 옮긴다.(다시 읽어온다;;)
|
||||
data.Destroy();
|
||||
if(!data.Load("mob_proto.txt",'\t'))
|
||||
{
|
||||
fprintf(stderr, "mob_proto.txt 파일을 읽어오지 못했습니다\n");
|
||||
fprintf(stderr, "mob_proto.txt 파일을 읽어오지 못했습니다\n");
|
||||
return false;
|
||||
}
|
||||
data.Next(); //맨 윗줄 제외 (아이템 칼럼을 설명하는 부분)
|
||||
//2.2 크기에 맞게 mob_table 생성
|
||||
data.Next(); //맨 윗줄 제외 (아이템 칼럼을 설명하는 부분)
|
||||
//2.2 크기에 맞게 mob_table 생성
|
||||
if (!m_vec_mobTable.empty())
|
||||
{
|
||||
sys_log(0, "RELOAD: mob_proto");
|
||||
@@ -296,18 +304,18 @@ bool CClientManager::InitializeMobTable()
|
||||
m_vec_mobTable.resize(data.m_File.GetRowCount()-1 + addNumber);
|
||||
memset(&m_vec_mobTable[0], 0, sizeof(TMobTable) * m_vec_mobTable.size());
|
||||
TMobTable * mob_table = &m_vec_mobTable[0];
|
||||
//2.3 데이터 채우기
|
||||
//2.3 데이터 채우기
|
||||
while (data.Next())
|
||||
{
|
||||
int col = 0;
|
||||
//(b)[test_map_mobTableByVnum]에 같은 row가 있는지 조사.
|
||||
//(b)[test_map_mobTableByVnum]에 같은 row가 있는지 조사.
|
||||
bool isSameRow = true;
|
||||
std::map<DWORD, TMobTable *>::iterator it_map_mobTable;
|
||||
it_map_mobTable = test_map_mobTableByVnum.find(atoi(data.AsStringByIndex(col)));
|
||||
if(it_map_mobTable == test_map_mobTableByVnum.end()) {
|
||||
isSameRow = false;
|
||||
}
|
||||
//같은 row 가 있으면 (b)에서 읽어온다.
|
||||
//같은 row 가 있으면 (b)에서 읽어온다.
|
||||
if(isSameRow) {
|
||||
TMobTable *tempTable = it_map_mobTable->second;
|
||||
|
||||
@@ -378,13 +386,13 @@ bool CClientManager::InitializeMobTable()
|
||||
|
||||
if (!Set_Proto_Mob_Table(mob_table, data, localMap))
|
||||
{
|
||||
fprintf(stderr, "몹 프로토 테이블 셋팅 실패.\n");
|
||||
fprintf(stderr, "몹 프로토 테이블 셋팅 실패.\n");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
//셋에 vnum 추가
|
||||
//셋에 vnum 추가
|
||||
vnumSet.insert(mob_table->dwVnum);
|
||||
|
||||
|
||||
@@ -395,22 +403,22 @@ bool CClientManager::InitializeMobTable()
|
||||
//_____________________________________________________//
|
||||
|
||||
|
||||
// 4) (b)[test_map_mobTableByVnum]의 row중, (!)[mob_table]에 없는 것을 추가한다.
|
||||
//파일 다시 읽어오기.
|
||||
// 4) (b)[test_map_mobTableByVnum]의 row중, (!)[mob_table]에 없는 것을 추가한다.
|
||||
//파일 다시 읽어오기.
|
||||
test_data.Destroy();
|
||||
isTestFile = true;
|
||||
test_data;
|
||||
if(!test_data.Load("mob_proto_test.txt",'\t'))
|
||||
{
|
||||
fprintf(stderr, "테스트 파일이 없습니다. 그대로 진행합니다.\n");
|
||||
fprintf(stderr, "테스트 파일이 없습니다. 그대로 진행합니다.\n");
|
||||
isTestFile = false;
|
||||
}
|
||||
if(isTestFile) {
|
||||
test_data.Next(); //설명 로우 넘어가기.
|
||||
test_data.Next(); //설명 로우 넘어가기.
|
||||
|
||||
while (test_data.Next()) //테스트 데이터 각각을 훑어나가며,새로운 것을 추가한다.
|
||||
while (test_data.Next()) //테스트 데이터 각각을 훑어나가며,새로운 것을 추가한다.
|
||||
{
|
||||
//중복되는 부분이면 넘어간다.
|
||||
//중복되는 부분이면 넘어간다.
|
||||
set<int>::iterator itVnum;
|
||||
itVnum=vnumSet.find(atoi(test_data.AsStringByIndex(0)));
|
||||
if (itVnum != vnumSet.end()) {
|
||||
@@ -419,7 +427,7 @@ bool CClientManager::InitializeMobTable()
|
||||
|
||||
if (!Set_Proto_Mob_Table(mob_table, test_data, localMap))
|
||||
{
|
||||
fprintf(stderr, "몹 프로토 테이블 셋팅 실패.\n");
|
||||
fprintf(stderr, "몹 프로토 테이블 셋팅 실패.\n");
|
||||
}
|
||||
|
||||
sys_log(0, "MOB #%-5d %-24s %-24s level: %-3u rank: %u empire: %d", mob_table->dwVnum, mob_table->szName, mob_table->szLocaleName, mob_table->bLevel, mob_table->bRank, mob_table->bEmpire);
|
||||
@@ -447,9 +455,10 @@ bool CClientManager::InitializeShopTable()
|
||||
|
||||
std::unique_ptr<SQLMsg> pkMsg2(CDBManager::instance().DirectQuery(s_szQuery));
|
||||
|
||||
// shop의 vnum은 있는데 shop_item 이 없을경우... 실패로 처리되니 주의 요망.
|
||||
// 고처야할부분
|
||||
// shop의 vnum은 있는데 shop_item 이 없을경우... 실패로 처리되니 주의 요망.
|
||||
// 고처야할부분
|
||||
SQLResult * pRes2 = pkMsg2->Get();
|
||||
if (pkMsg2->uiSQLErrno || !pRes2 || pRes2->uiNumRows > UINT16_MAX) { sys_err("boot table query failed or exceeds 16-bit wire count"); return false; }
|
||||
|
||||
if (!pRes2->uiNumRows)
|
||||
{
|
||||
@@ -487,7 +496,7 @@ bool CClientManager::InitializeShopTable()
|
||||
|
||||
str_to_number(shop_table->dwNPCVnum, data[col++]);
|
||||
|
||||
if (!data[col]) // 아이템이 하나도 없으면 NULL이 리턴 되므로..
|
||||
if (!data[col]) // 아이템이 하나도 없으면 NULL이 리턴 되므로..
|
||||
continue;
|
||||
|
||||
TShopItemTable * pItem = &shop_table->items[shop_table->byItemCount];
|
||||
@@ -526,6 +535,7 @@ bool CClientManager::InitializeQuestItemTable()
|
||||
|
||||
std::unique_ptr<SQLMsg> pkMsg(CDBManager::instance().DirectQuery(query));
|
||||
SQLResult * pRes = pkMsg->Get();
|
||||
if (pkMsg->uiSQLErrno || !pRes || pRes->uiNumRows > UINT16_MAX) { sys_err("boot table query failed or exceeds 16-bit wire count"); return false; }
|
||||
|
||||
if (!pRes->uiNumRows)
|
||||
{
|
||||
@@ -560,7 +570,7 @@ bool CClientManager::InitializeQuestItemTable()
|
||||
continue;
|
||||
}
|
||||
|
||||
tbl.bType = ITEM_QUEST; // quest_item_proto 테이블에 있는 것들은 모두 ITEM_QUEST 유형
|
||||
tbl.bType = ITEM_QUEST; // quest_item_proto 테이블에 있는 것들은 모두 ITEM_QUEST 유형
|
||||
tbl.bSize = 1;
|
||||
|
||||
m_vec_itemTable.push_back(tbl);
|
||||
@@ -571,39 +581,39 @@ bool CClientManager::InitializeQuestItemTable()
|
||||
|
||||
bool CClientManager::InitializeItemTable()
|
||||
{
|
||||
//================== 함수 설명 ==================//
|
||||
//1. 요약 : 'item_proto.txt', 'item_proto_test.txt', 'item_names.txt' 파일을 읽고,
|
||||
// <item_table>(TItemTable), <m_map_itemTableByVnum> 오브젝트를 생성한다.
|
||||
//2. 순서
|
||||
// 1) 'item_names.txt' 파일을 읽어서 (a)[localMap](vnum:name) 맵을 만든다.
|
||||
// 2) 'item_proto_text.txt'파일과 (a)[localMap] 맵으로
|
||||
// (b)[test_map_itemTableByVnum](vnum:TItemTable) 맵을 생성한다.
|
||||
// 3) 'item_proto.txt' 파일과 (a)[localMap] 맵으로
|
||||
// (!)[item_table], <m_map_itemTableByVnum>을 만든다.
|
||||
// <참고>
|
||||
// 각 row 들 중,
|
||||
// (b)[test_map_itemTableByVnum],(!)[mob_table] 모두에 있는 row는
|
||||
// (b)[test_map_itemTableByVnum]의 것을 사용한다.
|
||||
// 4) (b)[test_map_itemTableByVnum]의 row중, (!)[item_table]에 없는 것을 추가한다.
|
||||
//3. 테스트
|
||||
// 1)'item_proto.txt' 정보가 item_table에 잘 들어갔는지. -> 완료
|
||||
// 2)'item_names.txt' 정보가 item_table에 잘 들어갔는지.
|
||||
// 3)'item_proto_test.txt' 에서 [겹치는] 정보가 item_table 에 잘 들어갔는지.
|
||||
// 4)'item_proto_test.txt' 에서 [새로운] 정보가 item_table 에 잘 들어갔는지.
|
||||
// 5) (최종) 게임 클라이언트에서 제대로 작동 하는지.
|
||||
//================== 함수 설명 ==================//
|
||||
//1. 요약 : 'item_proto.txt', 'item_proto_test.txt', 'item_names.txt' 파일을 읽고,
|
||||
// <item_table>(TItemTable), <m_map_itemTableByVnum> 오브젝트를 생성한다.
|
||||
//2. 순서
|
||||
// 1) 'item_names.txt' 파일을 읽어서 (a)[localMap](vnum:name) 맵을 만든다.
|
||||
// 2) 'item_proto_text.txt'파일과 (a)[localMap] 맵으로
|
||||
// (b)[test_map_itemTableByVnum](vnum:TItemTable) 맵을 생성한다.
|
||||
// 3) 'item_proto.txt' 파일과 (a)[localMap] 맵으로
|
||||
// (!)[item_table], <m_map_itemTableByVnum>을 만든다.
|
||||
// <참고>
|
||||
// 각 row 들 중,
|
||||
// (b)[test_map_itemTableByVnum],(!)[mob_table] 모두에 있는 row는
|
||||
// (b)[test_map_itemTableByVnum]의 것을 사용한다.
|
||||
// 4) (b)[test_map_itemTableByVnum]의 row중, (!)[item_table]에 없는 것을 추가한다.
|
||||
//3. 테스트
|
||||
// 1)'item_proto.txt' 정보가 item_table에 잘 들어갔는지. -> 완료
|
||||
// 2)'item_names.txt' 정보가 item_table에 잘 들어갔는지.
|
||||
// 3)'item_proto_test.txt' 에서 [겹치는] 정보가 item_table 에 잘 들어갔는지.
|
||||
// 4)'item_proto_test.txt' 에서 [새로운] 정보가 item_table 에 잘 들어갔는지.
|
||||
// 5) (최종) 게임 클라이언트에서 제대로 작동 하는지.
|
||||
//_______________________________________________//
|
||||
|
||||
|
||||
|
||||
//=================================================================================//
|
||||
// 1) 'item_names.txt' 파일을 읽어서 (a)[localMap](vnum:name) 맵을 만든다.
|
||||
// 1) 'item_names.txt' 파일을 읽어서 (a)[localMap](vnum:name) 맵을 만든다.
|
||||
//=================================================================================//
|
||||
bool isNameFile = true;
|
||||
map<int,const char*> localMap;
|
||||
cCsvTable nameData;
|
||||
if(!nameData.Load("item_names.txt",'\t'))
|
||||
{
|
||||
fprintf(stderr, "item_names.txt 파일을 읽어오지 못했습니다\n");
|
||||
fprintf(stderr, "item_names.txt 파일을 읽어오지 못했습니다\n");
|
||||
isNameFile = false;
|
||||
} else {
|
||||
nameData.Next();
|
||||
@@ -614,32 +624,32 @@ bool CClientManager::InitializeItemTable()
|
||||
//_________________________________________________________________//
|
||||
|
||||
//=================================================================//
|
||||
// 2) 'item_proto_text.txt'파일과 (a)[localMap] 맵으로
|
||||
// (b)[test_map_itemTableByVnum](vnum:TItemTable) 맵을 생성한다.
|
||||
// 2) 'item_proto_text.txt'파일과 (a)[localMap] 맵으로
|
||||
// (b)[test_map_itemTableByVnum](vnum:TItemTable) 맵을 생성한다.
|
||||
//=================================================================//
|
||||
map<DWORD, TItemTable *> test_map_itemTableByVnum;
|
||||
//1. 파일 읽어오기.
|
||||
//1. 파일 읽어오기.
|
||||
cCsvTable test_data;
|
||||
if(!test_data.Load("item_proto_test.txt",'\t'))
|
||||
{
|
||||
fprintf(stderr, "item_proto_test.txt 파일을 읽어오지 못했습니다\n");
|
||||
fprintf(stderr, "item_proto_test.txt 파일을 읽어오지 못했습니다\n");
|
||||
//return false;
|
||||
} else {
|
||||
test_data.Next(); //설명 로우 넘어가기.
|
||||
test_data.Next(); //설명 로우 넘어가기.
|
||||
|
||||
//2. 테스트 아이템 테이블 생성.
|
||||
//2. 테스트 아이템 테이블 생성.
|
||||
TItemTable * test_item_table = NULL;
|
||||
int test_itemTableSize = test_data.m_File.GetRowCount()-1;
|
||||
test_item_table = new TItemTable[test_itemTableSize];
|
||||
memset(test_item_table, 0, sizeof(TItemTable) * test_itemTableSize);
|
||||
|
||||
//3. 테스트 아이템 테이블에 값을 넣고, 맵에까지 넣기.
|
||||
//3. 테스트 아이템 테이블에 값을 넣고, 맵에까지 넣기.
|
||||
while(test_data.Next()) {
|
||||
|
||||
|
||||
if (!Set_Proto_Item_Table(test_item_table, test_data, localMap))
|
||||
{
|
||||
fprintf(stderr, "아이템 프로토 테이블 셋팅 실패.\n");
|
||||
fprintf(stderr, "아이템 프로토 테이블 셋팅 실패.\n");
|
||||
}
|
||||
|
||||
test_map_itemTableByVnum.insert(std::map<DWORD, TItemTable *>::value_type(test_item_table->dwVnum, test_item_table));
|
||||
@@ -651,25 +661,25 @@ bool CClientManager::InitializeItemTable()
|
||||
|
||||
|
||||
//========================================================================//
|
||||
// 3) 'item_proto.txt' 파일과 (a)[localMap] 맵으로
|
||||
// (!)[item_table], <m_map_itemTableByVnum>을 만든다.
|
||||
// <참고>
|
||||
// 각 row 들 중,
|
||||
// (b)[test_map_itemTableByVnum],(!)[mob_table] 모두에 있는 row는
|
||||
// (b)[test_map_itemTableByVnum]의 것을 사용한다.
|
||||
// 3) 'item_proto.txt' 파일과 (a)[localMap] 맵으로
|
||||
// (!)[item_table], <m_map_itemTableByVnum>을 만든다.
|
||||
// <참고>
|
||||
// 각 row 들 중,
|
||||
// (b)[test_map_itemTableByVnum],(!)[mob_table] 모두에 있는 row는
|
||||
// (b)[test_map_itemTableByVnum]의 것을 사용한다.
|
||||
//========================================================================//
|
||||
|
||||
//vnum들을 저장할 셋. 새로운 테스트 아이템을 판별할때 사용된다.
|
||||
//vnum들을 저장할 셋. 새로운 테스트 아이템을 판별할때 사용된다.
|
||||
set<int> vnumSet;
|
||||
|
||||
//파일 읽어오기.
|
||||
//파일 읽어오기.
|
||||
cCsvTable data;
|
||||
if(!data.Load("item_proto.txt",'\t'))
|
||||
{
|
||||
fprintf(stderr, "item_proto.txt 파일을 읽어오지 못했습니다\n");
|
||||
fprintf(stderr, "item_proto.txt 파일을 읽어오지 못했습니다\n");
|
||||
return false;
|
||||
}
|
||||
data.Next(); //맨 윗줄 제외 (아이템 칼럼을 설명하는 부분)
|
||||
data.Next(); //맨 윗줄 제외 (아이템 칼럼을 설명하는 부분)
|
||||
|
||||
if (!m_vec_itemTable.empty())
|
||||
{
|
||||
@@ -678,8 +688,8 @@ bool CClientManager::InitializeItemTable()
|
||||
m_map_itemTableByVnum.clear();
|
||||
}
|
||||
|
||||
//===== 아이템 테이블 생성 =====//
|
||||
//새로 추가되는 갯수를 파악한다.
|
||||
//===== 아이템 테이블 생성 =====//
|
||||
//새로 추가되는 갯수를 파악한다.
|
||||
int addNumber = 0;
|
||||
while(data.Next()) {
|
||||
int vnum = atoi(data.AsStringByIndex(0));
|
||||
@@ -689,14 +699,14 @@ bool CClientManager::InitializeItemTable()
|
||||
addNumber++;
|
||||
}
|
||||
}
|
||||
//data를 다시 첫줄로 옮긴다.(다시 읽어온다;;)
|
||||
//data를 다시 첫줄로 옮긴다.(다시 읽어온다;;)
|
||||
data.Destroy();
|
||||
if(!data.Load("item_proto.txt",'\t'))
|
||||
{
|
||||
fprintf(stderr, "item_proto.txt 파일을 읽어오지 못했습니다\n");
|
||||
fprintf(stderr, "item_proto.txt 파일을 읽어오지 못했습니다\n");
|
||||
return false;
|
||||
}
|
||||
data.Next(); //맨 윗줄 제외 (아이템 칼럼을 설명하는 부분)
|
||||
data.Next(); //맨 윗줄 제외 (아이템 칼럼을 설명하는 부분)
|
||||
|
||||
m_vec_itemTable.resize(data.m_File.GetRowCount() - 1 + addNumber);
|
||||
memset(&m_vec_itemTable[0], 0, sizeof(TItemTable) * m_vec_itemTable.size());
|
||||
@@ -711,16 +721,16 @@ bool CClientManager::InitializeItemTable()
|
||||
std::map<DWORD, TItemTable *>::iterator it_map_itemTable;
|
||||
it_map_itemTable = test_map_itemTableByVnum.find(atoi(data.AsStringByIndex(col)));
|
||||
if(it_map_itemTable == test_map_itemTableByVnum.end()) {
|
||||
//각 칼럼 데이터 저장
|
||||
//각 칼럼 데이터 저장
|
||||
|
||||
if (!Set_Proto_Item_Table(item_table, data, localMap))
|
||||
{
|
||||
fprintf(stderr, "아이템 프로토 테이블 셋팅 실패.\n");
|
||||
fprintf(stderr, "아이템 프로토 테이블 셋팅 실패.\n");
|
||||
}
|
||||
|
||||
|
||||
|
||||
} else { //$$$$$$$$$$$$$$$$$$$$$$$ 테스트 아이템 정보가 있다!
|
||||
} else { //$$$$$$$$$$$$$$$$$$$$$$$ 테스트 아이템 정보가 있다!
|
||||
TItemTable *tempTable = it_map_itemTable->second;
|
||||
|
||||
item_table->dwVnum = tempTable->dwVnum;
|
||||
@@ -777,19 +787,19 @@ bool CClientManager::InitializeItemTable()
|
||||
//_______________________________________________________________________//
|
||||
|
||||
//========================================================================//
|
||||
// 4) (b)[test_map_itemTableByVnum]의 row중, (!)[item_table]에 없는 것을 추가한다.
|
||||
// 4) (b)[test_map_itemTableByVnum]의 row중, (!)[item_table]에 없는 것을 추가한다.
|
||||
//========================================================================//
|
||||
test_data.Destroy();
|
||||
if(!test_data.Load("item_proto_test.txt",'\t'))
|
||||
{
|
||||
fprintf(stderr, "item_proto_test.txt 파일을 읽어오지 못했습니다\n");
|
||||
fprintf(stderr, "item_proto_test.txt 파일을 읽어오지 못했습니다\n");
|
||||
//return false;
|
||||
} else {
|
||||
test_data.Next(); //설명 로우 넘어가기.
|
||||
test_data.Next(); //설명 로우 넘어가기.
|
||||
|
||||
while (test_data.Next()) //테스트 데이터 각각을 훑어나가며,새로운 것을 추가한다.
|
||||
while (test_data.Next()) //테스트 데이터 각각을 훑어나가며,새로운 것을 추가한다.
|
||||
{
|
||||
//중복되는 부분이면 넘어간다.
|
||||
//중복되는 부분이면 넘어간다.
|
||||
set<int>::iterator itVnum;
|
||||
itVnum=vnumSet.find(atoi(test_data.AsStringByIndex(0)));
|
||||
if (itVnum != vnumSet.end()) {
|
||||
@@ -798,7 +808,7 @@ bool CClientManager::InitializeItemTable()
|
||||
|
||||
if (!Set_Proto_Item_Table(item_table, test_data, localMap))
|
||||
{
|
||||
fprintf(stderr, "아이템 프로토 테이블 셋팅 실패.\n");
|
||||
fprintf(stderr, "아이템 프로토 테이블 셋팅 실패.\n");
|
||||
}
|
||||
|
||||
|
||||
@@ -863,6 +873,7 @@ bool CClientManager::InitializeSkillTable()
|
||||
|
||||
std::unique_ptr<SQLMsg> pkMsg(CDBManager::instance().DirectQuery(query));
|
||||
SQLResult * pRes = pkMsg->Get();
|
||||
if (pkMsg->uiSQLErrno || !pRes || pRes->uiNumRows > UINT16_MAX) { sys_err("boot table query failed or exceeds 16-bit wire count"); return false; }
|
||||
|
||||
if (!pRes->uiNumRows)
|
||||
{
|
||||
@@ -876,7 +887,7 @@ bool CClientManager::InitializeSkillTable()
|
||||
m_vec_skillTable.clear();
|
||||
}
|
||||
|
||||
m_vec_skillTable.reserve(pRes->uiNumRows);
|
||||
m_vec_skillTable.reserve(static_cast<size_t>(pRes->uiNumRows));
|
||||
|
||||
MYSQL_ROW data;
|
||||
int col;
|
||||
@@ -945,6 +956,7 @@ bool CClientManager::InitializeBanwordTable()
|
||||
std::unique_ptr<SQLMsg> pkMsg(CDBManager::instance().DirectQuery("SELECT word FROM banword"));
|
||||
|
||||
SQLResult * pRes = pkMsg->Get();
|
||||
if (pkMsg->uiSQLErrno || !pRes || pRes->uiNumRows > UINT16_MAX) { sys_err("boot table query failed or exceeds 16-bit wire count"); return false; }
|
||||
|
||||
if (pRes->uiNumRows == 0)
|
||||
return true;
|
||||
@@ -975,6 +987,7 @@ bool CClientManager::InitializeItemAttrTable()
|
||||
|
||||
std::unique_ptr<SQLMsg> pkMsg(CDBManager::instance().DirectQuery(query));
|
||||
SQLResult * pRes = pkMsg->Get();
|
||||
if (pkMsg->uiSQLErrno || !pRes || pRes->uiNumRows > UINT16_MAX) { sys_err("boot table query failed or exceeds 16-bit wire count"); return false; }
|
||||
|
||||
if (!pRes->uiNumRows)
|
||||
{
|
||||
@@ -988,7 +1001,7 @@ bool CClientManager::InitializeItemAttrTable()
|
||||
m_vec_itemAttrTable.clear();
|
||||
}
|
||||
|
||||
m_vec_itemAttrTable.reserve(pRes->uiNumRows);
|
||||
m_vec_itemAttrTable.reserve(static_cast<size_t>(pRes->uiNumRows));
|
||||
|
||||
MYSQL_ROW data;
|
||||
|
||||
@@ -1049,6 +1062,7 @@ bool CClientManager::InitializeItemRareTable()
|
||||
|
||||
std::unique_ptr<SQLMsg> pkMsg(CDBManager::instance().DirectQuery(query));
|
||||
SQLResult * pRes = pkMsg->Get();
|
||||
if (pkMsg->uiSQLErrno || !pRes || pRes->uiNumRows > UINT16_MAX) { sys_err("boot table query failed or exceeds 16-bit wire count"); return false; }
|
||||
|
||||
if (!pRes->uiNumRows)
|
||||
{
|
||||
@@ -1062,7 +1076,7 @@ bool CClientManager::InitializeItemRareTable()
|
||||
m_vec_itemRareTable.clear();
|
||||
}
|
||||
|
||||
m_vec_itemRareTable.reserve(pRes->uiNumRows);
|
||||
m_vec_itemRareTable.reserve(static_cast<size_t>(pRes->uiNumRows));
|
||||
|
||||
MYSQL_ROW data;
|
||||
|
||||
@@ -1127,6 +1141,7 @@ bool CClientManager::InitializeLandTable()
|
||||
|
||||
std::unique_ptr<SQLMsg> pkMsg(CDBManager::instance().DirectQuery(query));
|
||||
SQLResult * pRes = pkMsg->Get();
|
||||
if (pkMsg->uiSQLErrno || !pRes || pRes->uiNumRows > UINT16_MAX) { sys_err("boot table query failed or exceeds 16-bit wire count"); return false; }
|
||||
|
||||
if (!m_vec_kLandTable.empty())
|
||||
{
|
||||
@@ -1134,7 +1149,7 @@ bool CClientManager::InitializeLandTable()
|
||||
m_vec_kLandTable.clear();
|
||||
}
|
||||
|
||||
m_vec_kLandTable.reserve(pRes->uiNumRows);
|
||||
m_vec_kLandTable.reserve(static_cast<size_t>(pRes->uiNumRows));
|
||||
|
||||
MYSQL_ROW data;
|
||||
|
||||
@@ -1230,6 +1245,7 @@ bool CClientManager::InitializeObjectProto()
|
||||
|
||||
std::unique_ptr<SQLMsg> pkMsg(CDBManager::instance().DirectQuery(query));
|
||||
SQLResult * pRes = pkMsg->Get();
|
||||
if (pkMsg->uiSQLErrno || !pRes || pRes->uiNumRows > UINT16_MAX) { sys_err("boot table query failed or exceeds 16-bit wire count"); return false; }
|
||||
|
||||
if (!m_vec_kObjectProto.empty())
|
||||
{
|
||||
@@ -1237,7 +1253,7 @@ bool CClientManager::InitializeObjectProto()
|
||||
m_vec_kObjectProto.clear();
|
||||
}
|
||||
|
||||
m_vec_kObjectProto.reserve(MAX(0, pRes->uiNumRows));
|
||||
m_vec_kObjectProto.reserve(static_cast<size_t>(pRes->uiNumRows));
|
||||
|
||||
MYSQL_ROW data;
|
||||
|
||||
@@ -1299,6 +1315,7 @@ bool CClientManager::InitializeObjectTable()
|
||||
|
||||
std::unique_ptr<SQLMsg> pkMsg(CDBManager::instance().DirectQuery(query));
|
||||
SQLResult * pRes = pkMsg->Get();
|
||||
if (pkMsg->uiSQLErrno || !pRes || pRes->uiNumRows > UINT16_MAX) { sys_err("boot table query failed or exceeds 16-bit wire count"); return false; }
|
||||
|
||||
if (!m_map_pkObjectTable.empty())
|
||||
{
|
||||
|
||||
@@ -435,7 +435,7 @@ void CClientManager::RESULT_LOGIN(CPeer * peer, SQLMsg * msg)
|
||||
}
|
||||
else
|
||||
{
|
||||
sys_log(0, "RESULT_LOGIN: login success %s rows: %lu", info->pAccountTable->login, msg->Get()->uiNumRows);
|
||||
sys_log(0, "RESULT_LOGIN: login success %s rows: %llu", info->pAccountTable->login, static_cast<unsigned long long>(msg->Get()->uiNumRows));
|
||||
|
||||
if (msg->Get()->uiNumRows > 0)
|
||||
CreateAccountPlayerDataFromRes(msg->Get()->pSQLResult, info->pAccountTable);
|
||||
|
||||
@@ -0,0 +1,757 @@
|
||||
#include "stdafx.h"
|
||||
#ifdef ENABLE_OFFLINESHOP_SYSTEM
|
||||
#include "ClientManager.h"
|
||||
#include "../../common/offline_shop_safety.h"
|
||||
|
||||
void InsertImportLog(const char* logReason, TOfflineShop* p, DWORD targetPID, const char* targetName, const OFFLINE_SHOP_ITEM* item)
|
||||
{
|
||||
char szQuery[QUERY_MAX_LEN];
|
||||
snprintf(szQuery, sizeof(szQuery), "INSERT INTO offline_shop_log_important(reason, owner_id, owner, target_id, target, itemid, itemvnum, itemcount, price, date) VALUES('%s', %u, '%s', %u, '%s', %u, %u, %d, %lld, NOW())",
|
||||
logReason, p ? p->owner_id : 0, p ? p->owner_name : "Noname", targetPID, targetName, item? item->id : 0,item ? item->vnum : 0, item ? item->count : 0, item ? item->price : 0);
|
||||
std::unique_ptr<SQLMsg> pMsgPrice(CDBManager::instance().DirectQuery(szQuery));
|
||||
}
|
||||
|
||||
void CClientManager::OfflineShopAssert(TOfflineShop* p){}
|
||||
|
||||
bool CClientManager::InitializeOfflineShop()
|
||||
{
|
||||
if(!PortOfflineShopEconomyReady())return true; // Do not run legacy expiry/delete cleanup on stored custody.
|
||||
MYSQL_ROW row;
|
||||
//for (size_t j = 1; j <= channelcount; j++)
|
||||
{
|
||||
MYSQL_ROW row_item;
|
||||
char szQuery[QUERY_MAX_LEN];
|
||||
std::unique_ptr<SQLMsg> pMsg(CDBManager::instance().DirectQuery("SELECT * FROM offline_shop_npc"));
|
||||
if (pMsg && pMsg->Get()->uiNumRows != 0)
|
||||
{
|
||||
while (NULL != (row = mysql_fetch_row(pMsg->Get()->pSQLResult)))
|
||||
{
|
||||
TOfflineShop* offlineshop = new TOfflineShop;
|
||||
|
||||
memset(offlineshop, 0, sizeof(TOfflineShop));
|
||||
memset(&offlineshop->items, 0, sizeof(OFFLINE_SHOP_ITEM)*OFFLINE_SHOP_HOST_ITEM_MAX_NUM);
|
||||
memset(&offlineshop->log, 0, sizeof(ShopLog)*OFFLINE_SHOP_HOST_ITEM_MAX_NUM);
|
||||
|
||||
str_to_number(offlineshop->owner_id, row[0]);
|
||||
strlcpy(offlineshop->owner_name, row[1], sizeof(offlineshop->owner_name));
|
||||
strlcpy(offlineshop->sign, row[2], sizeof(offlineshop->sign));
|
||||
str_to_number(offlineshop->x, row[3]);
|
||||
str_to_number(offlineshop->y, row[4]);
|
||||
str_to_number(offlineshop->z, row[5]);
|
||||
str_to_number(offlineshop->mapindex, row[6]);
|
||||
str_to_number(offlineshop->type, row[7]);
|
||||
str_to_number(offlineshop->channel, row[8]);
|
||||
str_to_number(offlineshop->slotflag, row[9]);
|
||||
str_to_number(offlineshop->time, row[10]);
|
||||
|
||||
snprintf(szQuery, sizeof(szQuery), "SELECT shop_money FROM player WHERE id = %u", offlineshop->owner_id);
|
||||
std::unique_ptr<SQLMsg> pMsgPrice(CDBManager::instance().DirectQuery(szQuery));
|
||||
if (pMsgPrice->Get()->uiNumRows != 0)
|
||||
{
|
||||
MYSQL_ROW price = mysql_fetch_row(pMsgPrice->Get()->pSQLResult);
|
||||
str_to_number(offlineshop->price, price[0]);
|
||||
}
|
||||
else
|
||||
offlineshop->price = 0;
|
||||
|
||||
int iLen = snprintf(szQuery, sizeof(szQuery), "SELECT id,owner_id,pos,count,vnum");
|
||||
for (int j = 0; j < ITEM_SOCKET_MAX_NUM; j++)
|
||||
iLen+=snprintf(szQuery+iLen, sizeof(szQuery)-iLen, ",socket%d",j);
|
||||
for (int j = 0; j < ITEM_ATTRIBUTE_MAX_NUM; j++)
|
||||
iLen+=snprintf(szQuery+iLen, sizeof(szQuery)-iLen, ",attrtype%d,attrvalue%d",j,j);
|
||||
iLen+=snprintf(szQuery+iLen, sizeof(szQuery)-iLen, ",price,status,ownername,buyername,HEX(port_extra)");
|
||||
#ifdef ENABLE_CHANGELOOK_SYSTEM
|
||||
iLen+=snprintf(szQuery+iLen, sizeof(szQuery)-iLen, ",transmutation");
|
||||
#endif
|
||||
iLen+=snprintf(szQuery+iLen, sizeof(szQuery)-iLen, " FROM offline_shop_item WHERE owner_id = %u", offlineshop->owner_id);
|
||||
std::unique_ptr<SQLMsg> pMsg2(CDBManager::instance().DirectQuery(szQuery));
|
||||
int cur = 0;
|
||||
BYTE pos = 0;
|
||||
if (pMsg2 && pMsg2->Get()->uiNumRows != 0)
|
||||
{
|
||||
while (NULL != (row_item = mysql_fetch_row(pMsg2->Get()->pSQLResult)))
|
||||
{
|
||||
cur = 0;
|
||||
str_to_number(pos, row_item[2]);
|
||||
if (pos >= OFFLINE_SHOP_HOST_ITEM_MAX_NUM)
|
||||
continue;
|
||||
OFFLINE_SHOP_ITEM& item = offlineshop->items[pos];
|
||||
str_to_number(item.id, row_item[cur++]);
|
||||
str_to_number(item.owner_id, row_item[cur++]);
|
||||
str_to_number(item.pos, row_item[cur++]);
|
||||
str_to_number(item.count, row_item[cur++]);
|
||||
str_to_number(item.vnum, row_item[cur++]);
|
||||
for (int j = 0; j < ITEM_SOCKET_MAX_NUM; j++)
|
||||
str_to_number(item.alSockets[j], row_item[cur++]);
|
||||
for (int j = 0; j < ITEM_ATTRIBUTE_MAX_NUM; j++)
|
||||
{
|
||||
str_to_number(item.aAttr[j].bType, row_item[cur++]);
|
||||
str_to_number(item.aAttr[j].sValue, row_item[cur++]);
|
||||
}
|
||||
str_to_number(item.price, row_item[cur++]);
|
||||
str_to_number(item.status, row_item[cur++]);
|
||||
strlcpy(item.szOwnerName, row_item[cur++], sizeof(item.szOwnerName));
|
||||
strlcpy(item.szBuyerName, row_item[cur++], sizeof(item.szBuyerName));
|
||||
if(!PortItemExtraRead(row_item[cur++],item.extra)){sys_err("OFFLINE_EXTRA_QUARANTINE id=%u",item.id);return false;}
|
||||
#ifdef ENABLE_CHANGELOOK_SYSTEM
|
||||
str_to_number(item.transmutation, row_item[cur++]);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
bool status = false;
|
||||
for (DWORD i = 0; i < OFFLINE_SHOP_HOST_ITEM_MAX_NUM; ++i)
|
||||
{
|
||||
if (offlineshop->items[i].vnum != 0 && offlineshop->items[i].status == 0)
|
||||
{
|
||||
status = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!status)
|
||||
{
|
||||
char szQuery[1024];
|
||||
snprintf(szQuery, sizeof(szQuery), "DELETE FROM offline_shop_npc WHERE owner_id = %u", offlineshop->owner_id);
|
||||
std::unique_ptr<SQLMsg> pMsg2(CDBManager::instance().DirectQuery(szQuery));
|
||||
snprintf(szQuery, sizeof(szQuery), "DELETE FROM offline_shop_item WHERE owner_id = %u", offlineshop->owner_id);
|
||||
std::unique_ptr<SQLMsg> pMsg1(CDBManager::instance().DirectQuery(szQuery));
|
||||
delete offlineshop;
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
int i = 0;
|
||||
snprintf(szQuery, sizeof(szQuery), "SELECT target, time, itemvnum, itemcount, price FROM offline_shop_log WHERE owner_id = %u", offlineshop->owner_id);
|
||||
std::unique_ptr<SQLMsg> pMsg5(CDBManager::instance().DirectQuery(szQuery));
|
||||
if (pMsg5 && pMsg5->Get()->uiNumRows != 0)
|
||||
{
|
||||
MYSQL_ROW log_row = NULL;
|
||||
while ((log_row = mysql_fetch_row(pMsg5->Get()->pSQLResult)))
|
||||
{
|
||||
strlcpy(offlineshop->log[i].name, log_row[0], sizeof(offlineshop->log[i].name));
|
||||
strlcpy(offlineshop->log[i].date, log_row[1], sizeof(offlineshop->log[i].date));
|
||||
str_to_number(offlineshop->log[i].itemVnum, log_row[2]);
|
||||
str_to_number(offlineshop->log[i].itemCount, log_row[3]);
|
||||
str_to_number(offlineshop->log[i].price, log_row[4]);
|
||||
++i;
|
||||
}
|
||||
}
|
||||
|
||||
sys_log(0, "shop insert: owner_id: %u, owner_name: %s, sign: %s,x: %ld,y: %ld,mapIndex: %u, channel: %d",
|
||||
offlineshop->owner_id, offlineshop->owner_name, offlineshop->sign, offlineshop->x, offlineshop->y, offlineshop->mapindex, offlineshop->channel);
|
||||
|
||||
m_Offlineshop.insert(std::make_pair(offlineshop->owner_id, offlineshop));
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void CClientManager::CreateOfflineShop(TOfflineShop* p)
|
||||
{
|
||||
if(!PortOfflineShopEconomyReady())return;
|
||||
if (!p)
|
||||
return;
|
||||
auto it = m_Offlineshop.find(p->owner_id);
|
||||
if (it != m_Offlineshop.end())
|
||||
{
|
||||
sys_err("wtf, this guy have offlineshop???????????? owner id %d name %s", p->owner_id, p->owner_name);
|
||||
OfflineShopAssert(p);// save player items...
|
||||
return;
|
||||
}
|
||||
|
||||
int iLen = 0, iUpdateLen = 0;
|
||||
char szQuery[QUERY_MAX_LEN], szColumns[QUERY_MAX_LEN], szValues[QUERY_MAX_LEN];
|
||||
TOfflineShop* offlineshop = new TOfflineShop;
|
||||
thecore_memcpy(offlineshop, p, sizeof(TOfflineShop));
|
||||
m_Offlineshop.insert(std::make_pair(offlineshop->owner_id, offlineshop));
|
||||
|
||||
snprintf(szQuery, sizeof(szQuery), "SELECT shop_money FROM player WHERE id = %u", offlineshop->owner_id);
|
||||
std::unique_ptr<SQLMsg> pMsgPrice(CDBManager::instance().DirectQuery(szQuery));
|
||||
if (pMsgPrice->Get()->uiNumRows != 0)
|
||||
{
|
||||
MYSQL_ROW price = mysql_fetch_row(pMsgPrice->Get()->pSQLResult);
|
||||
str_to_number(offlineshop->price, price[0]);
|
||||
}
|
||||
else
|
||||
offlineshop->price = 0;
|
||||
|
||||
snprintf(szQuery, sizeof(szQuery), "INSERT INTO offline_shop_npc(owner_id, owner_name, sign, x, y, z, mapindex, type, channel, slotflag, time) VALUES(%u, '%s', '%s', %ld, %ld, %ld, %u, %d, %d, %lld, %d)",
|
||||
offlineshop->owner_id, offlineshop->owner_name, offlineshop->sign, offlineshop->x, offlineshop->y, offlineshop->z, offlineshop->mapindex, offlineshop->type, offlineshop->channel, offlineshop->slotflag, offlineshop->time);
|
||||
std::unique_ptr<SQLMsg> pMsg(CDBManager::Instance().DirectQuery(szQuery));
|
||||
for (DWORD i = 0; i < OFFLINE_SHOP_HOST_ITEM_MAX_NUM; ++i)
|
||||
{
|
||||
if (p->items[i].vnum == 0)
|
||||
continue;
|
||||
|
||||
iLen = snprintf(szColumns, sizeof(szColumns), "id,owner_id,pos,count,price,vnum");
|
||||
iUpdateLen = snprintf(szValues, sizeof(szValues), "%u,%u,%d,%d,%lld,%u", offlineshop->items[i].id, offlineshop->items[i].owner_id, offlineshop->items[i].pos, offlineshop->items[i].count, offlineshop->items[i].price, offlineshop->items[i].vnum);
|
||||
|
||||
for(BYTE j=0;j<ITEM_SOCKET_MAX_NUM;++j)
|
||||
{
|
||||
iLen += snprintf(szColumns + iLen, sizeof(szColumns) - iLen, ",socket%d",j);
|
||||
iUpdateLen += snprintf(szValues + iUpdateLen, sizeof(szValues) - iUpdateLen, ",%ld", offlineshop->items[i].alSockets[j]);
|
||||
}
|
||||
|
||||
for(BYTE j=0;j<ITEM_ATTRIBUTE_MAX_NUM;++j)
|
||||
{
|
||||
iLen += snprintf(szColumns + iLen, sizeof(szColumns) - iLen, ", attrtype%d, attrvalue%d",j,j);
|
||||
iUpdateLen += snprintf(szValues + iUpdateLen, sizeof(szValues) - iUpdateLen, ",%d,%d",offlineshop->items[i].aAttr[j].bType, offlineshop->items[i].aAttr[j].sValue);
|
||||
}
|
||||
|
||||
#ifdef ENABLE_CHANGELOOK_SYSTEM
|
||||
iLen += snprintf(szColumns + iLen, sizeof(szColumns) - iLen, ",transmutation");
|
||||
iUpdateLen += snprintf(szValues + iUpdateLen, sizeof(szValues) - iUpdateLen, ",%d", offlineshop->items[i].transmutation);
|
||||
#endif
|
||||
|
||||
iLen += snprintf(szColumns + iLen, sizeof(szColumns) - iLen, ",ownername,port_extra");
|
||||
iUpdateLen += snprintf(szValues + iUpdateLen, sizeof(szValues) - iUpdateLen, ",'%s',UNHEX('%s')", offlineshop->items[i].szOwnerName,PortItemExtraHex(offlineshop->items[i].extra).c_str());
|
||||
|
||||
snprintf(szQuery, sizeof(szQuery), "INSERT INTO offline_shop_item (%s) VALUES (%s)", szColumns, szValues);
|
||||
std::unique_ptr<SQLMsg> pMsg2(CDBManager::instance().DirectQuery(szQuery));
|
||||
}
|
||||
|
||||
memset(&offlineshop->log, 0, sizeof(ShopLog) * OFFLINE_SHOP_HOST_ITEM_MAX_NUM);
|
||||
int i = 0;
|
||||
snprintf(szQuery, sizeof(szQuery), "SELECT target, time, itemvnum, itemcount, price FROM offline_shop_log WHERE owner_id = %u", offlineshop->owner_id);
|
||||
std::unique_ptr<SQLMsg> pMsg5(CDBManager::instance().DirectQuery(szQuery));
|
||||
if (pMsg5->Get()->uiNumRows != 0)
|
||||
{
|
||||
MYSQL_ROW log_row = NULL;
|
||||
while ((log_row = mysql_fetch_row(pMsg5->Get()->pSQLResult)))
|
||||
{
|
||||
strlcpy(offlineshop->log[i].name, log_row[0], sizeof(offlineshop->log[i].name));
|
||||
strlcpy(offlineshop->log[i].date, log_row[1], sizeof(offlineshop->log[i].date));
|
||||
str_to_number(offlineshop->log[i].itemVnum, log_row[2]);
|
||||
str_to_number(offlineshop->log[i].itemCount, log_row[3]);
|
||||
str_to_number(offlineshop->log[i].price, log_row[4]);
|
||||
++i;
|
||||
}
|
||||
}
|
||||
|
||||
sys_log(0, "shop insert: owner_id: %u, owner_name: %s, sign: %s,x: %ld,y: %ld,mapIndex: %u, channel: %d",
|
||||
offlineshop->owner_id, offlineshop->owner_name, offlineshop->sign, offlineshop->x, offlineshop->y, offlineshop->mapindex, offlineshop->channel);
|
||||
|
||||
// and open this comment for 12h
|
||||
/*
|
||||
int firstOffshopTime = time(0)+(60*60*12);
|
||||
if(offlineshop->time < firstOffshopTime)
|
||||
{
|
||||
offlineshop->time = firstOffshopTime;
|
||||
sys_err("shop insert: negative offshop time.... pid: %d name: %s ",offlineshop->owner_id, offlineshop->owner_name);
|
||||
}
|
||||
*/
|
||||
|
||||
shop_create n;
|
||||
n.subheader = CREATE_OFFLINESHOP;
|
||||
thecore_memcpy(&n.offlineshop, offlineshop, sizeof(n.offlineshop));
|
||||
|
||||
ForwardPacket(HEADER_DG_OFFLINESHOP, &n, sizeof(shop_create));//, 0, peer);
|
||||
}
|
||||
|
||||
void CClientManager::DeleteOfflineShop(DWORD ownerid)
|
||||
{
|
||||
if(!PortOfflineShopEconomyReady())return;
|
||||
auto it = m_Offlineshop.find(ownerid);
|
||||
if (it == m_Offlineshop.end())
|
||||
return;
|
||||
char szQuery[1024];
|
||||
snprintf(szQuery, sizeof(szQuery), "DELETE FROM offline_shop_npc WHERE owner_id = %u", ownerid);
|
||||
std::unique_ptr<SQLMsg> pMsg2(CDBManager::instance().DirectQuery(szQuery));
|
||||
|
||||
snprintf(szQuery, sizeof(szQuery), "DELETE FROM offline_shop_item WHERE owner_id = %u and status = 1", ownerid);
|
||||
std::unique_ptr<SQLMsg> pMsg1(CDBManager::instance().DirectQuery(szQuery));
|
||||
|
||||
delete it->second;
|
||||
it->second = NULL;
|
||||
m_Offlineshop.erase(it);
|
||||
|
||||
sys_log(0, "DeleteOfflineShop %d ",ownerid);
|
||||
|
||||
shop_owner n;
|
||||
n.subheader = DESTROY_OFFLINESHOP;
|
||||
n.owner_id = ownerid;
|
||||
ForwardPacket(HEADER_DG_OFFLINESHOP, &n, sizeof(shop_owner));
|
||||
}
|
||||
|
||||
void CClientManager::RemoveItem(OFFLINE_SHOP_ITEM* item)
|
||||
{
|
||||
if(!PortOfflineShopEconomyReady())return;
|
||||
if(!item || item->pos>=OFFLINE_SHOP_HOST_ITEM_MAX_NUM)return;
|
||||
if (!item)
|
||||
return;
|
||||
auto it = m_Offlineshop.find(item->owner_id);
|
||||
if (it == m_Offlineshop.end())
|
||||
{
|
||||
InsertImportLog("TRY_REMOVE_BUT_NOT_EXIST_SHOP", NULL, item->owner_id, item->szOwnerName, item);
|
||||
// todo player removes items...
|
||||
return;
|
||||
}
|
||||
if (it->second->items[item->pos].vnum == 0)
|
||||
{
|
||||
InsertImportLog("TRY_REMOVE_BUT_NOT_EXIST_ITEM", it->second, item->owner_id, item->szOwnerName, item);
|
||||
return;
|
||||
}
|
||||
|
||||
shop_item n;
|
||||
n.subheader = REMOVE_ITEM;
|
||||
//thecore_memcpy(&n.item, item, sizeof(n.item));
|
||||
thecore_memcpy(&n.item, &it->second->items[item->pos], sizeof(n.item));
|
||||
ForwardPacket(HEADER_DG_OFFLINESHOP, &n, sizeof(shop_item));
|
||||
|
||||
char szQuery[1024];
|
||||
snprintf(szQuery, sizeof(szQuery), "DELETE FROM offline_shop_item WHERE id = %u", item->id);
|
||||
std::unique_ptr<SQLMsg> pMsg2(CDBManager::instance().DirectQuery(szQuery));
|
||||
memset(&it->second->items[item->pos], 0, sizeof(OFFLINE_SHOP_ITEM));
|
||||
sys_log(0, "RemoveItem %d -> vnum %d count %d pos %d price %lld status %d buyername %s ", item->owner_id, item->vnum, item->count, item->pos, item->price, item->status, item->szBuyerName);
|
||||
InsertImportLog("REMOVE_SUCCESFULLY", it->second, item->owner_id, item->szOwnerName, item);
|
||||
}
|
||||
|
||||
|
||||
void CClientManager::AddItem(OFFLINE_SHOP_ITEM* item)
|
||||
{
|
||||
if(!PortOfflineShopEconomyReady())return;
|
||||
if(!item || item->pos>=OFFLINE_SHOP_HOST_ITEM_MAX_NUM)return;
|
||||
if (!item)
|
||||
return;
|
||||
auto it = m_Offlineshop.find(item->owner_id);
|
||||
if (it == m_Offlineshop.end())
|
||||
{
|
||||
InsertImportLog("TRY_ADD_BUT_SHOP_NOT_EXIST", NULL, item->owner_id, item->szOwnerName, item);
|
||||
// todo player removes items...
|
||||
return;
|
||||
}
|
||||
InsertImportLog("ADD_SUCCESFULLY", it->second, item->owner_id, item->szOwnerName, item);
|
||||
thecore_memcpy(&it->second->items[item->pos], item, sizeof(OFFLINE_SHOP_ITEM));
|
||||
OFFLINE_SHOP_ITEM& newitem = it->second->items[item->pos];
|
||||
int iLen = 0, iUpdateLen = 0;
|
||||
char szQuery[QUERY_MAX_LEN], szColumns[QUERY_MAX_LEN], szValues[QUERY_MAX_LEN];
|
||||
|
||||
iLen = snprintf(szColumns, sizeof(szColumns), "id,owner_id,pos,count,price,vnum");
|
||||
iUpdateLen = snprintf(szValues, sizeof(szValues), "%u,%u,%d,%d,%lld,%u", newitem.id, newitem.owner_id, newitem.pos, newitem.count, newitem.price, newitem.vnum);
|
||||
|
||||
for(BYTE j=0;j<ITEM_SOCKET_MAX_NUM;++j)
|
||||
{
|
||||
iLen += snprintf(szColumns + iLen, sizeof(szColumns) - iLen, ",socket%d",j);
|
||||
iUpdateLen += snprintf(szValues + iUpdateLen, sizeof(szValues) - iUpdateLen, ",%ld", newitem.alSockets[j]);
|
||||
}
|
||||
|
||||
for(BYTE j=0;j<ITEM_ATTRIBUTE_MAX_NUM;++j)
|
||||
{
|
||||
iLen += snprintf(szColumns + iLen, sizeof(szColumns) - iLen, ", attrtype%d, attrvalue%d",j,j);
|
||||
iUpdateLen += snprintf(szValues + iUpdateLen, sizeof(szValues) - iUpdateLen, ",%d,%d",newitem.aAttr[j].bType, newitem.aAttr[j].sValue);
|
||||
}
|
||||
|
||||
#ifdef ENABLE_CHANGELOOK_SYSTEM
|
||||
iLen += snprintf(szColumns + iLen, sizeof(szColumns) - iLen, ",transmutation");
|
||||
iUpdateLen += snprintf(szValues + iUpdateLen, sizeof(szValues) - iUpdateLen, ",%d", newitem.transmutation);
|
||||
#endif
|
||||
iLen += snprintf(szColumns + iLen, sizeof(szColumns) - iLen, ",ownername,port_extra");
|
||||
iUpdateLen += snprintf(szValues + iUpdateLen, sizeof(szValues) - iUpdateLen, ",'%s',UNHEX('%s')", newitem.szOwnerName,PortItemExtraHex(newitem.extra).c_str());
|
||||
snprintf(szQuery, sizeof(szQuery), "INSERT INTO offline_shop_item (%s) VALUES (%s)", szColumns, szValues);
|
||||
std::unique_ptr<SQLMsg> pMsg2(CDBManager::instance().DirectQuery(szQuery));
|
||||
|
||||
sys_log(0, "AddItem %d -> vnum %d count %d pos %d price %lld ", newitem.owner_id, newitem.vnum, newitem.count, newitem.pos, newitem.price);
|
||||
|
||||
shop_item n;
|
||||
n.subheader = ADD_ITEM;
|
||||
thecore_memcpy(&n.item, item, sizeof(n.item));
|
||||
ForwardPacket(HEADER_DG_OFFLINESHOP, &n, sizeof(shop_item));
|
||||
|
||||
}
|
||||
|
||||
void CClientManager::BuyItem(TOfflineShopBuy* buyItem)
|
||||
{
|
||||
if(!PortOfflineShopEconomyReady())return;
|
||||
if(!buyItem || buyItem->item.pos>=OFFLINE_SHOP_HOST_ITEM_MAX_NUM)return;
|
||||
if (!buyItem)
|
||||
return;
|
||||
auto it = m_Offlineshop.find(buyItem->item.owner_id);
|
||||
if (it == m_Offlineshop.end())
|
||||
{
|
||||
InsertImportLog("TRY_BUY_BUT_NOT_EXIST_SHOP", NULL, buyItem->customer_id, buyItem->customer_name, NULL);
|
||||
// todo player removes price...
|
||||
return;
|
||||
}
|
||||
|
||||
OFFLINE_SHOP_ITEM& item = it->second->items[buyItem->item.pos];
|
||||
|
||||
if (item.vnum == 0 || item.status != 0)
|
||||
{
|
||||
InsertImportLog("TRY_BUY_BUT_ALREADY_SELLED", it->second, buyItem->customer_id, buyItem->customer_name, &item);
|
||||
return;
|
||||
}
|
||||
|
||||
char szQuery[QUERY_MAX_LEN];
|
||||
snprintf(szQuery, sizeof(szQuery), "UPDATE player SET shop_money = shop_money + %lld WHERE id = %u", buyItem->item.price, buyItem->item.owner_id);
|
||||
std::unique_ptr<SQLMsg> pMsg1(CDBManager::instance().DirectQuery(szQuery));
|
||||
it->second->price += buyItem->item.price;
|
||||
item.status = 1;
|
||||
strlcpy(item.szBuyerName, buyItem->customer_name, sizeof(item.szBuyerName));
|
||||
|
||||
memset(&buyItem->log, 0, sizeof(buyItem->log));
|
||||
buyItem->log_index = -1;
|
||||
InsertImportLog("BUY_SUCCESFULLY", it->second, buyItem->customer_id, buyItem->customer_name, &item);
|
||||
|
||||
for (DWORD i = 0; i < OFFLINE_SHOP_HOST_ITEM_MAX_NUM; i++)
|
||||
{
|
||||
ShopLog& log = it->second->log[i];
|
||||
if (log.price != 0)
|
||||
continue;
|
||||
|
||||
time_t now = time(0);
|
||||
struct tm tstruct;
|
||||
char buf[80];
|
||||
tstruct = *localtime(&now);
|
||||
strftime(buf, sizeof(buf), "%X-%d.%m.%Y", &tstruct);
|
||||
|
||||
strlcpy(log.date, buf, sizeof(log.date));
|
||||
log.itemCount = item.count;
|
||||
log.itemVnum = item.vnum;
|
||||
strlcpy(log.name, buyItem->customer_name, sizeof(log.name));
|
||||
log.price = item.price;
|
||||
|
||||
buyItem->log_index = i;
|
||||
thecore_memcpy(&buyItem->log,&log, sizeof(buyItem->log));
|
||||
|
||||
int iLen = snprintf(szQuery, sizeof(szQuery), "INSERT INTO offline_shop_log ("
|
||||
"owner_id, target, time, itemvnum, itemcount, price"
|
||||
",item_id, pos"
|
||||
#ifdef ENABLE_CHANGELOOK_SYSTEM
|
||||
",transmutation"
|
||||
#endif
|
||||
);
|
||||
|
||||
for(BYTE j=0;j<ITEM_SOCKET_MAX_NUM;++j)
|
||||
iLen += snprintf(szQuery+iLen, sizeof(szQuery)-iLen, ", socket%d",j);
|
||||
|
||||
for(BYTE j=0;j<ITEM_ATTRIBUTE_MAX_NUM;++j)
|
||||
iLen += snprintf(szQuery+iLen, sizeof(szQuery)-iLen, ", attrtype%d, attrvalue%d",j,j);
|
||||
|
||||
iLen += snprintf(szQuery+iLen, sizeof(szQuery)-iLen, ") VALUES("
|
||||
"%u, '%s', '%s', %d, %d, %lld"
|
||||
",%u, %d"
|
||||
#ifdef ENABLE_CHANGELOOK_SYSTEM
|
||||
",%d"
|
||||
#endif
|
||||
,item.owner_id, buyItem->customer_name, buf, item.vnum, item.count, item.price,
|
||||
item.id, item.pos
|
||||
#ifdef ENABLE_CHANGELOOK_SYSTEM
|
||||
,item.transmutation
|
||||
#endif
|
||||
);
|
||||
for(BYTE j=0;j<ITEM_SOCKET_MAX_NUM;++j)
|
||||
iLen += snprintf(szQuery+iLen, sizeof(szQuery)-iLen, ", %ld",item.alSockets[j]);
|
||||
for(BYTE j=0;j<ITEM_ATTRIBUTE_MAX_NUM;++j)
|
||||
iLen += snprintf(szQuery+iLen, sizeof(szQuery)-iLen, ", %d, %d",item.aAttr[j].bType, item.aAttr[j].sValue);
|
||||
iLen += snprintf(szQuery+iLen, sizeof(szQuery)-iLen, ")");
|
||||
std::unique_ptr<SQLMsg> pMsg2(CDBManager::instance().DirectQuery(szQuery));
|
||||
break;
|
||||
}
|
||||
snprintf(szQuery, sizeof(szQuery), "UPDATE offline_shop_item SET status = 1, buyername = '%s' WHERE id = %u and owner_id = %u", buyItem->customer_name,buyItem->item.id, buyItem->item.owner_id);
|
||||
std::unique_ptr<SQLMsg> pMsg2(CDBManager::instance().DirectQuery(szQuery));
|
||||
thecore_memcpy(&buyItem->item, &item, sizeof(buyItem->item));
|
||||
sys_log(0, "BuyItem %d -> buyer name %s vnum %d count %d pos %d price %lld ", buyItem->item.owner_id, buyItem->customer_name, buyItem->item.vnum, buyItem->item.count, buyItem->item.pos, buyItem->item.price);
|
||||
|
||||
shop_buy n;
|
||||
n.subheader = BUY_ITEM;
|
||||
thecore_memcpy(&n.buyItem, buyItem, sizeof(n.buyItem));
|
||||
ForwardPacket(HEADER_DG_OFFLINESHOP, &n, sizeof(shop_buy));
|
||||
}
|
||||
|
||||
void CClientManager::WithdrawMoney(DWORD ch)
|
||||
{
|
||||
if(!PortOfflineShopEconomyReady())return;
|
||||
auto it = m_Offlineshop.find(ch);
|
||||
if (it == m_Offlineshop.end())
|
||||
// todo player removes price...
|
||||
return;
|
||||
if (it->second->price == 0)
|
||||
return;
|
||||
char szQuery[QUERY_MAX_LEN];
|
||||
snprintf(szQuery, sizeof(szQuery), "UPDATE player SET shop_money = 0 WHERE id = '%u'",ch);
|
||||
std::unique_ptr<SQLMsg> pMsg(CDBManager::instance().DirectQuery(szQuery));
|
||||
|
||||
sys_log(0, "WithdrawMoney %d -> %lld ", ch, it->second->price);
|
||||
it->second->price = 0;
|
||||
|
||||
shop_owner n;
|
||||
n.subheader = WITHDRAW_MONEY;
|
||||
n.owner_id = ch;
|
||||
ForwardPacket(HEADER_DG_OFFLINESHOP, &n, sizeof(shop_owner));
|
||||
}
|
||||
|
||||
void CClientManager::ChangeTitle(TOfflineShopChangeTitle* p)
|
||||
{
|
||||
if (!p)
|
||||
return;
|
||||
auto it = m_Offlineshop.find(p->owner_id);
|
||||
if (it == m_Offlineshop.end())
|
||||
// todo player removes price...
|
||||
return;
|
||||
strlcpy(it->second->sign, p->sign, sizeof(it->second->sign));
|
||||
char szQuery[1024 + 1];
|
||||
snprintf(szQuery, sizeof(szQuery), "UPDATE offline_shop_npc SET sign = '%s' WHERE owner_id = '%d'", p->sign, p->owner_id);
|
||||
std::unique_ptr<SQLMsg> pmsg(CDBManager::instance().DirectQuery(szQuery));
|
||||
sys_log(0, "ChangeTitle %d -> %s ", p->owner_id, p->sign);
|
||||
|
||||
|
||||
shop_title n;
|
||||
n.subheader = CHANGE_TITLE;
|
||||
thecore_memcpy(&n.title, p, sizeof(n.title));
|
||||
ForwardPacket(HEADER_DG_OFFLINESHOP,&n, sizeof(shop_title));
|
||||
}
|
||||
|
||||
void CClientManager::ClearLog(DWORD ch)
|
||||
{
|
||||
auto it = m_Offlineshop.find(ch);
|
||||
if (it == m_Offlineshop.end())
|
||||
return;
|
||||
memset(&it->second->log, 0, sizeof(it->second->log));
|
||||
char szQuery[1024];
|
||||
snprintf(szQuery, sizeof(szQuery), "DELETE FROM offline_shop_log WHERE owner_id = %u", it->second->owner_id);
|
||||
std::unique_ptr<SQLMsg> pMsg(CDBManager::instance().DirectQuery(szQuery));
|
||||
sys_log(0, "ClearLog %d ", ch);
|
||||
|
||||
shop_owner n;
|
||||
n.subheader = CLEAR_LOG;
|
||||
n.owner_id = ch;
|
||||
ForwardPacket(HEADER_DG_OFFLINESHOP, &n, sizeof(shop_owner));
|
||||
}
|
||||
|
||||
void CClientManager::ChangeDecoration(TShopDecoration* ch)
|
||||
{
|
||||
if (!ch)
|
||||
return;
|
||||
auto it = m_Offlineshop.find(ch->owner_id);
|
||||
if (it == m_Offlineshop.end())
|
||||
return;
|
||||
it->second->type = 30000 + ch->vnum;
|
||||
strlcpy(it->second->sign, ch->sign, sizeof(it->second->sign));
|
||||
|
||||
char szQuery[1024];
|
||||
snprintf(szQuery, sizeof(szQuery), "UPDATE offline_shop_npc SET type = %d, sign = '%s' WHERE owner_id = %u", it->second->type, it->second->sign,it->first);
|
||||
std::unique_ptr<SQLMsg> pMsg(CDBManager::instance().DirectQuery(szQuery));
|
||||
sys_log(0, "ChangeDecoration %d -> %d %s ", ch->owner_id, 30000 + ch->vnum, ch->sign);
|
||||
|
||||
shop_decoration n;
|
||||
n.subheader = CHANGE_DECORATION;
|
||||
thecore_memcpy(&n.decoration, ch, sizeof(n.decoration));
|
||||
ForwardPacket(HEADER_DG_OFFLINESHOP, &n, sizeof(shop_decoration));
|
||||
}
|
||||
|
||||
void CClientManager::OpenSlot(TOfflineShopOpenSlot* ch)
|
||||
{
|
||||
if (!ch)
|
||||
return;
|
||||
auto it = m_Offlineshop.find(ch->owner_id);
|
||||
if (it == m_Offlineshop.end())
|
||||
return;
|
||||
it->second->slotflag = ch->flag;
|
||||
char szQuery[1024];
|
||||
snprintf(szQuery, sizeof(szQuery), "UPDATE offline_shop_npc SET slotflag = %lld WHERE owner_id = %u", ch->flag,ch->owner_id);
|
||||
std::unique_ptr<SQLMsg> pMsg(CDBManager::instance().DirectQuery(szQuery));
|
||||
sys_log(0, "OpenSlot %d -> %lld ", ch->owner_id, ch->flag);
|
||||
|
||||
shop_slot n;
|
||||
n.subheader = CHANGE_OPEN_SLOT;
|
||||
thecore_memcpy(&n.ch, ch, sizeof(n.ch));
|
||||
ForwardPacket(HEADER_DG_OFFLINESHOP, &n, sizeof(shop_slot));
|
||||
|
||||
}
|
||||
|
||||
void CClientManager::TimeDone(DWORD ch)
|
||||
{
|
||||
auto it = m_Offlineshop.find(ch);
|
||||
if (it == m_Offlineshop.end())
|
||||
return;
|
||||
sys_log(0, "TimeDone %d ", ch);
|
||||
|
||||
bool status = true;
|
||||
for (DWORD i = 0; i < OFFLINE_SHOP_HOST_ITEM_MAX_NUM; ++i)
|
||||
{
|
||||
if (it->second->items[i].vnum != 0 && it->second->items[i].status == 0) {
|
||||
status = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (status)
|
||||
{
|
||||
char szQuery[1024];
|
||||
snprintf(szQuery, sizeof(szQuery), "DELETE FROM offline_shop_npc WHERE owner_id = %u", ch);
|
||||
std::unique_ptr<SQLMsg> pMsg2(CDBManager::instance().DirectQuery(szQuery));
|
||||
snprintf(szQuery, sizeof(szQuery), "DELETE FROM offline_shop_item WHERE owner_id = %u", ch);
|
||||
std::unique_ptr<SQLMsg> pMsg1(CDBManager::instance().DirectQuery(szQuery));
|
||||
delete it->second;
|
||||
it->second = NULL;
|
||||
m_Offlineshop.erase(it);
|
||||
|
||||
sys_log(0, "TimeDone: %d shop closed. 0 item.", ch);
|
||||
}
|
||||
else
|
||||
sys_log(0, "TimeDone: %d ", ch);
|
||||
|
||||
shop_owner n;
|
||||
n.subheader = TIME_DONE;
|
||||
n.owner_id = ch;
|
||||
ForwardPacket(HEADER_DG_OFFLINESHOP, &n, sizeof(shop_owner));
|
||||
}
|
||||
|
||||
void CClientManager::GetBackItem(DWORD ch)
|
||||
{
|
||||
auto it = m_Offlineshop.find(ch);
|
||||
if (it == m_Offlineshop.end())
|
||||
return;
|
||||
|
||||
char szQuery[1024];
|
||||
snprintf(szQuery, sizeof(szQuery), "DELETE FROM offline_shop_npc WHERE owner_id = %u", ch);
|
||||
std::unique_ptr<SQLMsg> pMsg2(CDBManager::instance().DirectQuery(szQuery));
|
||||
|
||||
snprintf(szQuery, sizeof(szQuery), "DELETE FROM offline_shop_item WHERE owner_id = %u", ch);
|
||||
std::unique_ptr<SQLMsg> pMsg1(CDBManager::instance().DirectQuery(szQuery));
|
||||
|
||||
shop_back n;
|
||||
n.subheader = GET_BACK_ITEM;
|
||||
n.back.owner_id = ch;
|
||||
thecore_memcpy(&n.back.items, &it->second->items, sizeof(n.back.items));
|
||||
ForwardPacket(HEADER_DG_OFFLINESHOP, &n, sizeof(shop_back));
|
||||
|
||||
delete it->second;
|
||||
it->second = NULL;
|
||||
m_Offlineshop.erase(it);
|
||||
sys_log(0, "GetBackItem %d ", ch);
|
||||
}
|
||||
|
||||
void CClientManager::AddTime(DWORD ch)
|
||||
{
|
||||
auto it = m_Offlineshop.find(ch);
|
||||
if (it == m_Offlineshop.end())
|
||||
return;
|
||||
int oldtime = it->second->time-time(0);
|
||||
int addtime = (60 * 60 * 12);
|
||||
//int newTime = MIN((60*60*24*3) - oldtime, addtime);
|
||||
it->second->time = time(0) + (oldtime+ addtime);
|
||||
sys_log(0, "AddTime %d ", ch);
|
||||
|
||||
char szQuery[1024];
|
||||
snprintf(szQuery, sizeof(szQuery), "UPDATE offline_shop_npc SET time = %d WHERE owner_id = %u", it->second->time, it->second->owner_id);
|
||||
std::unique_ptr<SQLMsg> pMsg(CDBManager::instance().DirectQuery(szQuery));
|
||||
|
||||
shop_owner n;
|
||||
n.subheader = ADD_TIME;
|
||||
n.owner_id = ch;
|
||||
ForwardPacket(HEADER_DG_OFFLINESHOP, &n, sizeof(shop_owner));
|
||||
}
|
||||
|
||||
void CClientManager::RecvPackets(const char* data)
|
||||
{
|
||||
if(!PortOfflineShopEconomyReady())return;
|
||||
BYTE sub_header = (BYTE)*data;
|
||||
switch (sub_header)
|
||||
{
|
||||
case CREATE_OFFLINESHOP:
|
||||
{
|
||||
shop_create* p = (shop_create*)data;
|
||||
if (p)
|
||||
CreateOfflineShop(&p->offlineshop);
|
||||
}
|
||||
break;
|
||||
case DESTROY_OFFLINESHOP:
|
||||
{
|
||||
shop_owner* p = (shop_owner*)data;
|
||||
if (p)
|
||||
DeleteOfflineShop(p->owner_id);
|
||||
}
|
||||
break;
|
||||
case ADD_ITEM:
|
||||
{
|
||||
shop_item* p = (shop_item*)data;
|
||||
if (p)
|
||||
AddItem(&p->item);
|
||||
}
|
||||
break;
|
||||
case REMOVE_ITEM:
|
||||
{
|
||||
shop_item* p = (shop_item*)data;
|
||||
if (p)
|
||||
RemoveItem(&p->item);
|
||||
}
|
||||
break;
|
||||
case BUY_ITEM:
|
||||
{
|
||||
shop_buy* p = (shop_buy*)data;
|
||||
if (p)
|
||||
BuyItem(&p->buyItem);
|
||||
}
|
||||
break;
|
||||
case CHANGE_TITLE:
|
||||
{
|
||||
shop_title* p = (shop_title*)data;
|
||||
if (p)
|
||||
ChangeTitle(&p->title);
|
||||
}
|
||||
break;
|
||||
|
||||
case WITHDRAW_MONEY:
|
||||
{
|
||||
shop_owner* p = (shop_owner*)data;
|
||||
if (p)
|
||||
WithdrawMoney(p->owner_id);
|
||||
}
|
||||
break;
|
||||
|
||||
case CLEAR_LOG:
|
||||
{
|
||||
shop_owner* p = (shop_owner*)data;
|
||||
if (p)
|
||||
ClearLog(p->owner_id);
|
||||
}
|
||||
break;
|
||||
|
||||
case CHANGE_DECORATION:
|
||||
{
|
||||
shop_decoration* p = (shop_decoration*)data;
|
||||
if (p)
|
||||
ChangeDecoration(&p->decoration);
|
||||
}
|
||||
break;
|
||||
|
||||
case CHANGE_OPEN_SLOT:
|
||||
{
|
||||
shop_slot* p = (shop_slot*)data;
|
||||
if (p)
|
||||
OpenSlot(&p->ch);
|
||||
}
|
||||
break;
|
||||
|
||||
case TIME_DONE:
|
||||
{
|
||||
shop_owner* p = (shop_owner*)data;
|
||||
if (p)
|
||||
TimeDone(p->owner_id);
|
||||
}
|
||||
break;
|
||||
|
||||
case GET_BACK_ITEM:
|
||||
{
|
||||
shop_owner* p = (shop_owner*)data;
|
||||
if (p)
|
||||
GetBackItem(p->owner_id);
|
||||
}
|
||||
break;
|
||||
|
||||
case ADD_TIME:
|
||||
{
|
||||
shop_owner* p = (shop_owner*)data;
|
||||
if (p)
|
||||
AddTime(p->owner_id);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
sys_err("unkown offlineshop subheader %d", sub_header);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -22,6 +22,22 @@ extern int g_log;
|
||||
//
|
||||
// Check all SELECT syntax on item table before change this function!!!
|
||||
//
|
||||
bool CClientManager::ValidateLoadedExtra(const TPlayerItem& item,const char* hex) const {
|
||||
auto found=m_map_itemTableByVnum.find(item.vnum);
|
||||
if(found==m_map_itemTableByVnum.end())return false;
|
||||
const auto* proto=found->second;
|
||||
if(proto->bType!=ITEM_PET || proto->bSubType!=PET_LEVELABLE)return true;
|
||||
if(!hex || strlen(hex)!=138 || item.alSockets[1]<1 || item.alSockets[1]>120 || item.alSockets[2]<0 ||
|
||||
item.extra.sockets[0]<0 || item.extra.sockets[0]>3 || item.extra.sockets[1]<0 || item.extra.sockets[1]>15)return false;
|
||||
for(unsigned i=2;i<5;++i)if(item.extra.sockets[i]<0 || item.extra.sockets[i]>20)return false;
|
||||
for(unsigned i=0;i<15;++i){
|
||||
const unsigned type=i<7?item.aAttr[i].bType:item.extra.types[i-7];
|
||||
const int value=i<7?item.aAttr[i].sValue:item.extra.values[i-7];
|
||||
if((type>29 && type!=99) || value<0 || value>20 || ((type==0||type==99)&&value!=0))return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CreateItemTableFromRes(MYSQL_RES * res, std::vector<TPlayerItem> * pVec, DWORD dwPID)
|
||||
{
|
||||
if (!res)
|
||||
@@ -32,7 +48,7 @@ bool CreateItemTableFromRes(MYSQL_RES * res, std::vector<TPlayerItem> * pVec, DW
|
||||
|
||||
int rows;
|
||||
|
||||
if ((rows = mysql_num_rows(res)) <= 0) // 데이터 없음
|
||||
if ((rows = mysql_num_rows(res)) <= 0) // 데이터 없음
|
||||
{
|
||||
pVec->clear();
|
||||
return true;
|
||||
@@ -65,7 +81,12 @@ bool CreateItemTableFromRes(MYSQL_RES * res, std::vector<TPlayerItem> * pVec, DW
|
||||
str_to_number(item.aAttr[j].sValue, row[cur++]);
|
||||
}
|
||||
|
||||
PortItemExtraRead(mysql_num_fields(res)>unsigned(cur)?row[cur]:NULL,item.extra);
|
||||
if (!PortItemExtraRead(mysql_num_fields(res)>unsigned(cur)?row[cur]:NULL,item.extra) ||
|
||||
!CClientManager::instance().ValidateLoadedExtra(item,mysql_num_fields(res)>unsigned(cur)?row[cur]:NULL)) {
|
||||
// Original bytes stay in SQL. Do not create caches or return partial inventory.
|
||||
sys_err("ITEM_EXTRA_QUARANTINE owner=%u item=%u window=%u: invalid port_extra", dwPID,item.id,item.window);
|
||||
pVec->clear();return false;
|
||||
}
|
||||
item.owner = dwPID;
|
||||
}
|
||||
|
||||
@@ -100,7 +121,7 @@ size_t CreatePlayerSaveQuery(char * pszQuery, size_t querySize, TPlayerTable * p
|
||||
"ht = %d, "
|
||||
"dx = %d, "
|
||||
"iq = %d, "
|
||||
"gold = %d, "
|
||||
"gold = %lld, "
|
||||
"exp = %u, "
|
||||
"stat_point = %d, "
|
||||
"skill_point = %d, "
|
||||
@@ -118,6 +139,12 @@ size_t CreatePlayerSaveQuery(char * pszQuery, size_t querySize, TPlayerTable * p
|
||||
"horse_hp_droptime = %u, "
|
||||
"horse_stamina = %d, "
|
||||
"horse_skill_point = %d, "
|
||||
#ifdef UNLOCK_INVENTORY_WORLDARD
|
||||
"inventory_0 = %u, inventory_1 = %u, inventory_2 = %u, inventory_3 = %u, inventory_4 = %u, inventory_5 = %u, "
|
||||
#endif
|
||||
#ifdef ENABLE_OFFLINESHOP_SYSTEM
|
||||
"shopFlag = %llu, "
|
||||
#endif
|
||||
,
|
||||
GetTablePostfix(),
|
||||
pkTab->job,
|
||||
@@ -142,7 +169,7 @@ size_t CreatePlayerSaveQuery(char * pszQuery, size_t querySize, TPlayerTable * p
|
||||
pkTab->ht,
|
||||
pkTab->dx,
|
||||
pkTab->iq,
|
||||
pkTab->gold,
|
||||
(long long) pkTab->gold,
|
||||
pkTab->exp,
|
||||
pkTab->stat_point,
|
||||
pkTab->skill_point,
|
||||
@@ -158,9 +185,21 @@ size_t CreatePlayerSaveQuery(char * pszQuery, size_t querySize, TPlayerTable * p
|
||||
pkTab->horse.sHealth,
|
||||
pkTab->horse.dwHorseHealthDropTime,
|
||||
pkTab->horse.sStamina,
|
||||
pkTab->horse_skill_point);
|
||||
pkTab->horse_skill_point
|
||||
#ifdef UNLOCK_INVENTORY_WORLDARD
|
||||
, pkTab->inventory_unlock[0]
|
||||
, pkTab->inventory_unlock[1]
|
||||
, pkTab->inventory_unlock[2]
|
||||
, pkTab->inventory_unlock[3]
|
||||
, pkTab->inventory_unlock[4]
|
||||
, pkTab->inventory_unlock[5]
|
||||
#endif
|
||||
#ifdef ENABLE_OFFLINESHOP_SYSTEM
|
||||
, pkTab->shopFlag
|
||||
#endif
|
||||
);
|
||||
|
||||
// Binary 로 바꾸기 위한 임시 공간
|
||||
// Binary 로 바꾸기 위한 임시 공간
|
||||
static char text[8192 + 1];
|
||||
|
||||
CDBManager::instance().EscapeString(text, pkTab->skills, sizeof(pkTab->skills));
|
||||
@@ -208,11 +247,12 @@ void CClientManager::PutPlayerCache(TPlayerTable * pNew)
|
||||
*/
|
||||
void CClientManager::QUERY_PLAYER_LOAD(CPeer * peer, DWORD dwHandle, TPlayerLoadPacket * packet)
|
||||
{
|
||||
if(!EconomyBeforeLoad(peer,dwHandle,packet)){if(!m_economyFences.count(packet->player_id))peer->EncodeHeader(HEADER_DG_PLAYER_LOAD_FAILED,dwHandle,0);return;}
|
||||
CPlayerTableCache * c;
|
||||
TPlayerTable * pTab;
|
||||
|
||||
//
|
||||
// 한 계정에 속한 모든 캐릭터들 캐쉬처리
|
||||
// 한 계정에 속한 모든 캐릭터들 캐쉬처리
|
||||
//
|
||||
CLoginData * pLoginData = GetLoginDataByAID(packet->account_id);
|
||||
|
||||
@@ -224,12 +264,12 @@ void CClientManager::QUERY_PLAYER_LOAD(CPeer * peer, DWORD dwHandle, TPlayerLoad
|
||||
}
|
||||
|
||||
//----------------------------------------------------------------
|
||||
// 1. 유저정보가 DBCache 에 존재 : DBCache에서
|
||||
// 2. 유저정보가 DBCache 에 없음 : DB에서
|
||||
// 1. 유저정보가 DBCache 에 존재 : DBCache에서
|
||||
// 2. 유저정보가 DBCache 에 없음 : DB에서
|
||||
// ---------------------------------------------------------------
|
||||
|
||||
//----------------------------------
|
||||
// 1. 유저정보가 DBCache 에 존재 : DBCache에서
|
||||
// 1. 유저정보가 DBCache 에 존재 : DBCache에서
|
||||
//----------------------------------
|
||||
if ((c = GetPlayerCache(packet->player_id)))
|
||||
{
|
||||
@@ -266,16 +306,16 @@ void CClientManager::QUERY_PLAYER_LOAD(CPeer * peer, DWORD dwHandle, TPlayerLoad
|
||||
|
||||
TItemCacheSet * pSet = GetItemCacheSet(pTab->id);
|
||||
|
||||
sys_log(0, "[PLAYER_LOAD] ID %s pid %d gold %d ", pTab->name, pTab->id, pTab->gold);
|
||||
sys_log(0, "[PLAYER_LOAD] ID %s pid %d gold %lld ", pTab->name, pTab->id, (long long) pTab->gold);
|
||||
|
||||
//--------------------------------------------
|
||||
// 아이템 & AFFECT & QUEST 로딩 :
|
||||
// 아이템 & AFFECT & QUEST 로딩 :
|
||||
//--------------------------------------------
|
||||
// 1) 아이템이 DBCache 에 존재 : DBCache 에서 가져옴
|
||||
// 2) 아이템이 DBCache 에 없음 : DB 에서 가져옴
|
||||
// 1) 아이템이 DBCache 에 존재 : DBCache 에서 가져옴
|
||||
// 2) 아이템이 DBCache 에 없음 : DB 에서 가져옴
|
||||
|
||||
/////////////////////////////////////////////
|
||||
// 1) 아이템이 DBCache 에 존재 : DBCache 에서 가져옴
|
||||
// 1) 아이템이 DBCache 에 존재 : DBCache 에서 가져옴
|
||||
/////////////////////////////////////////////
|
||||
if (pSet)
|
||||
{
|
||||
@@ -290,7 +330,7 @@ void CClientManager::QUERY_PLAYER_LOAD(CPeer * peer, DWORD dwHandle, TPlayerLoad
|
||||
CItemCache * c = *it++;
|
||||
TPlayerItem * p = c->Get();
|
||||
|
||||
if (p->vnum) // vnum이 없으면 삭제된 아이템이다.
|
||||
if (p->vnum) // vnum이 없으면 삭제된 아이템이다.
|
||||
thecore_memcpy(&s_items[dwCount++], p, sizeof(TPlayerItem));
|
||||
}
|
||||
|
||||
@@ -317,14 +357,22 @@ void CClientManager::QUERY_PLAYER_LOAD(CPeer * peer, DWORD dwHandle, TPlayerLoad
|
||||
CDBManager::instance().ReturnQuery(szQuery, QID_AFFECT, peer->GetHandle(), new ClientHandleInfo(dwHandle));
|
||||
}
|
||||
/////////////////////////////////////////////
|
||||
// 2) 아이템이 DBCache 에 없음 : DB 에서 가져옴
|
||||
// 2) 아이템이 DBCache 에 없음 : DB 에서 가져옴
|
||||
/////////////////////////////////////////////
|
||||
else
|
||||
{
|
||||
snprintf(szQuery, sizeof(szQuery),
|
||||
"SELECT id,window+0,pos,count,vnum,socket0,socket1,socket2,attrtype0,attrvalue0,attrtype1,attrvalue1,attrtype2,attrvalue2,attrtype3,attrvalue3,attrtype4,attrvalue4,attrtype5,attrvalue5,attrtype6,attrvalue6,HEX(port_extra) "
|
||||
"FROM item%s WHERE owner_id=%d AND (window < %d or window = %d or window = %d)",
|
||||
GetTablePostfix(), pTab->id, SAFEBOX, DRAGON_SOUL_INVENTORY, SWITCHBOT);
|
||||
"FROM item%s WHERE owner_id=%d AND (window < %d or window = %d or window = %d"
|
||||
#ifdef ENABLE_SPECIAL_STORAGE
|
||||
" or (window >= %d and window <= %d)"
|
||||
#endif
|
||||
")",
|
||||
GetTablePostfix(), pTab->id, SAFEBOX, DRAGON_SOUL_INVENTORY, SWITCHBOT
|
||||
#ifdef ENABLE_SPECIAL_STORAGE
|
||||
, UPGRADE_INVENTORY, COSTUME_INVENTORY
|
||||
#endif
|
||||
);
|
||||
|
||||
CDBManager::instance().ReturnQuery(szQuery,
|
||||
QID_ITEM,
|
||||
@@ -351,7 +399,7 @@ void CClientManager::QUERY_PLAYER_LOAD(CPeer * peer, DWORD dwHandle, TPlayerLoad
|
||||
//return;
|
||||
}
|
||||
//----------------------------------
|
||||
// 2. 유저정보가 DBCache 에 없음 : DB에서
|
||||
// 2. 유저정보가 DBCache 에 없음 : DB에서
|
||||
//----------------------------------
|
||||
else
|
||||
{
|
||||
@@ -360,7 +408,7 @@ void CClientManager::QUERY_PLAYER_LOAD(CPeer * peer, DWORD dwHandle, TPlayerLoad
|
||||
char queryStr[QUERY_MAX_LEN];
|
||||
|
||||
//--------------------------------------------------------------
|
||||
// 캐릭터 정보 얻어오기 : 무조건 DB에서
|
||||
// 캐릭터 정보 얻어오기 : 무조건 DB에서
|
||||
//--------------------------------------------------------------
|
||||
snprintf(queryStr, sizeof(queryStr),
|
||||
"SELECT "
|
||||
@@ -368,7 +416,14 @@ void CClientManager::QUERY_PLAYER_LOAD(CPeer * peer, DWORD dwHandle, TPlayerLoad
|
||||
"gold,level,level_step,st,ht,dx,iq,exp,"
|
||||
"stat_point,skill_point,sub_skill_point,stat_reset_count,part_base,part_hair,"
|
||||
"skill_level,quickslot,skill_group,alignment,mobile,horse_level,horse_riding,horse_hp,horse_hp_droptime,horse_stamina,"
|
||||
"UNIX_TIMESTAMP(NOW())-UNIX_TIMESTAMP(last_play),horse_skill_point FROM player%s WHERE id=%d",
|
||||
"UNIX_TIMESTAMP(NOW())-UNIX_TIMESTAMP(last_play),horse_skill_point"
|
||||
#ifdef UNLOCK_INVENTORY_WORLDARD
|
||||
",inventory_0,inventory_1,inventory_2,inventory_3,inventory_4,inventory_5"
|
||||
#endif
|
||||
#ifdef ENABLE_OFFLINESHOP_SYSTEM
|
||||
",shopFlag"
|
||||
#endif
|
||||
" FROM player%s WHERE id=%d",
|
||||
GetTablePostfix(), packet->player_id);
|
||||
|
||||
ClientHandleInfo * pkInfo = new ClientHandleInfo(dwHandle, packet->player_id);
|
||||
@@ -376,24 +431,32 @@ void CClientManager::QUERY_PLAYER_LOAD(CPeer * peer, DWORD dwHandle, TPlayerLoad
|
||||
CDBManager::instance().ReturnQuery(queryStr, QID_PLAYER, peer->GetHandle(), pkInfo);
|
||||
|
||||
//--------------------------------------------------------------
|
||||
// 아이템 가져오기
|
||||
// 아이템 가져오기
|
||||
//--------------------------------------------------------------
|
||||
snprintf(queryStr, sizeof(queryStr),
|
||||
"SELECT id,window+0,pos,count,vnum,socket0,socket1,socket2,attrtype0,attrvalue0,attrtype1,attrvalue1,attrtype2,attrvalue2,attrtype3,attrvalue3,attrtype4,attrvalue4,attrtype5,attrvalue5,attrtype6,attrvalue6,HEX(port_extra) "
|
||||
"FROM item%s WHERE owner_id=%d AND (window < %d or window = %d or window = %d)",
|
||||
GetTablePostfix(), packet->player_id, SAFEBOX, DRAGON_SOUL_INVENTORY, SWITCHBOT);
|
||||
"FROM item%s WHERE owner_id=%d AND (window < %d or window = %d or window = %d"
|
||||
#ifdef ENABLE_SPECIAL_STORAGE
|
||||
" or (window >= %d and window <= %d)"
|
||||
#endif
|
||||
")",
|
||||
GetTablePostfix(), packet->player_id, SAFEBOX, DRAGON_SOUL_INVENTORY, SWITCHBOT
|
||||
#ifdef ENABLE_SPECIAL_STORAGE
|
||||
, UPGRADE_INVENTORY, COSTUME_INVENTORY
|
||||
#endif
|
||||
);
|
||||
CDBManager::instance().ReturnQuery(queryStr, QID_ITEM, peer->GetHandle(), new ClientHandleInfo(dwHandle, packet->player_id));
|
||||
|
||||
//--------------------------------------------------------------
|
||||
// QUEST 가져오기
|
||||
// QUEST 가져오기
|
||||
//--------------------------------------------------------------
|
||||
snprintf(queryStr, sizeof(queryStr),
|
||||
"SELECT dwPID,szName,szState,lValue FROM quest%s WHERE dwPID=%d",
|
||||
GetTablePostfix(), packet->player_id);
|
||||
CDBManager::instance().ReturnQuery(queryStr, QID_QUEST, peer->GetHandle(), new ClientHandleInfo(dwHandle, packet->player_id,packet->account_id));
|
||||
//독일 선물 기능에서 item_award테이블에서 login 정보를 얻기위해 account id도 넘겨준다
|
||||
//독일 선물 기능에서 item_award테이블에서 login 정보를 얻기위해 account id도 넘겨준다
|
||||
//--------------------------------------------------------------
|
||||
// AFFECT 가져오기
|
||||
// AFFECT 가져오기
|
||||
//--------------------------------------------------------------
|
||||
snprintf(queryStr, sizeof(queryStr),
|
||||
"SELECT dwPID,bType,bApplyOn,lApplyValue,dwFlag,lDuration,lSPCost FROM affect%s WHERE dwPID=%d",
|
||||
@@ -410,21 +473,21 @@ void CClientManager::ItemAward(CPeer * peer,char* login)
|
||||
std::set<TItemAward *> * pSet = ItemAwardManager::instance().GetByLogin(login_t);
|
||||
if(pSet == NULL)
|
||||
return;
|
||||
__typeof(pSet->begin()) it = pSet->begin(); //taken_time이 NULL인것들 읽어옴
|
||||
__typeof(pSet->begin()) it = pSet->begin(); //taken_time이 NULL인것들 읽어옴
|
||||
while(it != pSet->end() )
|
||||
{
|
||||
TItemAward * pItemAward = *(it++);
|
||||
char* whyStr = pItemAward->szWhy; //why 콜룸 읽기
|
||||
char cmdStr[100] = ""; //why콜룸에서 읽은 값을 임시 문자열에 복사해둠
|
||||
strcpy(cmdStr,whyStr); //명령어 얻는 과정에서 토큰쓰면 원본도 토큰화 되기 때문
|
||||
char* whyStr = pItemAward->szWhy; //why 콜룸 읽기
|
||||
char cmdStr[100] = ""; //why콜룸에서 읽은 값을 임시 문자열에 복사해둠
|
||||
strcpy(cmdStr,whyStr); //명령어 얻는 과정에서 토큰쓰면 원본도 토큰화 되기 때문
|
||||
char command[20] = "";
|
||||
strcpy(command,GetCommand(cmdStr)); // command 얻기
|
||||
if( !(strcmp(command,"GIFT") )) // command 가 GIFT이면
|
||||
strcpy(command,GetCommand(cmdStr)); // command 얻기
|
||||
if( !(strcmp(command,"GIFT") )) // command 가 GIFT이면
|
||||
{
|
||||
TPacketItemAwardInfromer giftData;
|
||||
strcpy(giftData.login, pItemAward->szLogin); //로그인 아이디 복사
|
||||
strcpy(giftData.command, command); //명령어 복사
|
||||
giftData.vnum = pItemAward->dwVnum; //아이템 vnum도 복사
|
||||
strcpy(giftData.login, pItemAward->szLogin); //로그인 아이디 복사
|
||||
strcpy(giftData.command, command); //명령어 복사
|
||||
giftData.vnum = pItemAward->dwVnum; //아이템 vnum도 복사
|
||||
ForwardPacket(HEADER_DG_ITEMAWARD_INFORMER,&giftData,sizeof(TPacketItemAwardInfromer));
|
||||
}
|
||||
}
|
||||
@@ -445,7 +508,7 @@ char* CClientManager::GetCommand(char* str)
|
||||
|
||||
bool CreatePlayerTableFromRes(MYSQL_RES * res, TPlayerTable * pkTab)
|
||||
{
|
||||
if (mysql_num_rows(res) == 0) // 데이터 없음
|
||||
if (mysql_num_rows(res) == 0) // 데이터 없음
|
||||
return false;
|
||||
|
||||
memset(pkTab, 0, sizeof(TPlayerTable));
|
||||
@@ -522,6 +585,13 @@ bool CreatePlayerTableFromRes(MYSQL_RES * res, TPlayerTable * pkTab)
|
||||
str_to_number(pkTab->horse.sStamina, row[col++]);
|
||||
str_to_number(pkTab->logoff_interval, row[col++]);
|
||||
str_to_number(pkTab->horse_skill_point, row[col++]);
|
||||
#ifdef UNLOCK_INVENTORY_WORLDARD
|
||||
for (int i = 0; i < UNLOCK_INVENTORY_MAX; ++i)
|
||||
str_to_number(pkTab->inventory_unlock[i], row[col++]);
|
||||
#endif
|
||||
#ifdef ENABLE_OFFLINESHOP_SYSTEM
|
||||
str_to_number(pkTab->shopFlag, row[col++]);
|
||||
#endif
|
||||
|
||||
// reset sub_skill_point
|
||||
{
|
||||
@@ -532,11 +602,11 @@ bool CreatePlayerTableFromRes(MYSQL_RES * res, TPlayerTable * pkTab)
|
||||
int max_point = pkTab->level - 9;
|
||||
|
||||
int skill_point =
|
||||
MIN(20, pkTab->skills[121].bLevel) + // SKILL_LEADERSHIP 통솔력
|
||||
MIN(20, pkTab->skills[124].bLevel) + // SKILL_MINING 채광
|
||||
MIN(10, pkTab->skills[131].bLevel) + // SKILL_HORSE_SUMMON 말소환
|
||||
MIN(20, pkTab->skills[141].bLevel) + // SKILL_ADD_HP HP보강
|
||||
MIN(20, pkTab->skills[142].bLevel); // SKILL_RESIST_PENETRATE 관통저항
|
||||
MIN(20, pkTab->skills[121].bLevel) + // SKILL_LEADERSHIP 통솔력
|
||||
MIN(20, pkTab->skills[124].bLevel) + // SKILL_MINING 채광
|
||||
MIN(10, pkTab->skills[131].bLevel) + // SKILL_HORSE_SUMMON 말소환
|
||||
MIN(20, pkTab->skills[141].bLevel) + // SKILL_ADD_HP HP보강
|
||||
MIN(20, pkTab->skills[142].bLevel); // SKILL_RESIST_PENETRATE 관통저항
|
||||
|
||||
pkTab->sub_skill_point = max_point - skill_point;
|
||||
}
|
||||
@@ -576,13 +646,13 @@ void CClientManager::RESULT_COMPOSITE_PLAYER(CPeer * peer, SQLMsg * pMsg, DWORD
|
||||
{
|
||||
sys_log(0, "QID_QUEST %u", info->dwHandle);
|
||||
RESULT_QUEST_LOAD(peer, pSQLResult, info->dwHandle, info->player_id);
|
||||
//aid얻기
|
||||
//aid얻기
|
||||
ClientHandleInfo* temp1 = info.get();
|
||||
if (temp1 == NULL)
|
||||
break;
|
||||
|
||||
CLoginData* pLoginData1 = GetLoginDataByAID(temp1->account_id); //
|
||||
//독일 선물 기능
|
||||
//독일 선물 기능
|
||||
if( pLoginData1->GetAccountRef().login == NULL)
|
||||
break;
|
||||
if( pLoginData1 == NULL )
|
||||
@@ -673,14 +743,17 @@ void CClientManager::RESULT_PLAYER_LOAD(CPeer * peer, MYSQL_RES * pRes, ClientHa
|
||||
void CClientManager::RESULT_ITEM_LOAD(CPeer * peer, MYSQL_RES * pRes, DWORD dwHandle, DWORD dwPID)
|
||||
{
|
||||
static std::vector<TPlayerItem> s_items;
|
||||
//DB에서 아이템 정보를 읽어온다.
|
||||
CreateItemTableFromRes(pRes, &s_items, dwPID);
|
||||
//DB에서 아이템 정보를 읽어온다.
|
||||
if (!CreateItemTableFromRes(pRes, &s_items, dwPID)) {
|
||||
peer->EncodeHeader(HEADER_DG_PLAYER_LOAD_FAILED, dwHandle, 0);
|
||||
return;
|
||||
}
|
||||
DWORD dwCount = s_items.size();
|
||||
|
||||
peer->EncodeHeader(HEADER_DG_ITEM_LOAD, dwHandle, sizeof(DWORD) + sizeof(TPlayerItem) * dwCount);
|
||||
peer->EncodeDWORD(dwCount);
|
||||
|
||||
//CacheSet을 만든다
|
||||
//CacheSet을 만든다
|
||||
CreateItemCacheSet(dwPID);
|
||||
|
||||
// ITEM_LOAD_LOG_ATTACH_PID
|
||||
@@ -692,7 +765,7 @@ void CClientManager::RESULT_ITEM_LOAD(CPeer * peer, MYSQL_RES * pRes, DWORD dwHa
|
||||
peer->Encode(&s_items[0], sizeof(TPlayerItem) * dwCount);
|
||||
|
||||
for (DWORD i = 0; i < dwCount; ++i)
|
||||
PutItemCache(&s_items[i], true); // 로드한 것은 따로 저장할 필요 없으므로, 인자 bSkipQuery에 true를 넣는다.
|
||||
PutItemCache(&s_items[i], true); // 로드한 것은 따로 저장할 필요 없으므로, 인자 bSkipQuery에 true를 넣는다.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -700,7 +773,7 @@ void CClientManager::RESULT_AFFECT_LOAD(CPeer * peer, MYSQL_RES * pRes, DWORD dw
|
||||
{
|
||||
int iNumRows;
|
||||
|
||||
if ((iNumRows = mysql_num_rows(pRes)) == 0) // 데이터 없음
|
||||
if ((iNumRows = mysql_num_rows(pRes)) == 0) // 데이터 없음
|
||||
return;
|
||||
|
||||
static std::vector<TPacketAffectElement> s_elements;
|
||||
@@ -779,6 +852,7 @@ void CClientManager::RESULT_QUEST_LOAD(CPeer * peer, MYSQL_RES * pRes, DWORD dwH
|
||||
*/
|
||||
void CClientManager::QUERY_PLAYER_SAVE(CPeer * peer, DWORD dwHandle, TPlayerTable * pkTab)
|
||||
{
|
||||
if(!EconomySaveAllowed(peer,pkTab->id))return;
|
||||
if (g_test_server)
|
||||
sys_log(0, "PLAYER_SAVE: %s", pkTab->name);
|
||||
|
||||
@@ -795,9 +869,9 @@ void CClientManager::__QUERY_PLAYER_CREATE(CPeer *peer, DWORD dwHandle, TPlayerC
|
||||
{
|
||||
char queryStr[QUERY_MAX_LEN];
|
||||
int queryLen;
|
||||
int player_id;
|
||||
DWORD player_id = 0;
|
||||
|
||||
// 한 계정에 X초 내로 캐릭터 생성을 할 수 없다.
|
||||
// 한 계정에 X초 내로 캐릭터 생성을 할 수 없다.
|
||||
time_by_id_map_t::iterator it = s_createTimeByAccountID.find(packet->account_id);
|
||||
|
||||
if (it != s_createTimeByAccountID.end())
|
||||
@@ -881,17 +955,17 @@ void CClientManager::__QUERY_PLAYER_CREATE(CPeer *peer, DWORD dwHandle, TPlayerC
|
||||
"skill_level, quickslot) "
|
||||
"VALUES(0, %u, '%s', %d, %d, %d, %d, %d, "
|
||||
"%d, %d, %d, %d, %d, %d, %d, "
|
||||
"%d, %d, %d, %d, %d, %d, %d, 0, %d, 0, ",
|
||||
"%d, %d, %d, %d, %d, %d, %d, 0, %lld, 0, ",
|
||||
GetTablePostfix(),
|
||||
packet->account_id, packet->player_table.name, packet->player_table.level, packet->player_table.st, packet->player_table.ht, packet->player_table.dx, packet->player_table.iq,
|
||||
packet->player_table.job, packet->player_table.voice, packet->player_table.dir, packet->player_table.x, packet->player_table.y, packet->player_table.z,
|
||||
packet->player_table.hp, packet->player_table.sp, packet->player_table.sRandomHP, packet->player_table.sRandomSP, packet->player_table.stat_point, packet->player_table.stamina, packet->player_table.part_base, packet->player_table.part_base, packet->player_table.gold);
|
||||
packet->player_table.hp, packet->player_table.sp, packet->player_table.sRandomHP, packet->player_table.sRandomSP, packet->player_table.stat_point, packet->player_table.stamina, packet->player_table.part_base, packet->player_table.part_base, (long long) packet->player_table.gold);
|
||||
|
||||
sys_log(0, "PlayerCreate accountid %d name %s level %d gold %d, st %d ht %d job %d",
|
||||
sys_log(0, "PlayerCreate accountid %d name %s level %d gold %lld, st %d ht %d job %d",
|
||||
packet->account_id,
|
||||
packet->player_table.name,
|
||||
packet->player_table.level,
|
||||
packet->player_table.gold,
|
||||
(long long) packet->player_table.gold,
|
||||
packet->player_table.st,
|
||||
packet->player_table.ht,
|
||||
packet->player_table.job);
|
||||
@@ -910,24 +984,23 @@ void CClientManager::__QUERY_PLAYER_CREATE(CPeer *peer, DWORD dwHandle, TPlayerC
|
||||
if (g_test_server)
|
||||
sys_log(0, "Create_Player queryLen[%d] TEXT[%s]", queryLen, text);
|
||||
|
||||
if (pMsg2->Get()->uiAffectedRows <= 0)
|
||||
if (!pMsg2->Get()->HasAffectedRows() || !pMsg2->Get()->GetInsertID32(player_id))
|
||||
{
|
||||
peer->EncodeHeader(HEADER_DG_PLAYER_CREATE_ALREADY, dwHandle, 0);
|
||||
sys_log(0, "ALREADY EXIST3 query: %s AffectedRows %lu", queryStr, pMsg2->Get()->uiAffectedRows);
|
||||
sys_log(0, "ALREADY EXIST3 query: %s AffectedRows %llu", queryStr, static_cast<unsigned long long>(pMsg2->Get()->uiAffectedRows));
|
||||
return;
|
||||
}
|
||||
|
||||
player_id = pMsg2->Get()->uiInsertID;
|
||||
|
||||
snprintf(queryStr, sizeof(queryStr), "UPDATE player_index%s SET pid%d=%d WHERE id=%d",
|
||||
snprintf(queryStr, sizeof(queryStr), "UPDATE player_index%s SET pid%d=%u WHERE id=%u",
|
||||
GetTablePostfix(), packet->account_index + 1, player_id, packet->account_id);
|
||||
std::unique_ptr<SQLMsg> pMsg3(CDBManager::instance().DirectQuery(queryStr));
|
||||
|
||||
if (pMsg3->Get()->uiAffectedRows <= 0)
|
||||
if (!pMsg3->Get()->HasAffectedRows())
|
||||
{
|
||||
sys_err("QUERY_ERROR: %s", queryStr);
|
||||
|
||||
snprintf(queryStr, sizeof(queryStr), "DELETE FROM player%s WHERE id=%d", GetTablePostfix(), player_id);
|
||||
snprintf(queryStr, sizeof(queryStr), "DELETE FROM player%s WHERE id=%u", GetTablePostfix(), player_id);
|
||||
CDBManager::instance().DirectQuery(queryStr);
|
||||
|
||||
peer->EncodeHeader(HEADER_DG_PLAYER_CREATE_FAILED, dwHandle, 0);
|
||||
@@ -1028,7 +1101,7 @@ void CClientManager::__QUERY_PLAYER_DELETE(CPeer* peer, DWORD dwHandle, TPlayerD
|
||||
}
|
||||
|
||||
//
|
||||
// @version 05/06/10 Bang2ni - 플레이어 삭제시 가격정보 리스트 삭제 추가.
|
||||
// @version 05/06/10 Bang2ni - 플레이어 삭제시 가격정보 리스트 삭제 추가.
|
||||
//
|
||||
void CClientManager::__RESULT_PLAYER_DELETE(CPeer *peer, SQLMsg* msg)
|
||||
{
|
||||
@@ -1064,13 +1137,18 @@ void CClientManager::__RESULT_PLAYER_DELETE(CPeer *peer, SQLMsg* msg)
|
||||
return;
|
||||
}
|
||||
|
||||
if(!EconomyCanDelete(dwPID)) {
|
||||
peer->EncodeHeader(HEADER_DG_PLAYER_DELETE_FAILED,pi->dwHandle,1);
|
||||
peer->EncodeBYTE(pi->account_index);
|
||||
delete pi;return;
|
||||
}
|
||||
char queryStr[QUERY_MAX_LEN];
|
||||
|
||||
snprintf(queryStr, sizeof(queryStr), "INSERT INTO player%s_deleted SELECT * FROM player%s WHERE id=%d",
|
||||
GetTablePostfix(), GetTablePostfix(), pi->player_id);
|
||||
std::unique_ptr<SQLMsg> pIns(CDBManager::instance().DirectQuery(queryStr));
|
||||
|
||||
if (pIns->Get()->uiAffectedRows == 0 || pIns->Get()->uiAffectedRows == (uint32_t)-1)
|
||||
if (pIns->Get()->uiAffectedRows == 0 || pIns->Get()->uiAffectedRows == UINT64_MAX)
|
||||
{
|
||||
sys_log(0, "PLAYER_DELETE FAILED %u CANNOT INSERT TO player%s_deleted", dwPID, GetTablePostfix());
|
||||
|
||||
@@ -1079,14 +1157,14 @@ void CClientManager::__RESULT_PLAYER_DELETE(CPeer *peer, SQLMsg* msg)
|
||||
return;
|
||||
}
|
||||
|
||||
// 삭제 성공
|
||||
// 삭제 성공
|
||||
sys_log(0, "PLAYER_DELETE SUCCESS %u", dwPID);
|
||||
|
||||
char account_index_string[16];
|
||||
|
||||
snprintf(account_index_string, sizeof(account_index_string), "player_id%d", m_iPlayerIDStart + pi->account_index);
|
||||
|
||||
// 플레이어 테이블을 캐쉬에서 삭제한다.
|
||||
// 플레이어 테이블을 캐쉬에서 삭제한다.
|
||||
CPlayerTableCache * pkPlayerCache = GetPlayerCache(pi->player_id);
|
||||
|
||||
if (pkPlayerCache)
|
||||
@@ -1095,7 +1173,7 @@ void CClientManager::__RESULT_PLAYER_DELETE(CPeer *peer, SQLMsg* msg)
|
||||
delete pkPlayerCache;
|
||||
}
|
||||
|
||||
// 아이템들을 캐쉬에서 삭제한다.
|
||||
// 아이템들을 캐쉬에서 삭제한다.
|
||||
TItemCacheSet * pSet = GetItemCacheSet(pi->player_id);
|
||||
|
||||
if (pSet)
|
||||
@@ -1122,7 +1200,7 @@ void CClientManager::__RESULT_PLAYER_DELETE(CPeer *peer, SQLMsg* msg)
|
||||
|
||||
std::unique_ptr<SQLMsg> pMsg(CDBManager::instance().DirectQuery(queryStr));
|
||||
|
||||
if (pMsg->Get()->uiAffectedRows == 0 || pMsg->Get()->uiAffectedRows == (uint32_t)-1)
|
||||
if (pMsg->Get()->uiAffectedRows == 0 || pMsg->Get()->uiAffectedRows == UINT64_MAX)
|
||||
{
|
||||
sys_log(0, "PLAYER_DELETE FAIL WHEN UPDATE account table");
|
||||
peer->EncodeHeader(HEADER_DG_PLAYER_DELETE_FAILED, pi->dwHandle, 1);
|
||||
@@ -1133,7 +1211,15 @@ void CClientManager::__RESULT_PLAYER_DELETE(CPeer *peer, SQLMsg* msg)
|
||||
snprintf(queryStr, sizeof(queryStr), "DELETE FROM player%s WHERE id=%d", GetTablePostfix(), pi->player_id);
|
||||
delete CDBManager::instance().DirectQuery(queryStr);
|
||||
|
||||
snprintf(queryStr, sizeof(queryStr), "DELETE FROM item%s WHERE owner_id=%d AND (window < %d or window = %d or window = %d)", GetTablePostfix(), pi->player_id, SAFEBOX, DRAGON_SOUL_INVENTORY, SWITCHBOT);
|
||||
snprintf(queryStr, sizeof(queryStr), "DELETE FROM item%s WHERE owner_id=%d AND (window < %d or window = %d or window = %d"
|
||||
#ifdef ENABLE_SPECIAL_STORAGE
|
||||
" or (window >= %d and window <= %d)"
|
||||
#endif
|
||||
")", GetTablePostfix(), pi->player_id, SAFEBOX, DRAGON_SOUL_INVENTORY, SWITCHBOT
|
||||
#ifdef ENABLE_SPECIAL_STORAGE
|
||||
, UPGRADE_INVENTORY, COSTUME_INVENTORY
|
||||
#endif
|
||||
);
|
||||
delete CDBManager::instance().DirectQuery(queryStr);
|
||||
|
||||
snprintf(queryStr, sizeof(queryStr), "DELETE FROM quest%s WHERE dwPID=%d", GetTablePostfix(), pi->player_id);
|
||||
@@ -1158,7 +1244,7 @@ void CClientManager::__RESULT_PLAYER_DELETE(CPeer *peer, SQLMsg* msg)
|
||||
}
|
||||
else
|
||||
{
|
||||
// 삭제 실패
|
||||
// 삭제 실패
|
||||
sys_log(0, "PLAYER_DELETE FAIL NO ROW");
|
||||
peer->EncodeHeader(HEADER_DG_PLAYER_DELETE_FAILED, pi->dwHandle, 1);
|
||||
peer->EncodeBYTE(pi->account_index);
|
||||
@@ -1243,7 +1329,7 @@ void CClientManager::RESULT_HIGHSCORE_REGISTER(CPeer * pkPeer, SQLMsg * msg)
|
||||
|
||||
if (res->uiNumRows == 0)
|
||||
{
|
||||
// 새로운 하이스코어를 삽입
|
||||
// 새로운 하이스코어를 삽입
|
||||
char buf[256];
|
||||
snprintf(buf, sizeof(buf), "INSERT INTO highscore%s VALUES('%s', %u, %d)", GetTablePostfix(), szBoard, pi->player_id, value);
|
||||
CDBManager::instance().AsyncQuery(buf);
|
||||
@@ -1278,7 +1364,7 @@ void CClientManager::RESULT_HIGHSCORE_REGISTER(CPeer * pkPeer, SQLMsg * msg)
|
||||
CDBManager::instance().AsyncQuery(buf);
|
||||
}
|
||||
}
|
||||
// TODO: 이곳에서 하이스코어가 업데이트 되었는지 체크하여 공지를 뿌려야한다.
|
||||
// TODO: 이곳에서 하이스코어가 업데이트 되었는지 체크하여 공지를 뿌려야한다.
|
||||
delete pi;
|
||||
}
|
||||
|
||||
@@ -1286,10 +1372,10 @@ void CClientManager::InsertLogoutPlayer(DWORD pid)
|
||||
{
|
||||
TLogoutPlayerMap::iterator it = m_map_logout.find(pid);
|
||||
|
||||
// 존재하지 않을경우 추가
|
||||
// 존재하지 않을경우 추가
|
||||
if (it != m_map_logout.end())
|
||||
{
|
||||
// 존재할경우 시간만 갱신
|
||||
// 존재할경우 시간만 갱신
|
||||
if (g_log)
|
||||
sys_log(0, "LOGOUT: Update player time pid(%d)", pid);
|
||||
|
||||
|
||||
@@ -26,72 +26,48 @@ void CConfig::NextLine(FILE *fp)
|
||||
}
|
||||
}
|
||||
|
||||
bool CConfig::GetWord(FILE *fp, char *tar)
|
||||
bool CConfig::GetWord(FILE *fp, char *dest, size_t size)
|
||||
{
|
||||
int i = 0;
|
||||
int c;
|
||||
|
||||
int semicolon_mode = 0;
|
||||
|
||||
while ((c = fgetc(fp)) != EOF)
|
||||
{
|
||||
if (c == 13)
|
||||
continue;
|
||||
|
||||
if (semicolon_mode)
|
||||
{
|
||||
if (c == '"')
|
||||
{
|
||||
tar[i] = '\0';
|
||||
return true;
|
||||
}
|
||||
|
||||
tar[i++] = c;
|
||||
continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (i == 0)
|
||||
{
|
||||
if (c == '"')
|
||||
{
|
||||
semicolon_mode = 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == ' ' || c == '\t' || c == '\n')
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if ((c == ' ' || c == '\t' || c == '\n'))
|
||||
{
|
||||
// ÅÜ.
|
||||
tar[i] = '\0';
|
||||
return true;
|
||||
}
|
||||
|
||||
tar[i] = c;
|
||||
++i;
|
||||
}
|
||||
}
|
||||
|
||||
return (i != 0);
|
||||
if (!fp || !dest || !size) { m_readError = true; return false; }
|
||||
size_t used = 0;
|
||||
bool quoted = false, started = false;
|
||||
dest[0] = 0;
|
||||
int c;
|
||||
while ((c = fgetc(fp)) != EOF)
|
||||
{
|
||||
if (c == 0) { m_readError = true; return false; }
|
||||
if (c == '\r') continue;
|
||||
if (!started)
|
||||
{
|
||||
if (c == ' ' || c == '\t' || c == '\n') continue;
|
||||
started = true;
|
||||
if (c == '"') { quoted = true; continue; }
|
||||
}
|
||||
if ((quoted && c == '"') || (!quoted && (c == ' ' || c == '\t' || c == '\n')))
|
||||
return true;
|
||||
if (used + 1 >= size) { m_readError = true; return false; }
|
||||
dest[used++] = static_cast<char>(c); // fgetc returned a byte, not EOF.
|
||||
dest[used] = 0;
|
||||
}
|
||||
if (ferror(fp) || quoted) m_readError = true;
|
||||
return started && !m_readError;
|
||||
}
|
||||
|
||||
bool CConfig::GetLine(FILE* fp, char*dest)
|
||||
bool CConfig::GetLine(FILE *fp, char *dest, size_t size)
|
||||
{
|
||||
int c;
|
||||
int i = 0;
|
||||
while ((c = fgetc(fp)) != EOF)
|
||||
{
|
||||
if (c == '\n')
|
||||
return true;
|
||||
dest[i] = c;
|
||||
++i;
|
||||
}
|
||||
return true;
|
||||
if (!fp || !dest || !size) { m_readError = true; return false; }
|
||||
size_t used = 0;
|
||||
dest[0] = 0;
|
||||
int c;
|
||||
while ((c = fgetc(fp)) != EOF)
|
||||
{
|
||||
if (c == '\n') return true;
|
||||
if (c == 0 || used + 1 >= size) { m_readError = true; return false; }
|
||||
dest[used++] = static_cast<char>(c);
|
||||
dest[used] = 0;
|
||||
}
|
||||
if (ferror(fp)) m_readError = true;
|
||||
return !m_readError;
|
||||
}
|
||||
|
||||
bool CConfig::LoadFile(const char* filename)
|
||||
@@ -105,8 +81,10 @@ bool CConfig::LoadFile(const char* filename)
|
||||
return false;
|
||||
|
||||
int mode = 0;
|
||||
m_readError = false;
|
||||
TValueMap staged = m_valueMap;
|
||||
|
||||
while (GetWord(fp, szTmp))
|
||||
while (GetWord(fp, szTmp, sizeof(szTmp)))
|
||||
{
|
||||
if (strcmp(szTmp, "//") == 0)
|
||||
{
|
||||
@@ -128,15 +106,15 @@ bool CConfig::LoadFile(const char* filename)
|
||||
|
||||
case 2:
|
||||
mode = 0;
|
||||
m_valueMap.insert(TValueMap::value_type(comment, szTmp));
|
||||
staged.insert(TValueMap::value_type(comment, szTmp));
|
||||
break;
|
||||
}
|
||||
|
||||
// ITEM_ID_RANGE
|
||||
if (mode == 2 && strcmp(comment, "ITEM_ID_RANGE") == 0)
|
||||
{
|
||||
GetLine(fp, szTmp);
|
||||
m_valueMap.insert(TValueMap::value_type(comment, szTmp));
|
||||
if (!GetLine(fp, szTmp, sizeof(szTmp))) break;
|
||||
staged.insert(TValueMap::value_type(comment, szTmp));
|
||||
mode = 0;
|
||||
|
||||
}
|
||||
@@ -145,8 +123,10 @@ bool CConfig::LoadFile(const char* filename)
|
||||
|
||||
|
||||
// ÆÄÀÏ ´Ý´Â ºÎºÐ.
|
||||
const bool valid = !m_readError && !ferror(fp) && mode == 0;
|
||||
fclose(fp);
|
||||
return true;
|
||||
if (valid) m_valueMap.swap(staged);
|
||||
return valid;
|
||||
}
|
||||
|
||||
std::string * CConfig::Search(const char* key)
|
||||
@@ -165,11 +145,14 @@ bool CConfig::GetParam(const char*key, int index, DWORD *Param)
|
||||
if (!pstStr)
|
||||
return false;
|
||||
|
||||
char szParam[5][32];
|
||||
if (!Param || index < 0 || index >= 5) return false;
|
||||
char szParam[5][32] = {};
|
||||
|
||||
sscanf(pstStr->c_str(), "%s %s %s %s %s", szParam[0],szParam[1],szParam[2],szParam[3],szParam[4]);
|
||||
if (sscanf(pstStr->c_str(), "%31s %31s %31s %31s %31s", szParam[0],szParam[1],szParam[2],szParam[3],szParam[4]) <= index) return false;
|
||||
|
||||
str_to_number(*Param, szParam[index]);
|
||||
unsigned long long value = 0;
|
||||
if (!str_to_number(value, szParam[index]) || value > UINT32_MAX) return false;
|
||||
*Param = static_cast<DWORD>(value);
|
||||
|
||||
sys_log(0, "GetParam %d", *Param);
|
||||
return true;
|
||||
@@ -239,12 +222,15 @@ bool CConfig::GetValue(const char * key, char *dest, size_t destSize)
|
||||
|
||||
bool CConfig::GetTwoValue(const char* key, DWORD * dest1, DWORD *dest2)
|
||||
{
|
||||
if (!GetParam(key, 0, dest1))
|
||||
DWORD first=0, second=0;
|
||||
if (!dest1 || !dest2) return false;
|
||||
if (!GetParam(key, 0, &first))
|
||||
return false;
|
||||
|
||||
if (!GetParam(key, 1, dest2))
|
||||
if (!GetParam(key, 1, &second))
|
||||
return false;
|
||||
|
||||
*dest1=first; *dest2=second;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -15,8 +15,8 @@ class CConfig : public singleton<CConfig>
|
||||
bool GetValue(const char* key, DWORD* dest);
|
||||
bool GetValue(const char* key, BYTE* dest);
|
||||
bool GetValue(const char* key, char* dest, size_t destSize);
|
||||
bool GetWord(FILE* fp, char* dest);
|
||||
bool GetLine(FILE* fp, char* dest);
|
||||
bool GetWord(FILE* fp, char* dest, size_t size);
|
||||
bool GetLine(FILE* fp, char* dest, size_t size);
|
||||
bool GetTwoValue(const char* key, DWORD * dest1, DWORD *dest2);
|
||||
void NextLine(FILE* fp);
|
||||
|
||||
@@ -29,6 +29,7 @@ class CConfig : public singleton<CConfig>
|
||||
|
||||
private:
|
||||
TValueMap m_valueMap;
|
||||
bool m_readError = false;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
#include "stdafx.h"
|
||||
#include "ClientManager.h"
|
||||
#include "Cache.h"
|
||||
#include "Main.h"
|
||||
#include <memory>
|
||||
|
||||
namespace {
|
||||
using CubeQuery=std::unique_ptr<SQLMsg>;
|
||||
CubeQuery cubeQuery(const std::string& sql){return CubeQuery(CDBManager::instance().DirectQuery(sql.c_str()));}
|
||||
bool cubeValid(const CubeQuery& q){return q&&!q->uiSQLErrno&&q->Get();}
|
||||
// No table installation at runtime. Cache only a completely absent schema;
|
||||
// migrations require coordinated restart. Partial/failed discovery fails closed.
|
||||
int cubeSchema() {
|
||||
static int state=-1;if(state>=0)return state;
|
||||
auto q=cubeQuery("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME IN ('port_cube_version','port_cube_fences','port_cube_item_fences')");
|
||||
if(!cubeValid(q)||q->Get()->uiNumRows!=1)return -1;
|
||||
MYSQL_ROW row=mysql_fetch_row(q->Get()->pSQLResult);if(!row||!row[0])return -1;
|
||||
const std::string count=row[0];
|
||||
if(count=="0")return state=0;
|
||||
if(count=="3") {
|
||||
auto version=cubeQuery("SELECT version FROM port_cube_version WHERE id=1");
|
||||
if(!cubeValid(version)||version->Get()->uiNumRows!=1)return -1;
|
||||
MYSQL_ROW value=mysql_fetch_row(version->Get()->pSQLResult);
|
||||
if(value&&value[0]&&std::string(value[0])=="2")return state=1;
|
||||
}
|
||||
return -1; // includes the older two-table v1 candidate: do not ignore fences
|
||||
}
|
||||
bool cubeClear(const std::string& predicate) {
|
||||
const int installed=cubeSchema();if(installed==0)return true;if(installed<0)return false;
|
||||
auto q=cubeQuery("SELECT pid FROM port_cube_fences WHERE phase<>'RELEASED' AND ("+predicate+") LIMIT 1");
|
||||
return cubeValid(q)&&q->Get()->uiNumRows==0;
|
||||
}
|
||||
// Modern terminal release is not a completed resume. Keep the SQL quarantine
|
||||
// across DB restart, when m_cubeDrains no longer carries its memory hold.
|
||||
// No resume activation receipt exists yet; do not infer one from RELEASED.
|
||||
int cubeTerminalSchema() {
|
||||
static int installed=-1;if(installed>=0)return installed;
|
||||
const std::string names="('port_cube_release_version','port_cube_releases')";
|
||||
auto scalar=[](const std::string& sql,const std::string& expected)->bool{auto q=cubeQuery(sql);if(!cubeValid(q)||q->Get()->uiNumRows!=1)return false;MYSQL_ROW row=mysql_fetch_row(q->Get()->pSQLResult);return row&&row[0]&&std::string(row[0])==expected;};
|
||||
auto q=cubeQuery("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME IN "+names);
|
||||
if(!cubeValid(q)||q->Get()->uiNumRows!=1)return -1;MYSQL_ROW row=mysql_fetch_row(q->Get()->pSQLResult);if(!row||!row[0])return -1;
|
||||
const std::string count=row[0];if(count=="0")return installed=0;
|
||||
if(count!="2"||!scalar("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND ENGINE='InnoDB' AND TABLE_NAME IN "+names,"2")||!scalar("SELECT version FROM port_cube_release_version WHERE id=1","1"))return -1;
|
||||
return installed=1;
|
||||
}
|
||||
bool cubeTerminalClear(const std::string& predicate) {
|
||||
const int schema=cubeTerminalSchema();if(schema==0)return true;if(schema<0)return false;
|
||||
auto q=cubeQuery("SELECT pid FROM port_cube_fences WHERE phase='RELEASED' AND request IN (SELECT request FROM port_cube_releases) AND ("+predicate+") LIMIT 1");
|
||||
return cubeValid(q)&&q->Get()->uiNumRows==0;
|
||||
}
|
||||
bool cubeGoldClear(const std::string& predicate) {
|
||||
// Coordinated restart on installation/removal, as with the base Cube gate.
|
||||
static int installed=-1;
|
||||
if(installed<0) {
|
||||
auto q=cubeQuery("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME IN ('port_cube_gold_version','port_cube_gold_intents','port_cube_gold_sources')");
|
||||
if(!cubeValid(q)||q->Get()->uiNumRows!=1)return false;
|
||||
MYSQL_ROW row=mysql_fetch_row(q->Get()->pSQLResult);if(!row||!row[0])return false;
|
||||
if(std::string(row[0])=="0")installed=0;
|
||||
else if(std::string(row[0])=="3") {
|
||||
auto engine=cubeQuery("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND ENGINE='InnoDB' AND TABLE_NAME IN ('port_cube_gold_version','port_cube_gold_intents','port_cube_gold_sources')");
|
||||
if(!cubeValid(engine)||engine->Get()->uiNumRows!=1)return false;
|
||||
MYSQL_ROW e=mysql_fetch_row(engine->Get()->pSQLResult);if(!e||!e[0]||std::string(e[0])!="3")return false;
|
||||
auto version=cubeQuery("SELECT version FROM port_cube_gold_version WHERE id=1");
|
||||
if(!cubeValid(version)||version->Get()->uiNumRows!=1)return false;
|
||||
MYSQL_ROW v=mysql_fetch_row(version->Get()->pSQLResult);if(!v||!v[0]||std::string(v[0])!="2")return false;
|
||||
installed=1;
|
||||
} else return false;
|
||||
}
|
||||
if(!installed)return true;
|
||||
auto q=cubeQuery("SELECT pid FROM port_cube_gold_intents WHERE state='QUEUED' AND ("+predicate+") LIMIT 1");
|
||||
return cubeValid(q)&&q->Get()->uiNumRows==0;
|
||||
}
|
||||
bool cubeOwnerClear(const std::string& predicate) {
|
||||
static int installed=-1;
|
||||
const std::string names="('port_cube_owner_version','port_cube_owner_broker','port_cube_owner_leases')";
|
||||
auto scalar=[](const std::string& sql,const std::string& expected)->bool {
|
||||
auto q=cubeQuery(sql);if(!cubeValid(q)||q->Get()->uiNumRows!=1)return false;
|
||||
MYSQL_ROW row=mysql_fetch_row(q->Get()->pSQLResult);return row&&row[0]&&std::string(row[0])==expected;
|
||||
};
|
||||
if(installed<0) {
|
||||
auto q=cubeQuery("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME IN "+names);
|
||||
if(!cubeValid(q)||q->Get()->uiNumRows!=1)return false;
|
||||
MYSQL_ROW row=mysql_fetch_row(q->Get()->pSQLResult);if(!row||!row[0])return false;
|
||||
if(std::string(row[0])=="0")installed=0;
|
||||
else if(std::string(row[0])=="3"&&scalar("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND ENGINE='InnoDB' AND TABLE_NAME IN "+names,"3")&&
|
||||
scalar("SELECT version FROM port_cube_owner_version WHERE id=1","1"))installed=1;
|
||||
else return false;
|
||||
}
|
||||
if(!installed)return true;
|
||||
// Includes REVOKED and ADOPTED. Neither is a normal-load/thaw receipt.
|
||||
auto q=cubeQuery("SELECT pid FROM port_cube_owner_leases WHERE "+predicate+" LIMIT 1");
|
||||
return cubeValid(q)&&q->Get()->uiNumRows==0;
|
||||
}
|
||||
}
|
||||
|
||||
bool CClientManager::CubePeerMayWriteItem(CPeer* peer,DWORD id) {
|
||||
if(*GetTablePostfix())return true;
|
||||
if(!id)return false;
|
||||
bool protectedActor=false;
|
||||
auto allowed=[&](DWORD pid)->bool {
|
||||
for(const auto& entry:m_cubeDrains)if(!entry.second.cancelled&&entry.second.batch.player==pid)
|
||||
return CubePeerMaySave(peer,pid);
|
||||
return true;
|
||||
};
|
||||
for(const auto& entry:m_cubeDrains) {
|
||||
const auto& c=entry.second;if(c.cancelled)continue;protectedActor=true;
|
||||
// Includes consumed inputs and not-yet-created reserved rewards. Never
|
||||
// trust a packet's claimed owner or lack of a current SQL item row.
|
||||
for(const auto& item:c.batch.inventory)if(item.value.id==id&&!allowed(c.batch.player))return false;
|
||||
for(const auto& reward:c.batch.rewards)if(reward.id==id&&!allowed(c.batch.player))return false;
|
||||
}
|
||||
if(!protectedActor)return true; // no extra SQL or cache access on baseline
|
||||
if(auto* cache=GetItemCache(id)) {
|
||||
const auto* item=cache->Get(false);
|
||||
if(!item||item->id!=id)return false;
|
||||
if(item->window!=SAFEBOX&&item->window!=MALL&&!allowed(item->owner))return false;
|
||||
}
|
||||
// Check BOTH cached and persisted ownership. A stale cache or a forged
|
||||
// SAFEBOX/MALL destination cannot conceal a protected ordinary SQL owner.
|
||||
auto owner=cubeQuery("SELECT owner_id FROM item WHERE id="+std::to_string(id)+" AND window NOT IN ('MALL','SAFEBOX')");
|
||||
if(!cubeValid(owner)||owner->Get()->uiNumRows>1)return false;
|
||||
if(owner->Get()->uiNumRows){MYSQL_ROW row=mysql_fetch_row(owner->Get()->pSQLResult);uint64_t pid=0;if(!row||!row[0]||!PortEconomy::Number(row[0],pid,UINT32_MAX)||!pid||!allowed(DWORD(pid)))return false;}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CClientManager::CubePlayerWritable(DWORD pid) {
|
||||
if(*GetTablePostfix())return true;
|
||||
if(!cubeTerminalClear("pid="+std::to_string(pid)))return false;
|
||||
if(!pid||!cubeOwnerClear("pid="+std::to_string(pid)))return false;
|
||||
if(!pid||!cubeGoldClear("pid="+std::to_string(pid)))return false;
|
||||
if(!pid||!cubeClear("pid="+std::to_string(pid)))return false;
|
||||
if(cubeSchema()==0)return true;
|
||||
auto q=cubeQuery("SELECT pid FROM port_cube_item_fences WHERE pid="+std::to_string(pid)+" LIMIT 1");
|
||||
return cubeValid(q)&&q->Get()->uiNumRows==0;
|
||||
}
|
||||
bool CClientManager::CubeAccountLoadable(DWORD account,DWORD pid) {
|
||||
if(*GetTablePostfix())return true;
|
||||
if(!cubeTerminalClear("account="+std::to_string(account)+" OR pid="+std::to_string(pid)))return false;
|
||||
if(!account||!pid||!cubeOwnerClear("account="+std::to_string(account)+" OR pid="+std::to_string(pid)))return false;
|
||||
if(!account||!pid||!cubeGoldClear("account="+std::to_string(account)+" OR pid="+std::to_string(pid)))return false;
|
||||
// Also stop selecting another character on an account with a held owner.
|
||||
if(!account||!pid||!cubeClear("account="+std::to_string(account)+" OR pid="+std::to_string(pid)))return false;
|
||||
if(cubeSchema()==0)return true;
|
||||
auto q=cubeQuery("SELECT f.pid FROM port_cube_item_fences f LEFT JOIN player p ON p.id=f.pid WHERE f.pid="+std::to_string(pid)+" OR p.account_id="+std::to_string(account)+" LIMIT 1");
|
||||
return cubeValid(q)&&q->Get()->uiNumRows==0;
|
||||
}
|
||||
bool CClientManager::CubeItemWritable(DWORD id) {
|
||||
if(*GetTablePostfix())return true;
|
||||
const int installed=cubeSchema();if(installed==0)return true;if(installed<0||!id)return false;
|
||||
const int terminal=cubeTerminalSchema();if(terminal<0)return false;
|
||||
if(terminal) {
|
||||
auto reservation=cubeQuery("SELECT f.pid FROM port_cube_fences f JOIN port_cube_releases r ON r.request=f.request JOIN port_economy_item_reservations i ON i.request=f.request WHERE f.phase='RELEASED' AND i.id="+std::to_string(id)+" LIMIT 1");
|
||||
if(!cubeValid(reservation)||reservation->Get()->uiNumRows)return false;
|
||||
auto owner=cubeQuery("SELECT owner_id FROM item WHERE id="+std::to_string(id)+" AND window NOT IN ('MALL','SAFEBOX')");
|
||||
if(!cubeValid(owner)||owner->Get()->uiNumRows>1)return false;
|
||||
if(owner->Get()->uiNumRows){MYSQL_ROW row=mysql_fetch_row(owner->Get()->pSQLResult);uint64_t pid=0;if(!row||!row[0]||!PortEconomy::Number(row[0],pid,UINT32_MAX)||!pid||!cubeTerminalClear("pid="+std::to_string(pid)))return false;}
|
||||
}
|
||||
// SQL RELEASED is not the save/resume handoff. ID-only legacy destroy and
|
||||
// flush packets cannot bypass a still-held playing context after SQL locks
|
||||
// retire. Batch IDs include consumed inputs and unissued reserved rewards.
|
||||
bool held=false;
|
||||
for(const auto& entry:m_cubeDrains) {
|
||||
const auto& c=entry.second;if(!c.began||c.cancelled)continue;held=true;
|
||||
for(const auto& item:c.batch.inventory)if(item.value.id==id)return false;
|
||||
for(const auto& reward:c.batch.rewards)if(reward.id==id)return false;
|
||||
}
|
||||
if(held) {
|
||||
auto owner=cubeQuery("SELECT owner_id FROM item WHERE id="+std::to_string(id)+" AND window NOT IN ('MALL','SAFEBOX')");
|
||||
if(!cubeValid(owner)||owner->Get()->uiNumRows>1)return false;
|
||||
if(owner->Get()->uiNumRows) {
|
||||
MYSQL_ROW row=mysql_fetch_row(owner->Get()->pSQLResult);uint64_t pid=0;
|
||||
if(!row||!row[0]||!PortEconomy::Number(row[0],pid,UINT32_MAX)||!pid)return false;
|
||||
for(const auto& entry:m_cubeDrains)if(entry.second.began&&!entry.second.cancelled&&entry.second.batch.player==pid)return false;
|
||||
}
|
||||
}
|
||||
// No JOIN against item: consumed input IDs no longer have an item row, and
|
||||
// owner-less legacy destroy packets must still be denied until resync ACK.
|
||||
auto q=cubeQuery("SELECT id FROM port_cube_item_fences WHERE id="+std::to_string(id)+" LIMIT 1");
|
||||
return cubeValid(q)&&q->Get()->uiNumRows==0;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
#include "stdafx.h"
|
||||
#include "../../common/economy_mysql.h"
|
||||
#include "../../common/cube_gold_store.h"
|
||||
// Compile the complete candidate against the real pinned MySQL adapter. No
|
||||
// runtime caller or producer registration is installed by this instantiation.
|
||||
template class PortCube::GoldIntentStore<PortEconomy::Mysql>;
|
||||
@@ -0,0 +1,536 @@
|
||||
#include "stdafx.h"
|
||||
#include "ClientManager.h"
|
||||
#include "Cache.h"
|
||||
#include "Main.h"
|
||||
#include "../../common/cube_fence.h"
|
||||
#include "../../common/cube_gold_store.h"
|
||||
#include "../../common/cube_owner.h"
|
||||
#include "../../common/cube_image_ack.h"
|
||||
#include "../../common/cube_release.h"
|
||||
#include "../../common/cube_random.h"
|
||||
#include "../../common/economy_mysql.h"
|
||||
#include <algorithm>
|
||||
#include <memory>
|
||||
|
||||
bool CClientManager::CubeDrainOwner(const PortCube::RuntimeDrain& context,bool lifecycleOnly) {
|
||||
auto* peer=GetPeer(context.peer);
|
||||
auto* login=GetLoginDataByAID(context.batch.account);
|
||||
if((context.ownerLost&&!lifecycleOnly)||!peer||!peer->GetChannel()||!login||login->IsPlay()==context.recovery||login->GetConnectedPeerHandle()!=context.peer)return false;
|
||||
for(const auto& player:login->GetAccountRef().players)if(player.dwID==context.batch.player)return true;
|
||||
return false;
|
||||
}
|
||||
bool CClientManager::CubeAuthorityCheck(const PortCube::RuntimeDrain& c,bool lease) {
|
||||
auto& db=CDBManager::instance();PortEconomy::Mysql mysql(db.DirectHandle());
|
||||
PortCube::OwnerStore<PortEconomy::Mysql> owner(mysql,[&](uint32_t v){auto it=m_map_itemTableByVnum.find(v);return it==m_map_itemTableByVnum.end()?PortCube::Proto{}:PortCube::Proto{unsigned(it->second->bSize),bool(it->second->dwFlags&ITEM_FLAG_STACKABLE)};});
|
||||
return lease?owner.Check(c.batch,c.ownership):owner.Current(c.ownership.leader);
|
||||
}
|
||||
void CClientManager::CubeAuthorityRevoke(PortCube::RuntimeDrain& c,unsigned reason) {
|
||||
if(!c.began||c.revocationDone)return;auto& db=CDBManager::instance();PortEconomy::Mysql mysql(db.DirectHandle());
|
||||
auto lookup=[&](uint32_t v){auto it=m_map_itemTableByVnum.find(v);return it==m_map_itemTableByVnum.end()?PortCube::Proto{}:PortCube::Proto{unsigned(it->second->bSize),bool(it->second->dwFlags&ITEM_FLAG_STACKABLE)};};
|
||||
PortCube::OwnerStore<PortEconomy::Mysql> owner(mysql,lookup);
|
||||
PortCube::OwnerGrant receipt;const auto result=owner.Revoke(c.batch,c.ownership.leader,reason,&c.ownership,receipt);
|
||||
c.revocationDone=result==PortCube::OwnerStore<PortEconomy::Mysql>::Revoked;
|
||||
if(!c.revocationDone&&!c.recovery&&result==PortCube::OwnerStore<PortEconomy::Mysql>::Refused) {
|
||||
// Release COMMIT can precede peer loss and its reply. Only exact durable
|
||||
// terminal proof retires revocation work; token/empty lease is not proof.
|
||||
PortCube::Batch saved;std::string phase,image;PortCube::FenceStore<PortEconomy::Mysql> fence(mysql,lookup);
|
||||
PortCube::ReleaseStore<PortEconomy::Mysql> release(mysql,lookup);
|
||||
if(fence.Recover(c.batch.account,c.batch.player,saved,phase,image)==PortCube::FenceStore<PortEconomy::Mysql>::Done&&
|
||||
phase=="RELEASED"&&PortCube::Encode(saved)==PortCube::Encode(c.batch)&&release.ReleaseLive(c.batch,c.ownership,image)==PortCube::ReleaseStore<PortEconomy::Mysql>::Released) {
|
||||
c.phase="RELEASED";c.revocationDone=true; // memory save/load hold remains
|
||||
}
|
||||
}
|
||||
if(!c.revocationDone&&c.recovery&&result==PortCube::OwnerStore<PortEconomy::Mysql>::Refused) {
|
||||
// A Retry may have occurred before adoption committed. Retire only
|
||||
// after reading durable proof that this proposed grant is NOT current.
|
||||
std::string phase;uint64_t revoked=0;
|
||||
if(owner.Inspect(c.batch,c.ownership.leader,receipt,phase,revoked)&&!PortCube::SameOwnerGrant(receipt,c.ownership)&&
|
||||
(receipt.revision>=c.ownership.revision||(phase=="REVOKED"&&receipt.revision!=UINT64_MAX&&receipt.revision+1==c.ownership.revision)))c.revocationDone=true;
|
||||
}
|
||||
if(!c.revocationDone)c.nextRevocation=time(nullptr)+5;
|
||||
}
|
||||
|
||||
// Recovery preparation only. The gated internal game/DB route may call this;
|
||||
// no normal player load, currency write, image ACK or thaw is authorized here.
|
||||
bool CClientManager::CubeRecoveryClaim(CPeer* peer,DWORD handle,DWORD account,DWORD pid,uint64_t session,PortCube::OwnerGrant& grant) {
|
||||
using namespace PortCube;grant={};
|
||||
if(*GetTablePostfix()||!peer||!peer->GetChannel()||!handle||!account||!pid||!session)return false;
|
||||
auto* login=GetLoginDataByAID(account);
|
||||
if(!login||login->IsPlay()||login->GetConnectedPeerHandle()!=peer->GetHandle()||GetPeer(peer->GetHandle())!=peer)return false;
|
||||
bool member=false;for(const auto& player:login->GetAccountRef().players)if(player.dwID==pid)member=true;
|
||||
if(!member)return false;
|
||||
auto lookup=[&](uint32_t v){auto it=m_map_itemTableByVnum.find(v);return it==m_map_itemTableByVnum.end()?Proto{}:Proto{unsigned(it->second->bSize),bool(it->second->dwFlags&ITEM_FLAG_STACKABLE)};};
|
||||
auto& db=CDBManager::instance();PortEconomy::Mysql mysql(db.DirectHandle());OwnerStore<PortEconomy::Mysql> owner(mysql,lookup);
|
||||
if(m_cubeOwnerBoot.empty())m_cubeOwnerBoot=OwnerBootNonce();
|
||||
OwnerLeader leader;if(owner.Acquire(m_cubeOwnerBoot,leader)!=OwnerStore<PortEconomy::Mysql>::Acquired)return false;
|
||||
Batch batch;std::string phase,image;FenceStore<PortEconomy::Mysql> fence(mysql,lookup);
|
||||
if(fence.Recover(account,pid,batch,phase,image)!=FenceStore<PortEconomy::Mysql>::Done)return false;
|
||||
OwnerGrant active;uint64_t revoked=0;
|
||||
if(!owner.Inspect(batch,leader,active,phase,revoked))return false;
|
||||
auto remember=[&](const OwnerGrant& held)->bool {
|
||||
auto found=m_cubeDrains.find(held.binding.cookie);
|
||||
if(found!=m_cubeDrains.end())return found->second.recovery&&!found->second.ownerLost&&!found->second.revocationReason&&PortCube::SameOwnerGrant(found->second.ownership,held)&&PortCube::Encode(found->second.batch)==PortCube::Encode(batch);
|
||||
if(m_cubeDrains.size()>=128)return false;
|
||||
RuntimeDrain c;c.batch=batch;c.ownership=held;c.peer=held.peer;c.handle=held.binding.handle;c.session=held.binding.session;
|
||||
c.began=c.queued=c.finished=c.recovery=true;c.phase="ADOPTED";c.created=time(nullptr);
|
||||
m_cubeDrains.emplace(held.binding.cookie,std::move(c));m_cubeCookie=std::max(m_cubeCookie,held.binding.cookie);return true;
|
||||
};
|
||||
// Lost adoption ACK: return the exact persisted grant, never a fresh cookie.
|
||||
if(phase=="ADOPTED"&&active.leader.boot==leader.boot&&active.leader.generation==leader.generation&&active.leader.connection==leader.connection&&
|
||||
active.peer==peer->GetHandle()&&active.binding.handle==handle&&active.binding.session==session){if(!remember(active))return false;grant=active;return true;}
|
||||
if(active.leader.generation<leader.generation) {
|
||||
OwnerGrant receipt;if(owner.Revoke(batch,leader,3,nullptr,receipt)!=OwnerStore<PortEconomy::Mysql>::Revoked)return false;
|
||||
active=receipt;phase="REVOKED";revoked=leader.generation;
|
||||
}
|
||||
if(phase!="REVOKED"||revoked!=leader.generation||active.revision==UINT64_MAX||session==active.binding.session)return false;
|
||||
OwnerGrant proposal;
|
||||
for(const auto& entry:m_cubeDrains) {
|
||||
const auto& c=entry.second;
|
||||
if(c.recovery&&c.batch.token==batch.token&&c.peer==peer->GetHandle()&&c.handle==handle&&c.session==session&&c.ownership.revision==active.revision+1&&
|
||||
c.ownership.leader.boot==leader.boot&&c.ownership.leader.generation==leader.generation&&c.ownership.leader.connection==leader.connection) {
|
||||
if(c.ownerLost||c.revocationReason)return false;proposal=c.ownership;break;
|
||||
}
|
||||
}
|
||||
if(!Valid(proposal)) {
|
||||
if(m_cubeDrains.size()>=128||m_cubeCookie==UINT32_MAX)return false;
|
||||
proposal={leader,GoldSourceFor(batch,session,++m_cubeCookie,handle),peer->GetHandle(),active.revision+1};
|
||||
}
|
||||
const auto result=owner.Adopt(batch,leader,active.revision,peer->GetHandle(),proposal.binding,grant);
|
||||
if(result==OwnerStore<PortEconomy::Mysql>::Refused)return false;
|
||||
// Also retain a Retry proposal: COMMIT may have succeeded before its ACK
|
||||
// was lost. A peer close must be able to revoke it before a client retry.
|
||||
if(!remember(proposal)){grant={};return false;}
|
||||
return result==OwnerStore<PortEconomy::Mysql>::Adopted;
|
||||
}
|
||||
|
||||
DWORD CClientManager::CubeDrainArm(CPeer* peer,DWORD handle,uint64_t session,const PortCube::Batch& batch) {
|
||||
if(*GetTablePostfix()||!peer||!handle||!session||!PortCube::Validate(batch)||m_cubeDrains.size()>=128||m_cubeCookie==UINT32_MAX)return 0;
|
||||
PortCube::RuntimeDrain context;context.batch=batch;context.peer=peer->GetHandle();context.handle=handle;context.session=session;
|
||||
if(!CubeDrainOwner(context)||!CubeMemoryLoadable(batch.account,batch.player)||!CubePlayerWritable(batch.player)||m_economyFences.count(batch.player)||m_economyClosed.count(batch.player))return 0;
|
||||
auto& db=CDBManager::instance();
|
||||
PortEconomy::Mysql mysql(db.DirectHandle());
|
||||
// A modern live owner may produce deferred gold. Do not Arm a source whose
|
||||
// durable enqueue/closure schema is missing, even if the base store exists.
|
||||
PortCube::OwnerStore<PortEconomy::Mysql> store(mysql,[&](uint32_t v){auto it=m_map_itemTableByVnum.find(v);return it==m_map_itemTableByVnum.end()?PortCube::Proto{}:PortCube::Proto{unsigned(it->second->bSize),bool(it->second->dwFlags&ITEM_FLAG_STACKABLE)};});
|
||||
if(!store.Ready())return 0;
|
||||
if(m_cubeOwnerBoot.empty())m_cubeOwnerBoot=PortCube::OwnerBootNonce();
|
||||
PortCube::OwnerLeader leader;if(store.Acquire(m_cubeOwnerBoot,leader)!=PortCube::OwnerStore<PortEconomy::Mysql>::Acquired)return 0;
|
||||
// Capture BEFORE the final-save handoff, not after eviction or first barrier.
|
||||
context.main=db.EconomyFailures(false);context.async=db.EconomyFailures(true);context.router=db.SQLFenceFailures();context.created=time(nullptr);
|
||||
const DWORD cookie=++m_cubeCookie;context.ownership={leader,PortCube::GoldSourceFor(batch,session,cookie,handle),peer->GetHandle(),1};
|
||||
m_cubeDrains.emplace(cookie,std::move(context));return cookie;
|
||||
}
|
||||
|
||||
bool CClientManager::CubeMemoryLoadable(DWORD account,DWORD pid) {
|
||||
for(const auto& entry:m_cubeDrains)if(!entry.second.cancelled&&(entry.second.batch.account==account||entry.second.batch.player==pid))return false;
|
||||
return true;
|
||||
}
|
||||
bool CClientManager::CubePeerMaySave(CPeer* peer,DWORD pid) {
|
||||
for(const auto& entry:m_cubeDrains)if(!entry.second.cancelled&&entry.second.batch.player==pid)
|
||||
return !entry.second.began&&peer&&GetPeer(peer->GetHandle())==peer&&peer->GetHandle()==entry.second.peer&&CubeDrainOwner(entry.second);
|
||||
return true;
|
||||
}
|
||||
void CClientManager::CubePeerGone(DWORD peer) {
|
||||
for(auto& entry:m_cubeDrains)if(entry.second.peer==peer){entry.second.ownerLost=true;entry.second.revocationReason=1;}
|
||||
}
|
||||
void CClientManager::CubeAccountGone(DWORD account,DWORD peer) {
|
||||
if(!account||!peer)return;
|
||||
for(auto& entry:m_cubeDrains)if(entry.second.peer==peer&&entry.second.batch.account==account){entry.second.ownerLost=true;entry.second.revocationReason=2;}
|
||||
}
|
||||
void CClientManager::CubeAccountLogout(CPeer* peer,const char* data,DWORD length) {
|
||||
if(!peer||!data||length!=sizeof(TLogoutPacket))return;
|
||||
TLogoutPacket packet;std::memcpy(&packet,data,sizeof(packet));
|
||||
if(!packet.login[0]||!std::memchr(packet.login,0,sizeof(packet.login)))return;
|
||||
auto* login=GetLoginDataByLogin(packet.login);
|
||||
if(!login||login->GetConnectedPeerHandle()!=peer->GetHandle())return;
|
||||
CubeAccountGone(login->GetAccountRef().id,peer->GetHandle());
|
||||
}
|
||||
|
||||
bool CClientManager::CubeDrainSubmit(CPeer* peer,DWORD handle,uint64_t session,DWORD cookie) {
|
||||
auto it=m_cubeDrains.find(cookie);if(it==m_cubeDrains.end())return false;auto& c=it->second;
|
||||
if(!peer||peer->GetHandle()!=c.peer||handle!=c.handle||session!=c.session||!CubeDrainOwner(c)||c.finished||c.cancelled)return false;
|
||||
if(!CubeAuthorityCheck(c,c.queued))return false;
|
||||
if(c.queued)return true;
|
||||
auto* player=GetPlayerCache(c.batch.player);auto* items=GetItemCacheSet(c.batch.player);
|
||||
if(!player||!items||player->Get(false)->gold!=c.batch.gold)return false;
|
||||
std::vector<uint32_t> ids;std::vector<PortCube::Item> snapshot;
|
||||
for(auto* cache:*items) {
|
||||
const auto* item=cache->Get(false);
|
||||
if(!item->id||item->owner!=c.batch.player||ids.size()>=4096)return false;
|
||||
ids.push_back(item->id); // include gear and dirty tombstones before eviction
|
||||
if(!item->vnum||item->window!=INVENTORY||item->pos>=225)continue;
|
||||
PortCube::Item image;image.usable=false;image.cell=item->pos;image.value.id=item->id;image.value.vnum=item->vnum;image.value.count=item->count;
|
||||
for(unsigned j=0;j<3;++j){if(item->alSockets[j]<INT32_MIN||item->alSockets[j]>INT32_MAX)return false;image.value.sockets[j]=int32_t(item->alSockets[j]);}
|
||||
for(unsigned j=0;j<7;++j){image.value.types[j]=item->aAttr[j].bType;image.value.values[j]=item->aAttr[j].sValue;}
|
||||
static_assert(sizeof(item->extra)==69,"Cube requires the exact extra-item image");
|
||||
std::memcpy(image.value.extra,&item->extra,69);snapshot.push_back(image);
|
||||
}
|
||||
std::sort(ids.begin(),ids.end());if(std::adjacent_find(ids.begin(),ids.end())!=ids.end())return false;
|
||||
std::sort(snapshot.begin(),snapshot.end(),[](const PortCube::Item& a,const PortCube::Item& b){return a.cell<b.cell;});
|
||||
auto expected=c.batch.inventory;
|
||||
// usable describes runtime event/lock ownership, not a SQL column. Game must
|
||||
// validate it while frozen; equality here validates only the persisted image.
|
||||
for(auto& image:expected)image.usable=false;
|
||||
PortCube::Writer actual,wanted;actual.items(snapshot);wanted.items(expected);
|
||||
if(actual.data!=wanted.data)return false;
|
||||
auto& db=CDBManager::instance();PortEconomy::Mysql mysql(db.DirectHandle());
|
||||
PortCube::FenceStore<PortEconomy::Mysql> store(mysql,[&](uint32_t v){auto p=m_map_itemTableByVnum.find(v);return p==m_map_itemTableByVnum.end()?PortCube::Proto{}:PortCube::Proto{unsigned(p->second->bSize),bool(p->second->dwFlags&ITEM_FLAG_STACKABLE)};});
|
||||
// A lost commit ACK may already have installed the fence. Never expire or
|
||||
// accept ordinary saves again after entering Begin, including Retry/Refused.
|
||||
c.began=true;
|
||||
PortCube::OwnerStore<PortEconomy::Mysql> owner(mysql,[&](uint32_t v){auto p=m_map_itemTableByVnum.find(v);return p==m_map_itemTableByVnum.end()?PortCube::Proto{}:PortCube::Proto{unsigned(p->second->bSize),bool(p->second->dwFlags&ITEM_FLAG_STACKABLE)};});
|
||||
if(store.Begin(c.batch,ids,[&](bool replay){return owner.BindWithin(c.batch,c.ownership,replay);})!=PortCube::FenceStore<PortEconomy::Mysql>::Done)return false;
|
||||
PortCube::Batch recovered;std::string phase,image;
|
||||
if(store.Recover(c.batch.account,c.batch.player,recovered,phase,image)!=PortCube::FenceStore<PortEconomy::Mysql>::Done||PortCube::Encode(recovered)!=PortCube::Encode(c.batch)||phase!="DRAINING")return false;
|
||||
if(!c.proof.Start(c.batch,c.session,c.main,c.async))return false;
|
||||
// Flush directly, not via peer QUERY_ITEM_FLUSH, whose ingress is now gated.
|
||||
FlushItemCacheSet(c.batch.player);FlushPlayerCacheSet(c.batch.player);DeleteLogoutPlayer(c.batch.player);
|
||||
c.queued=true;c.phase="DRAINING";
|
||||
db.ReturnQuery("SELECT 1",PortCube::MainFirst,cookie,nullptr);return true;
|
||||
}
|
||||
|
||||
void CClientManager::CubeMainFence(DWORD cookie,unsigned pass,bool failed) {
|
||||
auto it=m_cubeDrains.find(cookie);if(it==m_cubeDrains.end()||!it->second.queued||it->second.finished)return;auto& c=it->second;
|
||||
if(c.proof.Main(c.batch,c.session,pass,failed)==1) {
|
||||
c.phase="FIRST";
|
||||
auto& db=CDBManager::instance();db.ReturnQuery("SELECT 1",PortCube::MainSecond,cookie,nullptr);
|
||||
c.asyncQueued=db.CubeAsyncFence(cookie);
|
||||
}
|
||||
}
|
||||
|
||||
void CClientManager::CubeDrainTick() {
|
||||
auto& db=CDBManager::instance();
|
||||
while(SQLMsg* raw=db.PopCubeAsyncFence()) {
|
||||
std::unique_ptr<SQLMsg> msg(raw);const auto cookie=uint32_t(reinterpret_cast<uintptr_t>(msg->pvUserData));
|
||||
auto it=m_cubeDrains.find(cookie);if(it!=m_cubeDrains.end()&&it->second.queued&&!it->second.finished) {
|
||||
auto& c=it->second;c.proof.Async(c.batch,c.session,msg->uiSQLErrno!=0);
|
||||
}
|
||||
}
|
||||
// One joint queue: a persistent failing revoke must not starve a different
|
||||
// actor's drain (or vice versa). Keys also distinguish two jobs on one hold.
|
||||
struct Work {uint64_t key;DWORD cookie;bool revoke;};std::vector<Work> work;
|
||||
const auto now=time(nullptr);
|
||||
for(auto it=m_cubeDrains.begin();it!=m_cubeDrains.end();) {
|
||||
const auto cookie=it->first;auto& c=it->second;
|
||||
if(!CubeDrainOwner(c,true)){c.ownerLost=true;if(!c.revocationReason)c.revocationReason=2;}
|
||||
if(!c.began&&(c.ownerLost||now-c.created>=60)){it=m_cubeDrains.erase(it);continue;}++it;
|
||||
if(c.began&&c.revocationReason&&!c.revocationDone&&c.nextRevocation<=now)work.push_back({uint64_t(cookie)*2,cookie,true});
|
||||
if(!c.queued||c.finished||c.nextAttempt>now)continue;
|
||||
if(c.phase=="FIRST"&&!c.asyncQueued)c.asyncQueued=db.CubeAsyncFence(cookie);
|
||||
if(c.proof.Complete())work.push_back({uint64_t(cookie)*2+1,cookie,false});
|
||||
}
|
||||
const auto start=std::upper_bound(work.begin(),work.end(),m_cubeWorkCursor,[](uint64_t key,const Work& item){return key<item.key;});
|
||||
const size_t offset=size_t(start-work.begin());
|
||||
for(size_t n=0;n<work.size()&&n<2;++n) {
|
||||
const auto& item=work[(offset+n)%work.size()];auto& c=m_cubeDrains.find(item.cookie)->second;m_cubeWorkCursor=item.key;
|
||||
if(item.revoke)CubeAuthorityRevoke(c,c.revocationReason);else CubeDrainFinalize(c);
|
||||
}
|
||||
for(auto it=m_cubeDrains.begin();it!=m_cubeDrains.end();) {
|
||||
if(it->second.recovery&&it->second.revocationDone)it=m_cubeDrains.erase(it);else ++it;
|
||||
} // only obsolete in-memory recovery slots retire; SQL holds survive
|
||||
}
|
||||
void CClientManager::CubeDrainFinalize(PortCube::RuntimeDrain& c) {
|
||||
auto& db=CDBManager::instance();
|
||||
// An old DB connection/generation may still have queued callbacks.
|
||||
// Do not let it finalize a drain after authority has moved elsewhere.
|
||||
PortEconomy::Mysql mysql(db.DirectHandle());
|
||||
PortCube::OwnerStore<PortEconomy::Mysql> authority(mysql,[&](uint32_t v){auto p=m_map_itemTableByVnum.find(v);return p==m_map_itemTableByVnum.end()?PortCube::Proto{}:PortCube::Proto{unsigned(p->second->bSize),bool(p->second->dwFlags&ITEM_FLAG_STACKABLE)};});
|
||||
if(!(c.ownerLost?authority.Current(c.ownership.leader):authority.Check(c.batch,c.ownership))){c.nextAttempt=time(nullptr)+5;return;}
|
||||
PortCube::FenceStore<PortEconomy::Mysql> store(mysql,[&](uint32_t v){auto p=m_map_itemTableByVnum.find(v);return p==m_map_itemTableByVnum.end()?PortCube::Proto{}:PortCube::Proto{unsigned(p->second->bSize),bool(p->second->dwFlags&ITEM_FLAG_STACKABLE)};});
|
||||
const bool owner=!c.ownerLost&&db.SQLFenceFailures()==c.router;
|
||||
auto result=store.FinishDrain(c.batch,c.proof,c.session,db.EconomyFailures(false),db.EconomyFailures(true),owner);
|
||||
if(result==PortCube::FenceStore<PortEconomy::Mysql>::Done) {
|
||||
c.finished=true;c.phase=owner&&c.proof.Clean(db.EconomyFailures(false),db.EconomyFailures(true))?"FROZEN":"ABORTED";
|
||||
} else {
|
||||
// FinishDrain may have committed despite a lost COMMIT ACK. Read
|
||||
// its original durable outcome, never infer a downgrade or unlock.
|
||||
PortCube::Batch recovered;std::string phase,image;
|
||||
if(store.Recover(c.batch.account,c.batch.player,recovered,phase,image)==PortCube::FenceStore<PortEconomy::Mysql>::Done&&
|
||||
PortCube::Encode(recovered)==PortCube::Encode(c.batch)&&(phase=="FROZEN"||phase=="ABORTED")) {
|
||||
c.finished=true;c.phase=phase;
|
||||
} else c.nextAttempt=time(nullptr)+5;
|
||||
}
|
||||
// Deliberately retain both FROZEN and ABORTED holds. Settlement/image
|
||||
// application and exact resync ACK must be wired before any release.
|
||||
}
|
||||
|
||||
void CClientManager::CubeHandshakeRequest(CPeer* peer,DWORD handle,const char* data,DWORD length) {
|
||||
PortCube::Handshake f;
|
||||
if(!peer||!peer->GetChannel()||!handle||!PortCube::DecodeHandshake(data,length,f)||PortCube::IsDbHandshakeReply(f.message))return;
|
||||
if(f.message==PortCube::Message::LiveResumeCheckRequest) {
|
||||
if(PortCube::HandshakeEnabled&&PortCube::ActorMutationAuditComplete){CubeLiveResumeCheckRoute(peer,handle,f);return;}
|
||||
f.message=PortCube::Message::LiveResumeCheckAnswer;f.status=PortCube::Status::Held;f.body.clear();
|
||||
const auto bytes=PortCube::EncodeHandshake(f);peer->EncodeHeader(PortCube::HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());return;
|
||||
}
|
||||
if(f.message==PortCube::Message::LiveReleaseRequest) {
|
||||
if(PortCube::HandshakeEnabled&&PortCube::ActorMutationAuditComplete){CubeLiveReleaseRoute(peer,handle,f);return;}
|
||||
f.message=PortCube::Message::LiveReleaseAnswer;f.status=PortCube::Status::Held;f.body.clear();
|
||||
const auto bytes=PortCube::EncodeHandshake(f);peer->EncodeHeader(PortCube::HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());return;
|
||||
}
|
||||
if(f.message==PortCube::Message::LiveImageAck) {
|
||||
if(PortCube::HandshakeEnabled&&PortCube::ActorMutationAuditComplete){CubeLiveImageAckRoute(peer,handle,f);return;}
|
||||
f.message=PortCube::Message::LiveImageAckAnswer;f.status=PortCube::Status::Held;f.body.clear();
|
||||
const auto bytes=PortCube::EncodeHandshake(f);peer->EncodeHeader(PortCube::HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());return;
|
||||
}
|
||||
if(f.message==PortCube::Message::LiveImageRequest) {
|
||||
if(PortCube::HandshakeEnabled&&PortCube::ActorMutationAuditComplete){CubeLiveImageRoute(peer,handle,f);return;}
|
||||
f.message=PortCube::Message::LiveImageAnswer;f.status=PortCube::Status::Held;
|
||||
const auto bytes=PortCube::EncodeHandshake(f);peer->EncodeHeader(PortCube::HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());return;
|
||||
}
|
||||
if(f.message==PortCube::Message::Prepare||f.message==PortCube::Message::Execute) {
|
||||
if(PortCube::HandshakeEnabled&&PortCube::ActorMutationAuditComplete){CubeCraftRoute(peer,handle,f);return;}
|
||||
f.message=PortCube::Message::CraftAnswer;f.status=PortCube::Status::Held;
|
||||
const auto bytes=PortCube::EncodeHandshake(f);peer->EncodeHeader(PortCube::HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());return;
|
||||
}
|
||||
if(f.message==PortCube::Message::RecoveryClaim||f.message==PortCube::Message::RecoveryImageRequest) {
|
||||
const bool image=f.message==PortCube::Message::RecoveryImageRequest;
|
||||
if(PortCube::HandshakeEnabled&&PortCube::ActorMutationAuditComplete){if(image)CubeRecoveryImageRoute(peer,handle,f);else CubeRecoveryRoute(peer,handle,f);return;}
|
||||
f.message=image?PortCube::Message::RecoveryImageAnswer:PortCube::Message::RecoveryAnswer;f.status=PortCube::Status::Held;
|
||||
const auto bytes=PortCube::EncodeHandshake(f);peer->EncodeHeader(PortCube::HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());return;
|
||||
}
|
||||
// Closed at the actual ingress, not merely at a UI button. In particular,
|
||||
// receiving a syntactically valid Arm does not prove the actor was frozen.
|
||||
if(!PortCube::HandshakeEnabled) {
|
||||
f.message=PortCube::Message::Answer;f.status=PortCube::Status::Held;f.body.clear();
|
||||
const auto bytes=PortCube::EncodeHandshake(f);peer->EncodeHeader(PortCube::HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());return;
|
||||
}
|
||||
CubeHandshakeRoute(peer,handle,f);
|
||||
}
|
||||
void CClientManager::CubeRecoveryRoute(CPeer* peer,DWORD handle,const PortCube::Handshake& request) {
|
||||
using namespace PortCube;if(!peer||!handle||!peer->GetChannel()||!ValidHandshake(request)||request.message!=Message::RecoveryClaim)return;
|
||||
auto reply=request;reply.message=Message::RecoveryAnswer;reply.status=Status::Held;
|
||||
auto* login=GetLoginDataByAID(request.account);bool member=false;
|
||||
if(login&&!login->IsPlay()&&GetPeer(peer->GetHandle())==peer&&login->GetConnectedPeerHandle()==peer->GetHandle())
|
||||
for(const auto& player:login->GetAccountRef().players)if(player.dwID==request.player)member=true;
|
||||
if(member&&!*GetTablePostfix()) {
|
||||
if(CubeMemoryLoadable(request.account,request.player)&&CubeAccountLoadable(request.account,request.player))reply.status=Status::RecoveryClear;
|
||||
else {
|
||||
OwnerGrant grant;
|
||||
if(CubeRecoveryClaim(peer,handle,request.account,request.player,request.session,grant)) {
|
||||
reply.status=Status::RecoveryGranted;reply.cookie=grant.binding.cookie;reply.epoch=grant.binding.epoch;reply.owner=grant.binding.owner;reply.token=grant.binding.request;reply.body=EncodeOwnerGrant(grant);
|
||||
}
|
||||
}
|
||||
}
|
||||
const auto bytes=EncodeHandshake(reply);if(bytes.empty())return;
|
||||
peer->EncodeHeader(HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());
|
||||
}
|
||||
|
||||
void CClientManager::CubeRecoveryImageRoute(CPeer* peer,DWORD handle,const PortCube::Handshake& request) {
|
||||
using namespace PortCube;
|
||||
if(!peer||!peer->GetChannel()||!handle||!ValidHandshake(request)||request.message!=Message::RecoveryImageRequest)return;
|
||||
auto reply=request;reply.message=Message::RecoveryImageAnswer;reply.status=Status::Held;
|
||||
OwnerGrant grant;DecodeOwnerGrant(request.body,grant);auto found=m_cubeDrains.find(request.cookie);
|
||||
if(!*GetTablePostfix()&&found!=m_cubeDrains.end()&&GetPeer(peer->GetHandle())==peer) {
|
||||
const auto& c=found->second;
|
||||
if(c.recovery&&c.peer==peer->GetHandle()&&c.handle==handle&&grant.binding.handle==handle&&SameOwnerGrant(c.ownership,grant)&&CubeDrainOwner(c)) {
|
||||
auto lookup=[&](uint32_t v){auto it=m_map_itemTableByVnum.find(v);return it==m_map_itemTableByVnum.end()?Proto{}:Proto{unsigned(it->second->bSize),bool(it->second->dwFlags&ITEM_FLAG_STACKABLE)};};
|
||||
PortEconomy::Mysql mysql(CDBManager::instance().DirectHandle());OwnerStore<PortEconomy::Mysql> owner(mysql,lookup);FenceStore<PortEconomy::Mysql> fence(mysql,lookup);std::string image;
|
||||
if(fence.Resync(c.batch,image,[&](const std::string& current){return owner.ImageWithin(c.batch,grant,current);})==FenceStore<PortEconomy::Mysql>::Done) {
|
||||
const auto body=EncodeRecoveryImage(grant,image);
|
||||
if(!body.empty()){reply.body=body;reply.status=Status::RecoveryImageReady;}
|
||||
}
|
||||
}
|
||||
}
|
||||
const auto bytes=EncodeHandshake(reply);if(bytes.empty())return;peer->EncodeHeader(HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());
|
||||
}
|
||||
|
||||
void CClientManager::CubeCraftRoute(CPeer* peer,DWORD handle,const PortCube::Handshake& request) {
|
||||
using namespace PortCube;
|
||||
if(!peer||!peer->GetChannel()||!handle||!ValidHandshake(request)||(request.message!=Message::Prepare&&request.message!=Message::Execute))return;
|
||||
auto reply=request;reply.message=Message::CraftAnswer;reply.status=Status::Held;
|
||||
auto found=m_cubeDrains.find(request.cookie);
|
||||
if(!*GetTablePostfix()&&found!=m_cubeDrains.end()&&GetPeer(peer->GetHandle())==peer) {
|
||||
const auto& c=found->second;
|
||||
if(!c.recovery&&c.queued&&c.finished&&c.phase=="FROZEN"&&c.peer==peer->GetHandle()&&c.handle==handle&&c.session==request.session&&
|
||||
c.batch.account==request.account&&c.batch.player==request.player&&c.batch.epoch==request.epoch&&c.batch.owner==request.owner&&c.batch.token==request.token&&CubeDrainOwner(c)) {
|
||||
auto lookup=[&](uint32_t v){auto it=m_map_itemTableByVnum.find(v);return it==m_map_itemTableByVnum.end()?Proto{}:Proto{unsigned(it->second->bSize),bool(it->second->dwFlags&ITEM_FLAG_STACKABLE)};};
|
||||
PortEconomy::Mysql mysql(CDBManager::instance().DirectHandle());OwnerStore<PortEconomy::Mysql> owner(mysql,lookup);BatchStore<PortEconomy::Mysql> store(mysql,lookup);
|
||||
if(request.message==Message::Prepare) {
|
||||
CraftEntropy entropy;
|
||||
if(store.Prepare(c.batch,[&](){return entropy.Draw();},[&](){return owner.CraftWithin(c.batch,c.ownership);})==BatchStore<PortEconomy::Mysql>::Prepared)reply.status=Status::Prepared;
|
||||
} else {
|
||||
BatchStore<PortEconomy::Mysql>::Receipt result;
|
||||
if(store.Execute(c.batch.token,c.batch.account,c.batch.player,result,[&](const Batch& saved){return Encode(saved)==Encode(c.batch)&&owner.CraftWithin(saved,c.ownership);})==BatchStore<PortEconomy::Mysql>::Complete) {
|
||||
CraftReceipt receipt{result.result,result.successes,result.fee,result.awards};reply.body=EncodeCraftReceipt(receipt);if(!reply.body.empty())reply.status=Status::Complete;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const auto bytes=EncodeHandshake(reply);if(bytes.empty())return;peer->EncodeHeader(HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());
|
||||
}
|
||||
|
||||
void CClientManager::CubeLiveImageRoute(CPeer* peer,DWORD handle,const PortCube::Handshake& request) {
|
||||
using namespace PortCube;
|
||||
if(!peer||!peer->GetChannel()||!handle||!ValidHandshake(request)||request.message!=Message::LiveImageRequest)return;
|
||||
auto reply=request;reply.message=Message::LiveImageAnswer;reply.status=Status::Held;
|
||||
auto found=m_cubeDrains.find(request.cookie);
|
||||
if(!*GetTablePostfix()&&found!=m_cubeDrains.end()&&GetPeer(peer->GetHandle())==peer) {
|
||||
auto& c=found->second;
|
||||
if(!c.recovery&&c.queued&&c.finished&&(c.phase=="FROZEN"||c.phase=="RESYNC")&&c.peer==peer->GetHandle()&&c.handle==handle&&c.session==request.session&&
|
||||
c.batch.account==request.account&&c.batch.player==request.player&&c.batch.epoch==request.epoch&&c.batch.owner==request.owner&&c.batch.token==request.token&&CubeDrainOwner(c)) {
|
||||
auto lookup=[&](uint32_t v){auto it=m_map_itemTableByVnum.find(v);return it==m_map_itemTableByVnum.end()?Proto{}:Proto{unsigned(it->second->bSize),bool(it->second->dwFlags&ITEM_FLAG_STACKABLE)};};
|
||||
PortEconomy::Mysql mysql(CDBManager::instance().DirectHandle());OwnerStore<PortEconomy::Mysql> owner(mysql,lookup);FenceStore<PortEconomy::Mysql> fence(mysql,lookup);GoldIntentStore<PortEconomy::Mysql> gold(mysql,lookup);
|
||||
std::vector<GoldIntent> pending;bool credited=gold.Pending(c.batch,pending)==GoldIntentStore<PortEconomy::Mysql>::Stored;
|
||||
for(size_t n=0;credited&&n<std::min(size_t(2),pending.size());++n) {
|
||||
typename GoldIntentStore<PortEconomy::Mysql>::Receipt receipt;
|
||||
credited=gold.Apply(pending[n].event,c.batch.account,c.batch.player,receipt,[&](const GoldIntent& intent){return Matches(intent,c.batch)&&owner.CraftWithin(c.batch,c.ownership);})==GoldIntentStore<PortEconomy::Mysql>::Applied;
|
||||
}
|
||||
std::string image;
|
||||
if(credited&&pending.size()<=2&&fence.Resync(c.batch,image,[&](const std::string& current){return owner.LiveImageWithin(c.batch,c.ownership,current);})==FenceStore<PortEconomy::Mysql>::Done) {
|
||||
reply.body=std::move(image);reply.status=Status::LiveImageReady;c.phase="RESYNC";
|
||||
}
|
||||
}
|
||||
}
|
||||
const auto bytes=EncodeHandshake(reply);if(bytes.empty())return;peer->EncodeHeader(HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());
|
||||
}
|
||||
|
||||
void CClientManager::CubeLiveImageAckRoute(CPeer* peer,DWORD handle,const PortCube::Handshake& request) {
|
||||
using namespace PortCube;
|
||||
if(!peer||!peer->GetChannel()||!handle||!ValidHandshake(request)||request.message!=Message::LiveImageAck)return;
|
||||
auto reply=request;reply.message=Message::LiveImageAckAnswer;reply.status=Status::Held;reply.body.clear();
|
||||
const auto found=m_cubeDrains.find(request.cookie);
|
||||
if(!*GetTablePostfix()&&found!=m_cubeDrains.end()&&GetPeer(peer->GetHandle())==peer) {
|
||||
const auto& c=found->second;
|
||||
if(!c.recovery&&c.queued&&c.finished&&c.phase=="RESYNC"&&c.peer==peer->GetHandle()&&c.handle==handle&&c.session==request.session&&
|
||||
c.batch.account==request.account&&c.batch.player==request.player&&c.batch.epoch==request.epoch&&c.batch.owner==request.owner&&c.batch.token==request.token&&CubeDrainOwner(c)) {
|
||||
auto lookup=[&](uint32_t v){auto it=m_map_itemTableByVnum.find(v);return it==m_map_itemTableByVnum.end()?Proto{}:Proto{unsigned(it->second->bSize),bool(it->second->dwFlags&ITEM_FLAG_STACKABLE)};};
|
||||
PortEconomy::Mysql mysql(CDBManager::instance().DirectHandle());ImageAckStore<PortEconomy::Mysql> ack(mysql,lookup);
|
||||
if(ack.AcknowledgeLive(c.batch,c.ownership,request.body)==ImageAckStore<PortEconomy::Mysql>::Stored) {
|
||||
reply.status=Status::LiveImageAcknowledged;reply.body=request.body;
|
||||
}
|
||||
}
|
||||
}
|
||||
const auto bytes=EncodeHandshake(reply);if(bytes.empty())return;peer->EncodeHeader(HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());
|
||||
}
|
||||
|
||||
void CClientManager::CubeLiveReleaseRoute(CPeer* peer,DWORD handle,const PortCube::Handshake& request) {
|
||||
using namespace PortCube;
|
||||
if(!peer||!peer->GetChannel()||!handle||!ValidHandshake(request)||request.message!=Message::LiveReleaseRequest)return;
|
||||
auto reply=request;reply.message=Message::LiveReleaseAnswer;reply.status=Status::Held;reply.body.clear();
|
||||
const auto found=m_cubeDrains.find(request.cookie);
|
||||
if(!*GetTablePostfix()&&found!=m_cubeDrains.end()&&GetPeer(peer->GetHandle())==peer) {
|
||||
auto& c=found->second;
|
||||
if(!c.recovery&&c.queued&&c.finished&&(c.phase=="RESYNC"||c.phase=="RELEASED")&&c.peer==peer->GetHandle()&&c.handle==handle&&c.session==request.session&&
|
||||
c.batch.account==request.account&&c.batch.player==request.player&&c.batch.epoch==request.epoch&&c.batch.owner==request.owner&&c.batch.token==request.token&&CubeDrainOwner(c)) {
|
||||
auto lookup=[&](uint32_t v){auto it=m_map_itemTableByVnum.find(v);return it==m_map_itemTableByVnum.end()?Proto{}:Proto{unsigned(it->second->bSize),bool(it->second->dwFlags&ITEM_FLAG_STACKABLE)};};
|
||||
PortEconomy::Mysql mysql(CDBManager::instance().DirectHandle());ReleaseStore<PortEconomy::Mysql> release(mysql,lookup);
|
||||
if(release.ReleaseLive(c.batch,c.ownership,request.body)==ReleaseStore<PortEconomy::Mysql>::Released) {
|
||||
c.phase="RELEASED";c.revocationDone=true;reply.status=Status::LiveReleased;reply.body=request.body;
|
||||
}
|
||||
}
|
||||
}
|
||||
const auto bytes=EncodeHandshake(reply);if(bytes.empty())return;peer->EncodeHeader(HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());
|
||||
}
|
||||
|
||||
void CClientManager::CubeLiveResumeCheckRoute(CPeer* peer,DWORD handle,const PortCube::Handshake& request) {
|
||||
using namespace PortCube;
|
||||
if(!peer||!peer->GetChannel()||!handle||!ValidHandshake(request)||request.message!=Message::LiveResumeCheckRequest)return;
|
||||
auto reply=request;reply.message=Message::LiveResumeCheckAnswer;reply.status=Status::Held;reply.body.clear();
|
||||
const auto found=m_cubeDrains.find(request.cookie);
|
||||
if(!*GetTablePostfix()&&found!=m_cubeDrains.end()&&GetPeer(peer->GetHandle())==peer) {
|
||||
const auto& c=found->second;
|
||||
if(!c.recovery&&c.queued&&c.finished&&c.phase=="RELEASED"&&c.revocationDone&&c.peer==peer->GetHandle()&&c.handle==handle&&c.session==request.session&&
|
||||
c.batch.account==request.account&&c.batch.player==request.player&&c.batch.epoch==request.epoch&&c.batch.owner==request.owner&&c.batch.token==request.token&&CubeDrainOwner(c)) {
|
||||
auto lookup=[&](uint32_t v){auto it=m_map_itemTableByVnum.find(v);return it==m_map_itemTableByVnum.end()?Proto{}:Proto{unsigned(it->second->bSize),bool(it->second->dwFlags&ITEM_FLAG_STACKABLE)};};
|
||||
PortEconomy::Mysql mysql(CDBManager::instance().DirectHandle());ReleaseStore<PortEconomy::Mysql> release(mysql,lookup);
|
||||
if(release.CheckResumeLive(c.batch,c.ownership,request.body)==ReleaseStore<PortEconomy::Mysql>::Checked){reply.status=Status::LiveResumeChecked;reply.body=request.body;}
|
||||
}
|
||||
}
|
||||
// Read-only preflight: no context erasure, save/load grant or actor thaw.
|
||||
const auto bytes=EncodeHandshake(reply);if(bytes.empty())return;peer->EncodeHeader(HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());
|
||||
}
|
||||
|
||||
void CClientManager::CubeHandshakeRoute(CPeer* peer,DWORD handle,const PortCube::Handshake& f) {
|
||||
using namespace PortCube;
|
||||
if(f.message==Message::LiveResumeCheckRequest){CubeLiveResumeCheckRoute(peer,handle,f);return;}
|
||||
if(f.message==Message::LiveReleaseRequest){CubeLiveReleaseRoute(peer,handle,f);return;}
|
||||
if(f.message==Message::LiveImageAck){CubeLiveImageAckRoute(peer,handle,f);return;}
|
||||
if(f.message==Message::LiveImageRequest){CubeLiveImageRoute(peer,handle,f);return;}
|
||||
if(f.message==Message::Prepare||f.message==Message::Execute){CubeCraftRoute(peer,handle,f);return;}
|
||||
if(f.message==Message::RecoveryClaim){CubeRecoveryRoute(peer,handle,f);return;}
|
||||
if(f.message==Message::RecoveryImageRequest){CubeRecoveryImageRoute(peer,handle,f);return;}
|
||||
if(!peer||!handle||!peer->GetChannel()||!ValidHandshake(f)||IsDbHandshakeReply(f.message))return;
|
||||
RuntimeDrain binding;binding.batch.account=f.account;binding.batch.player=f.player;binding.peer=peer->GetHandle();
|
||||
if(!CubeDrainOwner(binding))return; // authenticated core AND current account ownership
|
||||
auto send=[&](Status status,DWORD cookie) {
|
||||
Handshake reply=f;reply.message=Message::Answer;reply.status=status;reply.cookie=cookie;reply.body.clear();
|
||||
const auto bytes=EncodeHandshake(reply);if(bytes.empty())return;
|
||||
peer->EncodeHeader(HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());
|
||||
};
|
||||
auto matches=[&](const RuntimeDrain& c) {
|
||||
return c.peer==peer->GetHandle()&&c.handle==handle&&c.session==f.session&&c.batch.account==f.account&&c.batch.player==f.player&&
|
||||
c.batch.epoch==f.epoch&&c.batch.owner==f.owner&&c.batch.token==f.token;
|
||||
};
|
||||
auto status=[&](const RuntimeDrain& c) {
|
||||
if(c.cancelled)return Status::Cancelled;
|
||||
if(!CubeDrainOwner(c))return Status::Held;
|
||||
if(c.finished)return c.phase=="FROZEN"?Status::Frozen:c.phase=="ABORTED"?Status::Aborted:Status::Held;
|
||||
if(c.queued)return Status::Draining;
|
||||
return c.began?Status::Held:Status::Armed;
|
||||
};
|
||||
if(f.message==Message::Arm) {
|
||||
for(const auto& entry:m_cubeDrains)if(matches(entry.second)) {
|
||||
// Exact retry returns the original cookie; changed body is not a
|
||||
// second Arm and must not release or replace the first hold.
|
||||
send(Encode(entry.second.batch)==f.body&&CubeAuthorityCheck(entry.second,entry.second.queued)?status(entry.second):Status::Held,entry.first);return;
|
||||
}
|
||||
Batch b;if(!Decode(f.body,b))return;
|
||||
const auto cookie=CubeDrainArm(peer,handle,f.session,b);
|
||||
send(cookie?Status::Armed:Status::Held,cookie);return;
|
||||
}
|
||||
auto it=m_cubeDrains.find(f.cookie);
|
||||
if(it==m_cubeDrains.end()||!matches(it->second)){send(Status::Held,f.cookie);return;}
|
||||
auto& c=it->second;
|
||||
if(c.cancelled){send(Status::Cancelled,f.cookie);return;}
|
||||
if(!CubeAuthorityCheck(c,c.queued)){c.ownerLost=true;send(Status::Held,f.cookie);return;}
|
||||
if(f.message==Message::GoldClose) {
|
||||
if(!c.began||!CubeDrainOwner(c)){send(Status::Held,f.cookie);return;}
|
||||
GoldSourceSeal seal;static_cast<GoldSourceBinding&>(seal)=GoldSourceFor(c.batch,f.session,f.cookie,handle);
|
||||
if(!DecodeGoldManifest(f.body,seal.events))return;
|
||||
auto& db=CDBManager::instance();PortEconomy::Mysql mysql(db.DirectHandle());
|
||||
OwnerStore<PortEconomy::Mysql> authority(mysql,[&](uint32_t v){auto p=m_map_itemTableByVnum.find(v);return p==m_map_itemTableByVnum.end()?Proto{}:Proto{unsigned(p->second->bSize),bool(p->second->dwFlags&ITEM_FLAG_STACKABLE)};});
|
||||
if(!authority.Check(c.batch,c.ownership)){send(Status::Held,f.cookie);return;}
|
||||
GoldIntentStore<PortEconomy::Mysql> store(mysql,[&](uint32_t v){auto p=m_map_itemTableByVnum.find(v);return p==m_map_itemTableByVnum.end()?Proto{}:Proto{unsigned(p->second->bSize),bool(p->second->dwFlags&ITEM_FLAG_STACKABLE)};});
|
||||
if(store.CloseSource(c.batch,seal)!=GoldIntentStore<PortEconomy::Mysql>::Stored){send(Status::Held,f.cookie);return;}
|
||||
auto reply=f;reply.message=Message::GoldCloseAck;reply.status=Status::GoldClosed;const auto bytes=EncodeHandshake(reply);
|
||||
if(bytes.empty())return;peer->EncodeHeader(HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());return;
|
||||
}
|
||||
if(f.message==Message::GoldEnqueue) {
|
||||
// Original authenticated peer/login/handle/session/cookie AND immutable
|
||||
// batch, not a client-provided amount on an unowned player. DB restart
|
||||
// loses this binding: keep the source outbox pending, never adopt it.
|
||||
GoldIntent i;
|
||||
if(!c.began||!CubeDrainOwner(c)||!DecodeGoldIntent(f.body,i)||!Matches(i,c.batch)){send(Status::Held,f.cookie);return;}
|
||||
auto& db=CDBManager::instance();PortEconomy::Mysql mysql(db.DirectHandle());
|
||||
OwnerStore<PortEconomy::Mysql> authority(mysql,[&](uint32_t v){auto p=m_map_itemTableByVnum.find(v);return p==m_map_itemTableByVnum.end()?Proto{}:Proto{unsigned(p->second->bSize),bool(p->second->dwFlags&ITEM_FLAG_STACKABLE)};});
|
||||
if(!authority.Check(c.batch,c.ownership)){send(Status::Held,f.cookie);return;}
|
||||
GoldIntentStore<PortEconomy::Mysql> store(mysql,[&](uint32_t v){auto p=m_map_itemTableByVnum.find(v);return p==m_map_itemTableByVnum.end()?Proto{}:Proto{unsigned(p->second->bSize),bool(p->second->dwFlags&ITEM_FLAG_STACKABLE)};});
|
||||
const auto result=store.Enqueue(c.batch,i);
|
||||
if(result!=GoldIntentStore<PortEconomy::Mysql>::Stored&&result!=GoldIntentStore<PortEconomy::Mysql>::Applied){send(Status::Held,f.cookie);return;}
|
||||
auto reply=f;reply.message=Message::GoldAck;reply.status=result==GoldIntentStore<PortEconomy::Mysql>::Stored?Status::GoldStored:Status::GoldApplied;
|
||||
const auto bytes=EncodeHandshake(reply);if(bytes.empty())return;
|
||||
peer->EncodeHeader(HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());return;
|
||||
}
|
||||
if(f.message==Message::Invalidate) {
|
||||
// Sticky poison. Never turn an invalidated actor snapshot into a clean
|
||||
// FROZEN proof, even if its ordinary values later return to the same bytes.
|
||||
c.ownerLost=true;
|
||||
if(c.began) {
|
||||
auto& db=CDBManager::instance();PortEconomy::Mysql mysql(db.DirectHandle());
|
||||
FenceStore<PortEconomy::Mysql> store(mysql,[&](uint32_t v){auto p=m_map_itemTableByVnum.find(v);return p==m_map_itemTableByVnum.end()?Proto{}:Proto{unsigned(p->second->bSize),bool(p->second->dwFlags&ITEM_FLAG_STACKABLE)};});
|
||||
// The store refuses to abort an already accepted/ambiguous Prepare.
|
||||
// Retain that hold for receipt recovery instead of inventing refunds.
|
||||
if(store.AbortUnprepared(c.batch)==FenceStore<PortEconomy::Mysql>::Done)c.phase="ABORTED";
|
||||
}
|
||||
send(Status::Held,f.cookie);return;
|
||||
}
|
||||
if(f.message==Message::Cancel) {
|
||||
// No SQL Begin attempt: no accepted/ambiguous durable ownership exists.
|
||||
// Keep a short tombstone so lost cancellation ACK can be replayed.
|
||||
if(!c.began&&!c.ownerLost){c.cancelled=true;c.created=time(nullptr);send(Status::Cancelled,f.cookie);}
|
||||
else send(Status::Held,f.cookie);
|
||||
return;
|
||||
}
|
||||
if(f.message==Message::Submit&&!c.finished&&!c.queued)CubeDrainSubmit(peer,handle,f.session,f.cookie);
|
||||
send(status(c),f.cookie); // Submit refusal is a hold, never an unlock ACK
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
#include "../../common/cube_drain.h"
|
||||
#include "../../common/cube_handshake.h"
|
||||
#include "../../common/cube_owner_types.h"
|
||||
#include <ctime>
|
||||
|
||||
namespace PortCube {
|
||||
// Internal DB adapter. Header78 dispatch is compiled but ingress is hard-gated
|
||||
// off in cube_handshake.h. A game coordinator MUST quiesce the actor before Arm,
|
||||
// send final saves after Arm ACK, and submit on the same peer FIFO. These APIs
|
||||
// and the game preparation state machine do not themselves stop asset events.
|
||||
constexpr int MainFirst=101,MainSecond=102;
|
||||
struct RuntimeDrain {
|
||||
Batch batch;Drain proof;
|
||||
uint64_t session=0,main=0,async=0,router=0;
|
||||
uint32_t peer=0,handle=0;
|
||||
bool began=false,queued=false,asyncQueued=false,ownerLost=false,finished=false,cancelled=false;
|
||||
std::time_t created=0,nextAttempt=0;
|
||||
std::string phase;
|
||||
OwnerGrant ownership;
|
||||
bool revocationDone=false;
|
||||
unsigned revocationReason=0; // trusted peer/account lifecycle, not Invalidate
|
||||
bool recovery=false; // held pre-load adoption, not a playing actor
|
||||
std::time_t nextRevocation=0;
|
||||
};
|
||||
}
|
||||
@@ -52,6 +52,7 @@ void CDBManager::Clear()
|
||||
}
|
||||
}
|
||||
|
||||
PortSQLFence::PlayerRouter().Clear();
|
||||
Initialize();
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#include <mysql/mysql.h>
|
||||
|
||||
#include "../../libsql/AsyncSQL.h"
|
||||
#include "SQLFences.h"
|
||||
|
||||
#define SQL_SAFE_LENGTH(size) (size * 2 + 1)
|
||||
#define QUERY_SAFE_LENGTH(size) (1024 + SQL_SAFE_LENGTH(size))
|
||||
@@ -46,6 +47,12 @@ class CDBManager : public singleton<CDBManager>
|
||||
|
||||
void ReturnQuery(const char * c_pszQuery, int iType, DWORD dwIdent, void * pvData, int iSlot = SQL_PLAYER);
|
||||
void AsyncQuery(const char * c_pszQuery, int iSlot = SQL_PLAYER);
|
||||
bool EconomyAsyncFence(DWORD pid) { return PortSQLFence::Queue(m_asyncSQL[SQL_PLAYER],PortSQLFence::Economy,pid); }
|
||||
SQLMsg* PopEconomyAsyncFence() { return PortSQLFence::Pop(m_asyncSQL[SQL_PLAYER],PortSQLFence::Economy); }
|
||||
bool CubeAsyncFence(DWORD cookie) { return PortSQLFence::Queue(m_asyncSQL[SQL_PLAYER],PortSQLFence::Cube,cookie); }
|
||||
SQLMsg* PopCubeAsyncFence() { return PortSQLFence::Pop(m_asyncSQL[SQL_PLAYER],PortSQLFence::Cube); }
|
||||
uint64_t SQLFenceFailures() { return PortSQLFence::PlayerRouter().Failures(); }
|
||||
uint64_t EconomyFailures(bool async) { return (async?m_asyncSQL[SQL_PLAYER]:m_mainSQL[SQL_PLAYER])->FailureEpoch(); }
|
||||
MYSQL* DirectHandle(int slot=SQL_PLAYER) { return m_directSQL[slot]->GetSQLHandle(); }
|
||||
SQLMsg * DirectQuery(const char * c_pszQuery, int iSlot = SQL_PLAYER);
|
||||
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
#include "stdafx.h"
|
||||
#include "ClientManager.h"
|
||||
#include "Cache.h"
|
||||
#include "QID.h"
|
||||
#include "Main.h"
|
||||
#include "../../common/economy_mysql.h"
|
||||
#include <memory>
|
||||
#include "../../common/economy_view.h"
|
||||
|
||||
namespace {
|
||||
using namespace PortEconomy;
|
||||
using Query=std::unique_ptr<SQLMsg>;
|
||||
Query query(const std::string& sql){return Query(CDBManager::instance().DirectQuery(sql.c_str()));}
|
||||
bool valid(const Query& q){return q&&!q->uiSQLErrno&&q->Get();}
|
||||
// Schema installation/removal requires a coordinated restart. An absent schema
|
||||
// is detected once without issuing failing SQL for every ordinary item save.
|
||||
int schema() {
|
||||
static int state=-1;if(state>=0)return state;
|
||||
auto q=query("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='port_economy_version'");
|
||||
if(!valid(q)||q->Get()->uiNumRows!=1)return -1;
|
||||
MYSQL_ROW row=mysql_fetch_row(q->Get()->pSQLResult);if(!row||!row[0])return -1;
|
||||
state=std::string(row[0])=="1"?1:0;return state;
|
||||
}
|
||||
bool owns(CLoginData* login,CPeer* peer,DWORD pid,bool playing) {
|
||||
if(!login || login->GetConnectedPeerHandle()!=peer->GetHandle() || login->IsPlay()!=playing)return false;
|
||||
for(const auto& p:login->GetAccountRef().players)if(p.dwID==pid)return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void CClientManager::EconomyRequest(CPeer* peer,DWORD handle,const char* data,DWORD length) {
|
||||
if(length!=sizeof(PortEconomy::Request)||!peer->GetChannel())return;
|
||||
PortEconomy::Request r;memcpy(&r,data,sizeof(r));
|
||||
if(!PortEconomy::Valid(r)||!owns(GetLoginDataByAID(r.account),peer,r.player,true))return;
|
||||
PortEconomy::Reply reply={};reply.account=r.account;reply.player=r.player;
|
||||
auto send=[&](const std::string& text,bool success){reply.ok=success;const std::string message=r.operation==PortEconomy::UiStatus&&text.find("MTECON1 ")!=0?"MTECON1 error "+std::to_string(r.generation)+" storage":text;strlcpy(reply.message,message.c_str(),sizeof(reply.message));peer->EncodeHeader(PortEconomy::Header,handle,sizeof(reply));peer->Encode(&reply,sizeof(reply));};
|
||||
if(*GetTablePostfix()||schema()!=1){send("Economy transactions require the unsuffixed player schema.",false);return;}
|
||||
PortEconomy::Mysql mysql(CDBManager::instance().DirectHandle());
|
||||
PortEconomy::Store<PortEconomy::Mysql> store(mysql,[&](uint32_t vnum){auto it=m_map_itemTableByVnum.find(vnum);return it==m_map_itemTableByVnum.end()?0u:unsigned(it->second->bSize);});
|
||||
if(!store.Ready()){send("Economy storage is unavailable; no payment was made.",false);return;}
|
||||
if(r.operation==PortEconomy::UiStatus) {
|
||||
std::vector<std::string> frames;
|
||||
if(!PortEconomy::View(mysql,r,[&](uint32_t vnum){auto it=m_map_itemTableByVnum.find(vnum);return it==m_map_itemTableByVnum.end()?0u:unsigned(it->second->bSize);},frames)) {
|
||||
send("MTECON1 error "+std::to_string(r.generation)+" storage",false);return;
|
||||
}
|
||||
for(const auto& frame:frames)send(frame,true);
|
||||
return;
|
||||
}
|
||||
if(r.operation==PortEconomy::Status) {
|
||||
PortEconomy::Rows rows;
|
||||
if(!mysql.Query("SELECT token,result,reference FROM port_economy_requests WHERE pid="+std::to_string(r.player)+" ORDER BY created_at DESC,token DESC LIMIT 3",rows)){send("Economy storage is unavailable.",false);return;}
|
||||
std::string text="Recent transactions:";
|
||||
for(const auto& row:rows)text+=" "+row[1]+" #"+row[2];send(text,true);
|
||||
if(mysql.Query("SELECT l.id,l.price,l.state,COALESCE(c.vnum,0),COALESCE(c.count,0) FROM port_economy_listings l LEFT JOIN port_economy_custody c ON c.id=l.item WHERE l.state='OPEN' OR l.owner="+std::to_string(r.player)+" ORDER BY l.id DESC LIMIT 5 OFFSET "+std::to_string(r.reference*5),rows))for(const auto& row:rows)send("Listing #"+row[0]+" vnum="+row[3]+" count="+row[4]+" price="+row[1]+" "+row[2],true);
|
||||
if(mysql.Query("SELECT id,state FROM port_economy_orders WHERE buyer="+std::to_string(r.player)+" ORDER BY id DESC LIMIT 5 OFFSET "+std::to_string(r.reference*5),rows))for(const auto& row:rows)send("Order #"+row[0]+" "+row[1],true);
|
||||
if(mysql.Query("SELECT amount FROM port_economy_credit WHERE pid="+std::to_string(r.player),rows))send("Unclaimed proceeds: "+(rows.empty()?std::string("0"):rows[0][0]),true);
|
||||
return;
|
||||
}
|
||||
if(!CubeMemoryLoadable(r.account,r.player)||!CubePlayerWritable(r.player)){send("Character assets are awaiting Cube reconciliation.",false);return;}
|
||||
if(r.operation==PortEconomy::List) {
|
||||
auto it=m_map_itemTableByVnum.find(r.itemVnum);
|
||||
if(it==m_map_itemTableByVnum.end() || (it->second->dwAntiFlags&(ITEM_ANTIFLAG_GIVE|ITEM_ANTIFLAG_MYSHOP)) || it->second->bType==ITEM_QUEST) {send("This item cannot be listed.",false);return;}
|
||||
}
|
||||
// Materialized Gaya stacks are generated by game using the normal item
|
||||
// factory. Validate proto stack limits before accepting their durable IDs.
|
||||
for(unsigned i=0;i<r.rewardCount;++i) {
|
||||
const auto& reward=r.rewards[i];auto it=m_map_itemTableByVnum.find(reward.vnum);
|
||||
if(it==m_map_itemTableByVnum.end() || reward.count>2000 || (!(it->second->dwFlags&ITEM_FLAG_STACKABLE)&&reward.count!=1)){send("Invalid reward stack.",false);return;}
|
||||
}
|
||||
if(store.Enqueue(r)) {
|
||||
m_economyOwners[r.player]=r.account;
|
||||
m_economyEnqueueEpoch.emplace(r.player,std::make_pair(CDBManager::instance().EconomyFailures(false),CDBManager::instance().EconomyFailures(true)));
|
||||
send("Transaction queued. Reconnect and select the character to settle it; use /mt_economy status for the result.",true);
|
||||
} else send("Transaction was not accepted, or another request is pending. Reconnect to recover it.",false);
|
||||
}
|
||||
|
||||
bool CClientManager::EconomyBeforeLoad(CPeer* peer,DWORD handle,TPlayerLoadPacket* packet) {
|
||||
if(!CubeMemoryLoadable(packet->account_id,packet->player_id))return false;
|
||||
if(!CubeAccountLoadable(packet->account_id,packet->player_id))return false;
|
||||
if(*GetTablePostfix())return true;
|
||||
const int installed=schema();if(installed==0)return true;if(installed<0)return false;
|
||||
// Existing ownership checks must run before evicting or fencing any cache.
|
||||
auto* login=GetLoginDataByAID(packet->account_id);
|
||||
if(!owns(login,peer,packet->player_id,false))return false;
|
||||
for(const auto& running:m_economyFences)if(running.second.account==packet->account_id)return false;
|
||||
auto pending=query("SELECT token FROM port_economy_pending WHERE pid="+std::to_string(packet->player_id));
|
||||
if(!valid(pending))return false;
|
||||
if(!pending->Get()->uiNumRows){m_economyClosed.erase(packet->player_id);return true;}
|
||||
m_economyOwners[packet->player_id]=packet->account_id;
|
||||
m_economyClosed.insert(packet->player_id);
|
||||
EconomyFence fence;fence.account=packet->account_id;fence.peer=peer->GetHandle();fence.handle=handle;fence.load=*packet;
|
||||
auto& database=CDBManager::instance();
|
||||
auto epoch=m_economyEnqueueEpoch.find(packet->player_id);
|
||||
fence.mainFailures=epoch==m_economyEnqueueEpoch.end()?database.EconomyFailures(false):epoch->second.first;
|
||||
fence.asyncFailures=epoch==m_economyEnqueueEpoch.end()?database.EconomyFailures(true):epoch->second.second;
|
||||
fence.routerFailures=database.SQLFenceFailures();
|
||||
m_economyFences[packet->player_id]=fence;
|
||||
// Eviction sends every dirty snapshot before the two FIFO barriers. Never
|
||||
// settle on a cached player, including caches still awaiting logout timeout.
|
||||
FlushItemCacheSet(packet->player_id);FlushPlayerCacheSet(packet->player_id);
|
||||
DeleteLogoutPlayer(packet->player_id);
|
||||
database.ReturnQuery("SELECT 1",QID_ECONOMY_FENCE,packet->player_id,nullptr);
|
||||
return false;
|
||||
}
|
||||
|
||||
void CClientManager::EconomyMainFence(DWORD pid,bool failed) {
|
||||
auto it=m_economyFences.find(pid);if(it==m_economyFences.end())return;
|
||||
it->second.failed|=failed;
|
||||
if(!it->second.primed) {
|
||||
// Earlier load callbacks may themselves queue saves (e.g. mall awards).
|
||||
// A second main barrier and an async barrier follow those callbacks.
|
||||
it->second.primed=true;
|
||||
CDBManager::instance().ReturnQuery("SELECT 1",QID_ECONOMY_FENCE,pid,nullptr);
|
||||
it->second.asyncQueued=CDBManager::instance().EconomyAsyncFence(pid);
|
||||
} else it->second.mainDone=true;
|
||||
}
|
||||
void CClientManager::EconomyTick() {
|
||||
auto& database=CDBManager::instance();
|
||||
for(auto& entry:m_economyFences)if(entry.second.primed&&!entry.second.asyncQueued)
|
||||
entry.second.asyncQueued=database.EconomyAsyncFence(entry.first);
|
||||
while(SQLMsg* raw=database.PopEconomyAsyncFence()) {
|
||||
Query q(raw);DWORD pid=static_cast<DWORD>(reinterpret_cast<uintptr_t>(q->pvUserData));
|
||||
auto it=m_economyFences.find(pid);if(it!=m_economyFences.end()){it->second.asyncDone=true;it->second.failed|=q->uiSQLErrno!=0;}
|
||||
}
|
||||
for(auto it=m_economyFences.begin();it!=m_economyFences.end();) {
|
||||
auto& fence=it->second;
|
||||
if(fence.nextAttempt>time(nullptr)){++it;continue;}
|
||||
if(!fence.mainDone||!fence.asyncDone){++it;continue;}
|
||||
auto* login=GetLoginDataByAID(fence.account);
|
||||
if((login&&login->IsPlay())||!CubeMemoryLoadable(fence.account,it->first)||!CubePlayerWritable(it->first)){++it;continue;}
|
||||
PortEconomy::Mysql mysql(database.DirectHandle());
|
||||
PortEconomy::Store<PortEconomy::Mysql> store(mysql,[&](uint32_t vnum){auto p=m_map_itemTableByVnum.find(vnum);return p==m_map_itemTableByVnum.end()?0u:unsigned(p->second->bSize);});
|
||||
const bool failed=fence.failed||database.EconomyFailures(false)!=fence.mainFailures||database.EconomyFailures(true)!=fence.asyncFailures||database.SQLFenceFailures()!=fence.routerFailures;
|
||||
bool done=failed?store.Abort(it->first,fence.account):store.Settle(it->first,fence.account)!=PortEconomy::Store<PortEconomy::Mysql>::Retry;
|
||||
if(done) {
|
||||
m_economyEnqueueEpoch.erase(it->first);
|
||||
sys_log(0,"ECONOMY_SETTLE pid=%u outcome=%s ref=%llu",it->first,failed?"save_failed":store.Outcome().c_str(),static_cast<unsigned long long>(store.Reference()));
|
||||
EconomyFence completed=fence;it=m_economyFences.erase(it);
|
||||
if(CPeer* peer=GetPeer(completed.peer))QUERY_PLAYER_LOAD(peer,completed.handle,&completed.load);
|
||||
} else {fence.nextAttempt=time(nullptr)+5;++it;}
|
||||
}
|
||||
}
|
||||
|
||||
bool CClientManager::EconomySaveAllowed(CPeer* peer,DWORD pid) {
|
||||
if(!CubePeerMaySave(peer,pid))return false;
|
||||
if(!CubePlayerWritable(pid))return false;
|
||||
if(m_economyClosed.count(pid))return false;
|
||||
auto it=m_economyOwners.find(pid);if(it==m_economyOwners.end())return true;
|
||||
return owns(GetLoginDataByAID(it->second),peer,pid,true);
|
||||
}
|
||||
bool CClientManager::EconomyItemWritable(DWORD id) {
|
||||
if(!CubeItemWritable(id))return false;
|
||||
if(*GetTablePostfix())return true;
|
||||
const int installed=schema();if(installed==0)return true;if(installed<0)return false;
|
||||
auto q=query("SELECT id FROM port_economy_custody WHERE id="+std::to_string(id));
|
||||
if(!valid(q))return false;
|
||||
return q->Get()->uiNumRows==0;
|
||||
}
|
||||
|
||||
// Native character deletion must not strand escrow, pending refunds, proceeds
|
||||
// or a migrated catalogue outside the tables that legacy deletion cleans up.
|
||||
// Catalogue users need an explicit audited retirement, not an implicit reset.
|
||||
bool CClientManager::EconomyCanDelete(DWORD pid) {
|
||||
if(!CubeMemoryLoadable(0,pid))return false;
|
||||
if(!CubePlayerWritable(pid))return false;
|
||||
if(*GetTablePostfix())return true;
|
||||
const int installed=schema();if(installed==0)return true;if(installed<0)return false;
|
||||
if(m_economyFences.count(pid)||m_economyClosed.count(pid))return false;
|
||||
const std::string id=std::to_string(pid);
|
||||
auto q=query("SELECT (EXISTS(SELECT 1 FROM port_economy_pending WHERE pid="+id+"))+(EXISTS(SELECT 1 FROM port_economy_listings WHERE owner="+id+" AND state IN('OPEN','RESERVED')))+(EXISTS(SELECT 1 FROM port_economy_orders WHERE buyer="+id+" AND state='READY'))+(EXISTS(SELECT 1 FROM port_economy_credit WHERE pid="+id+" AND amount<>0))+(EXISTS(SELECT 1 FROM port_economy_gaya WHERE pid="+id+" AND generation<>"+std::to_string(PortEconomy::RetiredGeneration)+"))+(EXISTS(SELECT 1 FROM port_economy_gaya WHERE pid="+id+" AND generation="+std::to_string(PortEconomy::RetiredGeneration)+" AND EXISTS(SELECT 1 FROM quest WHERE dwPID="+id+" AND szName='gem' AND szState='points' AND lValue<>0)))");
|
||||
if(!valid(q)||q->Get()->uiNumRows!=1)return false;
|
||||
MYSQL_ROW row=mysql_fetch_row(q->Get()->pSQLResult);return row&&row[0]&&std::string(row[0])=="0";
|
||||
}
|
||||
@@ -765,9 +765,9 @@ void CGuildManager::UseSkill(DWORD GID, DWORD dwSkillVnum, DWORD dwCooltime)
|
||||
// END_OF_GUILD_SKILL_COOLTIME_BUG_FIX
|
||||
}
|
||||
|
||||
void CGuildManager::MoneyChange(DWORD dwGuild, DWORD dwGold)
|
||||
void CGuildManager::MoneyChange(DWORD dwGuild, int64_t dwGold)
|
||||
{
|
||||
sys_log(0, "GuildManager::MoneyChange %d %d", dwGuild, dwGold);
|
||||
sys_log(0, "GuildManager::MoneyChange %u %lld", dwGuild, (long long)dwGold);
|
||||
|
||||
TPacketDGGuildMoneyChange p;
|
||||
p.dwGuild = dwGuild;
|
||||
@@ -775,11 +775,11 @@ void CGuildManager::MoneyChange(DWORD dwGuild, DWORD dwGold)
|
||||
CClientManager::instance().ForwardPacket(HEADER_DG_GUILD_MONEY_CHANGE, &p, sizeof(p));
|
||||
|
||||
char buf[1024];
|
||||
snprintf(buf, sizeof(buf), "UPDATE guild%s SET gold=%u WHERE id = %u", GetTablePostfix(), dwGold, dwGuild);
|
||||
snprintf(buf, sizeof(buf), "UPDATE guild%s SET gold=%lld WHERE id = %u", GetTablePostfix(), (long long)dwGold, dwGuild);
|
||||
CDBManager::instance().AsyncQuery(buf);
|
||||
}
|
||||
|
||||
void CGuildManager::DepositMoney(DWORD dwGuild, INT iGold)
|
||||
void CGuildManager::DepositMoney(DWORD dwGuild, int64_t iGold)
|
||||
{
|
||||
if (iGold <= 0)
|
||||
return;
|
||||
@@ -793,12 +793,12 @@ void CGuildManager::DepositMoney(DWORD dwGuild, INT iGold)
|
||||
}
|
||||
|
||||
it->second.gold += iGold;
|
||||
sys_log(0, "GUILD: %u Deposit %u Total %d", dwGuild, iGold, it->second.gold);
|
||||
sys_log(0, "GUILD: %u Deposit %lld Total %lld", dwGuild, (long long)iGold, (long long)it->second.gold);
|
||||
|
||||
MoneyChange(dwGuild, it->second.gold);
|
||||
}
|
||||
|
||||
void CGuildManager::WithdrawMoney(CPeer* peer, DWORD dwGuild, INT iGold)
|
||||
void CGuildManager::WithdrawMoney(CPeer* peer, DWORD dwGuild, int64_t iGold)
|
||||
{
|
||||
itertype(m_map_kGuild) it = m_map_kGuild.find(dwGuild);
|
||||
|
||||
@@ -812,7 +812,7 @@ void CGuildManager::WithdrawMoney(CPeer* peer, DWORD dwGuild, INT iGold)
|
||||
if (it->second.gold >= iGold)
|
||||
{
|
||||
it->second.gold -= iGold;
|
||||
sys_log(0, "GUILD: %u Withdraw %d Total %d", dwGuild, iGold, it->second.gold);
|
||||
sys_log(0, "GUILD: %u Withdraw %lld Total %lld", dwGuild, (long long)iGold, (long long)it->second.gold);
|
||||
|
||||
TPacketDGGuildMoneyWithdraw p;
|
||||
p.dwGuild = dwGuild;
|
||||
@@ -823,14 +823,14 @@ void CGuildManager::WithdrawMoney(CPeer* peer, DWORD dwGuild, INT iGold)
|
||||
}
|
||||
}
|
||||
|
||||
void CGuildManager::WithdrawMoneyReply(DWORD dwGuild, BYTE bGiveSuccess, INT iGold)
|
||||
void CGuildManager::WithdrawMoneyReply(DWORD dwGuild, BYTE bGiveSuccess, int64_t iGold)
|
||||
{
|
||||
itertype(m_map_kGuild) it = m_map_kGuild.find(dwGuild);
|
||||
|
||||
if (it == m_map_kGuild.end())
|
||||
return;
|
||||
|
||||
sys_log(0, "GuildManager::WithdrawMoneyReply : guild %u success %d gold %d", dwGuild, bGiveSuccess, iGold);
|
||||
sys_log(0, "GuildManager::WithdrawMoneyReply : guild %u success %d gold %lld", dwGuild, bGiveSuccess, (long long)iGold);
|
||||
|
||||
if (!bGiveSuccess)
|
||||
it->second.gold += iGold;
|
||||
@@ -1067,13 +1067,12 @@ bool CGuildManager::ReserveWar(TPacketGuildWar * p)
|
||||
|
||||
std::unique_ptr<SQLMsg> pmsg(CDBManager::instance().DirectQuery(szQuery));
|
||||
|
||||
if (pmsg->Get()->uiAffectedRows == 0 || pmsg->Get()->uiInsertID == 0 || pmsg->Get()->uiAffectedRows == (uint32_t)-1)
|
||||
if (pmsg->Get()->uiAffectedRows == 0 || !pmsg->Get()->GetInsertID32(t.dwID) || pmsg->Get()->uiAffectedRows == UINT64_MAX)
|
||||
{
|
||||
sys_err("GuildWar: Cannot insert row");
|
||||
return false;
|
||||
}
|
||||
|
||||
t.dwID = pmsg->Get()->uiInsertID;
|
||||
|
||||
m_map_kWarReserve.insert(std::make_pair(t.dwID, new CGuildWarReserve(t)));
|
||||
|
||||
@@ -1293,7 +1292,7 @@ bool CGuildWarReserve::Bet(const char * pszLogin, DWORD dwGold, DWORD dwGuild)
|
||||
|
||||
std::unique_ptr<SQLMsg> pmsg(CDBManager::instance().DirectQuery(szQuery));
|
||||
|
||||
if (pmsg->Get()->uiAffectedRows == 0 || pmsg->Get()->uiAffectedRows == (uint32_t)-1)
|
||||
if (pmsg->Get()->uiAffectedRows == 0 || pmsg->Get()->uiAffectedRows == UINT64_MAX)
|
||||
{
|
||||
sys_log(0, "GuildWarReserve::Bet: failed. cannot insert row to guild_war_bet table");
|
||||
return false;
|
||||
|
||||
@@ -114,7 +114,7 @@ typedef struct SGuild
|
||||
int win;
|
||||
int draw;
|
||||
int loss;
|
||||
int gold;
|
||||
int64_t gold;
|
||||
int level;
|
||||
} TGuild;
|
||||
|
||||
@@ -191,12 +191,12 @@ class CGuildManager : public singleton<CGuildManager>
|
||||
|
||||
void UseSkill(DWORD dwGuild, DWORD dwSkillVnum, DWORD dwCooltime);
|
||||
|
||||
INT GetGuildGold(DWORD dwGuild);
|
||||
void DepositMoney(DWORD dwGuild, INT lGold);
|
||||
void WithdrawMoney(CPeer* peer, DWORD dwGuild, INT lGold);
|
||||
void WithdrawMoneyReply(DWORD dwGuild, BYTE bGiveSuccess, INT lGold);
|
||||
int64_t GetGuildGold(DWORD dwGuild);
|
||||
void DepositMoney(DWORD dwGuild, int64_t lGold);
|
||||
void WithdrawMoney(CPeer* peer, DWORD dwGuild, int64_t lGold);
|
||||
void WithdrawMoneyReply(DWORD dwGuild, BYTE bGiveSuccess, int64_t lGold);
|
||||
|
||||
void MoneyChange(DWORD dwGuild, DWORD dwGold);
|
||||
void MoneyChange(DWORD dwGuild, int64_t dwGold);
|
||||
|
||||
void QueryRanking();
|
||||
void ResultRanking(MYSQL_RES * pRes);
|
||||
|
||||
@@ -28,7 +28,7 @@ void ItemAwardManager::Load(SQLMsg * pMsg)
|
||||
{
|
||||
MYSQL_RES * pRes = pMsg->Get()->pSQLResult;
|
||||
|
||||
for (uint i = 0; i < pMsg->Get()->uiNumRows; ++i)
|
||||
for (uint64_t i = 0; i < pMsg->Get()->uiNumRows; ++i)
|
||||
{
|
||||
MYSQL_ROW row = mysql_fetch_row(pRes);
|
||||
int col = 0;
|
||||
|
||||
@@ -93,20 +93,54 @@ bool CItemIDRangeManager::BuildRange(DWORD dwMin, DWORD dwMax, TItemIDRangeTable
|
||||
|
||||
snprintf(szQuery, sizeof(szQuery), "SELECT MAX(id) FROM item%s WHERE id >= %u and id <= %u", GetTablePostfix(), dwMin, dwMax);
|
||||
|
||||
if(!*GetTablePostfix()) {
|
||||
// Legacy escrow remains reserved until explicit reconciliation. Closing
|
||||
// its UI must not make those original IDs available after a DB restart.
|
||||
auto* legacy=CDBManager::instance().DirectQuery("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='offline_shop_item'");
|
||||
if(!legacy || legacy->uiSQLErrno || !legacy->Get() || legacy->Get()->uiNumRows!=1 || !legacy->Get()->pSQLResult){delete legacy;return false;}
|
||||
row=mysql_fetch_row(legacy->Get()->pSQLResult);
|
||||
const bool hasLegacy=row && row[0] && !strcmp(row[0],"1");
|
||||
const bool noLegacy=row && row[0] && !strcmp(row[0],"0");
|
||||
delete legacy;if(!hasLegacy && !noLegacy)return false;
|
||||
SQLMsg* version=CDBManager::instance().DirectQuery("SELECT version FROM port_economy_version WHERE id=1");
|
||||
if(!version)return false;
|
||||
const bool absent=version->uiSQLErrno==ER_NO_SUCH_TABLE;
|
||||
const bool valid=!version->uiSQLErrno && version->Get() && version->Get()->uiNumRows==1;
|
||||
delete version;
|
||||
if(!absent && !valid)return false;
|
||||
const std::string bounds=" WHERE id BETWEEN "+std::to_string(dwMin)+" AND "+std::to_string(dwMax);
|
||||
std::string sources="SELECT id FROM item"+bounds;
|
||||
if(hasLegacy)sources+=" UNION ALL SELECT id FROM offline_shop_item"+bounds;
|
||||
if(valid)sources+=" UNION ALL SELECT id FROM port_economy_custody"+bounds+" UNION ALL SELECT id FROM port_economy_item_reservations"+bounds;
|
||||
// PORT: a durable Cube drain may hold dirty cached IDs that are not in
|
||||
// item yet. They must not be reissued while that owner awaits resync.
|
||||
auto* cube=CDBManager::instance().DirectQuery("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='port_cube_item_fences'");
|
||||
if(!cube||cube->uiSQLErrno||!cube->Get()||cube->Get()->uiNumRows!=1||!cube->Get()->pSQLResult){delete cube;return false;}
|
||||
row=mysql_fetch_row(cube->Get()->pSQLResult);
|
||||
const bool hasCube=row&&row[0]&&!strcmp(row[0],"1"),noCube=row&&row[0]&&!strcmp(row[0],"0");
|
||||
delete cube;if(!hasCube&&!noCube)return false;
|
||||
if(hasCube)sources+=" UNION ALL SELECT id FROM port_cube_item_fences"+bounds;
|
||||
const int length=snprintf(szQuery,sizeof(szQuery),"SELECT MAX(id) FROM (%s) AS allocated_ids",sources.c_str());
|
||||
if(length<0||size_t(length)>=sizeof(szQuery))return false;
|
||||
}
|
||||
pMsg = CDBManager::instance().DirectQuery(szQuery);
|
||||
if(!pMsg || pMsg->uiSQLErrno || !pMsg->Get() || pMsg->Get()->uiNumRows!=1 || !pMsg->Get()->pSQLResult){delete pMsg;return false;}
|
||||
|
||||
if (pMsg != NULL)
|
||||
{
|
||||
if (pMsg->Get()->uiNumRows > 0)
|
||||
if (pMsg->Get()->uiNumRows == 1 && pMsg->Get()->pSQLResult)
|
||||
{
|
||||
row = mysql_fetch_row(pMsg->Get()->pSQLResult);
|
||||
str_to_number(dwItemMaxID, row[0]);
|
||||
unsigned long long maximum=0;
|
||||
if(!row || (row[0] && (!str_to_number(maximum,row[0]) || maximum>UINT32_MAX))){delete pMsg;return false;}
|
||||
dwItemMaxID=static_cast<DWORD>(maximum);
|
||||
}
|
||||
delete pMsg;
|
||||
}
|
||||
|
||||
if (dwItemMaxID == 0)
|
||||
dwItemMaxID = dwMin;
|
||||
else if(dwItemMaxID>=dwMax)return false;
|
||||
else
|
||||
dwItemMaxID++;
|
||||
|
||||
@@ -126,28 +160,14 @@ bool CItemIDRangeManager::BuildRange(DWORD dwMin, DWORD dwMax, TItemIDRangeTable
|
||||
|
||||
pMsg = CDBManager::instance().DirectQuery(szQuery);
|
||||
|
||||
if (pMsg != NULL)
|
||||
{
|
||||
if (pMsg->Get()->uiNumRows > 0)
|
||||
{
|
||||
DWORD count = 0;
|
||||
row = mysql_fetch_row(pMsg->Get()->pSQLResult);
|
||||
str_to_number(count, row[0]);
|
||||
|
||||
if (count > 0)
|
||||
{
|
||||
sys_err("ItemIDRange: Build: %u ~ %u\thave a item", range.dwUsableItemIDMin, range.dwMax);
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
sys_log(0, "ItemIDRange: Build: %u ~ %u start:%u", range.dwMin, range.dwMax, range.dwUsableItemIDMin);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
delete pMsg;
|
||||
}
|
||||
if(!pMsg || pMsg->uiSQLErrno || !pMsg->Get() || pMsg->Get()->uiNumRows!=1 || !pMsg->Get()->pSQLResult){delete pMsg;return false;}
|
||||
row=mysql_fetch_row(pMsg->Get()->pSQLResult);
|
||||
unsigned long long count=0;
|
||||
const bool empty=row && row[0] && str_to_number(count,row[0]) && count==0;
|
||||
delete pMsg;
|
||||
if(!empty)return false;
|
||||
sys_log(0,"ItemIDRange: Build: %u ~ %u start:%u",range.dwMin,range.dwMax,range.dwUsableItemIDMin);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
|
||||
@@ -38,8 +38,8 @@ SRCS = Config.cpp NetBase.cpp Peer.cpp PeerBase.cpp Main.cpp Lock.cpp DBManager.
|
||||
Cache.cpp LoginData.cpp ClientManager.cpp ClientManagerPlayer.cpp ClientManagerLogin.cpp \
|
||||
ClientManagerBoot.cpp ClientManagerParty.cpp ClientManagerGuild.cpp GuildManager.cpp HB.cpp \
|
||||
PrivManager.cpp MoneyLog.cpp ItemAwardManager.cpp ClientManagerEventFlag.cpp Marriage.cpp \
|
||||
Monarch.cpp BlockCountry.cpp ItemIDRangeManager.cpp ClientManagerHorseName.cpp version.cpp \
|
||||
AuctionManager.cpp ProtoReader.cpp CsvReader.cpp Ava2ItemShop.cpp
|
||||
Monarch.cpp BlockCountry.cpp ItemIDRangeManager.cpp ClientManagerHorseName.cpp ClientManagerOfflineshop.cpp version.cpp \
|
||||
AuctionManager.cpp ProtoReader.cpp CsvReader.cpp Ava2ItemShop.cpp Economy.cpp Cube.cpp CubeRuntime.cpp CubeGold.cpp
|
||||
|
||||
OBJS = $(SRCS:%.cpp=$(OBJDIR)/%.o)
|
||||
|
||||
@@ -72,3 +72,23 @@ dep:
|
||||
makedepend -fDepend $(INCDIR) -I/usr/include/c++/3.3 -I/usr/include/c++/4.2 -p$(OBJDIR)/ $(SRCS) 2> /dev/null
|
||||
|
||||
sinclude Depend
|
||||
|
||||
# PORT: handwritten economy headers are not present in the legacy Depend file.
|
||||
$(OBJDIR)/Economy.o: ../../common/economy.h ../../common/economy_store.h ../../common/economy_mysql.h ../../common/economy_view.h
|
||||
|
||||
# ClientManager layout and DB result ownership affect every DB translation unit.
|
||||
$(OBJS): ClientManager.h DBManager.h SQLFences.h CubeRuntime.h ../../common/sql_fence_router.h ../../common/cube_batch.h ../../common/cube_recipe.h ../../common/cube_drain.h
|
||||
$(OBJDIR)/CubeRuntime.o: ../../common/cube_fence.h ../../common/cube_store.h ../../common/economy_mysql.h
|
||||
$(OBJS): ../../common/cube_handshake.h
|
||||
$(OBJS): ../../common/cube_mutation.h
|
||||
$(OBJDIR)/CubeGold.o: ../../common/cube_gold_store.h ../../common/cube_gold_intent.h ../../common/cube_store.h ../../common/economy_mysql.h
|
||||
$(OBJDIR)/CubeRuntime.o: ../../common/cube_gold_intent.h
|
||||
$(OBJDIR)/CubeRuntime.o: ../../common/cube_gold_store.h
|
||||
$(OBJS): ../../common/cube_gold_source.h
|
||||
$(OBJS): ../../common/cube_owner_types.h
|
||||
$(OBJDIR)/CubeRuntime.o: ../../common/cube_owner.h
|
||||
$(OBJDIR)/CubeRuntime.o: ../../common/cube_image_ack.h
|
||||
$(OBJDIR)/CubeRuntime.o: ../../common/cube_release.h
|
||||
$(OBJS): ../../common/cube_image.h
|
||||
$(OBJS): ../../common/cube_receipt.h
|
||||
$(OBJDIR)/CubeRuntime.o: ../../common/cube_random.h
|
||||
|
||||
@@ -44,11 +44,11 @@ namespace marriage
|
||||
unique_ptr<SQLMsg> pmsg(CDBManager::instance().DirectQuery(szQuery));
|
||||
|
||||
SQLResult * pRes = pmsg->Get();
|
||||
sys_log(0, "MarriageList(size=%lu)", pRes->uiNumRows);
|
||||
sys_log(0, "MarriageList(size=%llu)", static_cast<unsigned long long>(pRes->uiNumRows));
|
||||
|
||||
if (pRes->uiNumRows > 0)
|
||||
{
|
||||
for (uint uiRow = 0; uiRow != pRes->uiNumRows; ++uiRow)
|
||||
for (uint64_t uiRow = 0; uiRow != pRes->uiNumRows; ++uiRow)
|
||||
{
|
||||
MYSQL_ROW row = mysql_fetch_row(pRes->pSQLResult);
|
||||
|
||||
@@ -104,7 +104,7 @@ namespace marriage
|
||||
unique_ptr<SQLMsg> pmsg(CDBManager::instance().DirectQuery(szQuery));
|
||||
|
||||
SQLResult* res = pmsg->Get();
|
||||
if (res->uiAffectedRows == 0 || res->uiAffectedRows == (uint32_t)-1)
|
||||
if (res->uiAffectedRows == 0 || res->uiAffectedRows == UINT64_MAX)
|
||||
{
|
||||
sys_err("cannot insert marriage");
|
||||
return;
|
||||
@@ -144,7 +144,7 @@ namespace marriage
|
||||
unique_ptr<SQLMsg> pmsg(CDBManager::instance().DirectQuery(szQuery));
|
||||
|
||||
SQLResult* res = pmsg->Get();
|
||||
if (res->uiAffectedRows == 0 || res->uiAffectedRows == (uint32_t)-1)
|
||||
if (res->uiAffectedRows == 0 || res->uiAffectedRows == UINT64_MAX)
|
||||
{
|
||||
sys_err("cannot update marriage : PID:%u %u", dwPID1, dwPID2);
|
||||
return;
|
||||
@@ -190,7 +190,7 @@ namespace marriage
|
||||
unique_ptr<SQLMsg> pmsg(CDBManager::instance().DirectQuery(szQuery));
|
||||
|
||||
SQLResult* res = pmsg->Get();
|
||||
if (res->uiAffectedRows == 0 || res->uiAffectedRows == (uint32_t)-1)
|
||||
if (res->uiAffectedRows == 0 || res->uiAffectedRows == UINT64_MAX)
|
||||
{
|
||||
sys_err("cannot delete marriage : PID:%u %u", dwPID1, dwPID2);
|
||||
return;
|
||||
@@ -234,7 +234,7 @@ namespace marriage
|
||||
unique_ptr<SQLMsg> pmsg(CDBManager::instance().DirectQuery(szQuery));
|
||||
|
||||
SQLResult* res = pmsg->Get();
|
||||
if (res->uiAffectedRows == 0 || res->uiAffectedRows == (uint32_t)-1)
|
||||
if (res->uiAffectedRows == 0 || res->uiAffectedRows == UINT64_MAX)
|
||||
{
|
||||
sys_err("cannot change engage to marriage : PID:%u %u", dwPID1, dwPID2);
|
||||
return;
|
||||
|
||||
@@ -51,7 +51,7 @@ void CMoneyLog::Save()
|
||||
*/
|
||||
}
|
||||
|
||||
void CMoneyLog::AddLog(BYTE bType, DWORD dwVnum, int iGold)
|
||||
void CMoneyLog::AddLog(BYTE bType, DWORD dwVnum, int64_t iGold)
|
||||
{
|
||||
m_MoneyLogContainer[bType][dwVnum] += iGold;
|
||||
}
|
||||
|
||||
@@ -11,10 +11,10 @@ class CMoneyLog : public singleton<CMoneyLog>
|
||||
virtual ~CMoneyLog();
|
||||
|
||||
void Save();
|
||||
void AddLog(BYTE bType, DWORD dwVnum, int iGold);
|
||||
void AddLog(BYTE bType, DWORD dwVnum, int64_t iGold);
|
||||
|
||||
private:
|
||||
std::map<DWORD, int> m_MoneyLogContainer[MONEY_LOG_TYPE_MAX_NUM];
|
||||
std::map<DWORD, int64_t> m_MoneyLogContainer[MONEY_LOG_TYPE_MAX_NUM];
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
@@ -102,7 +102,7 @@ int get_Item_Type_Value(string inputString)
|
||||
int get_Item_SubType_Value(int type_value, string inputString)
|
||||
{
|
||||
static string arSub1[] = { "WEAPON_SWORD", "WEAPON_DAGGER", "WEAPON_BOW", "WEAPON_TWO_HANDED",
|
||||
"WEAPON_BELL", "WEAPON_FAN", "WEAPON_ARROW", "WEAPON_MOUNT_SPEAR"};
|
||||
"WEAPON_BELL", "WEAPON_FAN", "WEAPON_ARROW", "WEAPON_MOUNT_SPEAR", "WEAPON_CLAW", "WEAPON_QUIVER"};
|
||||
static string arSub2[] = { "ARMOR_BODY", "ARMOR_HEAD", "ARMOR_SHIELD", "ARMOR_WRIST", "ARMOR_FOOTS",
|
||||
"ARMOR_NECK", "ARMOR_EAR", "ARMOR_PENDANT", "ARMOR_NUM_TYPES"};
|
||||
static string arSub3[] = { "USE_POTION", "USE_TALISMAN", "USE_TUNING", "USE_MOVE", "USE_TREASURE_BOX", "USE_MONEYBAG", "USE_BAIT",
|
||||
@@ -403,7 +403,7 @@ int get_Item_ApplyType_Value(string inputString)
|
||||
"APPLY_ENERGY", "APPLY_DEF_GRADE", "APPLY_COSTUME_ATTR_BONUS", "APPLY_MAGIC_ATTBONUS_PER", "APPLY_MELEE_MAGIC_ATTBONUS_PER",
|
||||
"APPLY_RESIST_ICE", "APPLY_RESIST_EARTH", "APPLY_RESIST_DARK", "APPLY_ANTI_CRITICAL_PCT", "APPLY_ANTI_PENETRATE_PCT",
|
||||
// PORT AVA2 numbering: 92-138 not ported yet (common/length.h)
|
||||
"APPLY_RESERVED_92", "APPLY_RESERVED_93", "APPLY_RESERVED_94", "APPLY_RESERVED_95", "APPLY_RESERVED_96", "APPLY_RESERVED_97", "APPLY_RESERVED_98", "APPLY_RESERVED_99",
|
||||
"APPLY_RESERVED_92", "APPLY_RESERVED_93", "APPLY_RESERVED_94", "APPLY_RESERVED_95", "APPLY_RESERVED_96", "APPLY_RESERVED_97", "APPLY_RESIST_MAGIC_REDUCTION", "APPLY_RESIST_HUMAN",
|
||||
"APPLY_RESERVED_100", "APPLY_RESERVED_101", "APPLY_RESERVED_102", "APPLY_RESERVED_103", "APPLY_RESERVED_104", "APPLY_RESERVED_105", "APPLY_RESERVED_106", "APPLY_RESERVED_107",
|
||||
"APPLY_RESERVED_108", "APPLY_RESERVED_109", "APPLY_RESERVED_110", "APPLY_RESERVED_111", "APPLY_RESERVED_112", "APPLY_RESERVED_113", "APPLY_RESERVED_114", "APPLY_RESERVED_115",
|
||||
"APPLY_RESERVED_116", "APPLY_RESERVED_117", "APPLY_RESERVED_118", "APPLY_RESERVED_119", "APPLY_RESERVED_120", "APPLY_RESERVED_121", "APPLY_RESERVED_122", "APPLY_ENCHANT_ELECT",
|
||||
|
||||
@@ -32,7 +32,8 @@ enum QID
|
||||
QID_ITEMPRICE_SAVE, ///< 21, 아이템 가격정보 저장 쿼리
|
||||
QID_ITEMPRICE_DESTROY, ///< 22, 아이템 가격정보 삭제 쿼리
|
||||
QID_ITEMPRICE_LOAD_FOR_UPDATE, ///< 23, 가격정보 업데이트를 위한 아이템 가격정보 로드 쿼리
|
||||
QID_ITEMPRICE_LOAD, ///< 24, 아이템 가격정보 로드 쿼리
|
||||
QID_ECONOMY_FENCE = 100,
|
||||
QID_ITEMPRICE_LOAD = 24, ///< 24, 아이템 가격정보 로드 쿼리
|
||||
// END_OF_MYSHOP_PRICE_LIST
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
#include "../../common/sql_fence_router.h"
|
||||
|
||||
// Include after libsql/AsyncSQL.h. Every return-query on the PLAYER async queue
|
||||
// must register here; regular fire-and-forget AsyncQuery has no result message.
|
||||
namespace PortSQLFence {
|
||||
// Process-lifetime registry avoids static-destruction order against the DB
|
||||
// singleton. CDBManager::Clear drains ownership explicitly after SQL shutdown.
|
||||
inline Router<SQLMsg>& PlayerRouter(){static auto* router=new Router<SQLMsg>;return *router;}
|
||||
inline bool Queue(CAsyncSQL* sql,Kind kind,uint32_t logical) {
|
||||
if(!sql)return false;const auto ticket=PlayerRouter().Reserve(kind,logical);if(!ticket)return false;
|
||||
sql->ReturnQuery("SELECT 1",reinterpret_cast<void*>(uintptr_t(ticket)));return true;
|
||||
}
|
||||
inline SQLMsg* Pop(CAsyncSQL* sql,Kind kind) {
|
||||
if(sql){SQLMsg* message=nullptr;unsigned budget=1024;while(budget--&&sql->PopResult(&message))PlayerRouter().Complete(message);}
|
||||
return PlayerRouter().Pop(kind);
|
||||
}
|
||||
}
|
||||
@@ -52,9 +52,9 @@ struct FWarpToHome
|
||||
if ( lpChar->GetGMLevel() != GM_PLAYER ) return;
|
||||
}
|
||||
|
||||
int nEmpire, nMapIndex, x, y;
|
||||
const BYTE nEmpire = lpChar->GetEmpire();
|
||||
int nMapIndex, x, y;
|
||||
|
||||
nEmpire = lpChar->GetEmpire();
|
||||
nMapIndex = EMPIRE_START_MAP(nEmpire);
|
||||
x = EMPIRE_START_X(nEmpire);
|
||||
y = EMPIRE_START_Y(nEmpire);
|
||||
@@ -243,7 +243,7 @@ bool CBattleArena::Start(int nEmpire)
|
||||
m_nEmpire = nEmpire;
|
||||
|
||||
char szBuf[1024];
|
||||
snprintf(szBuf, sizeof(szBuf), LC_TEXT("%s의 성으로 몬스터들이 진군하고 있습니다."), EMPIRE_NAME(m_nEmpire));
|
||||
snprintf(szBuf, sizeof(szBuf), LC_TEXT("%s의 성으로 몬스터들이 진군하고 있습니다."), EMPIRE_NAME(static_cast<BYTE>(nEmpire)));
|
||||
BroadcastNotice(szBuf);
|
||||
BroadcastNotice(LC_TEXT("10분 뒤 성을 공격할 예정입니다."));
|
||||
|
||||
|
||||
@@ -53,7 +53,7 @@ TARGET = $(BINDIR)/game
|
||||
|
||||
CFILE = minilzo.c
|
||||
|
||||
CPPFILE = BattleArena.cpp FSM.cpp MarkConvert.cpp MarkImage.cpp MarkManager.cpp OXEvent.cpp TrafficProfiler.cpp ani.cpp\
|
||||
CPPFILE = port_cube_actor.cpp port_cube_recovery.cpp port_cube_factory.cpp port_cube_apply.cpp port_cube_publish.cpp port_cube_restore.cpp BattleArena.cpp FSM.cpp MarkConvert.cpp MarkImage.cpp MarkManager.cpp OXEvent.cpp TrafficProfiler.cpp ani.cpp\
|
||||
arena.cpp banword.cpp battle.cpp blend_item.cpp block_country.cpp buffer_manager.cpp building.cpp castle.cpp\
|
||||
char.cpp char_affect.cpp char_battle.cpp char_change_empire.cpp char_horse.cpp char_item.cpp char_manager.cpp\
|
||||
char_quickslot.cpp char_resist.cpp char_skill.cpp char_state.cpp PetSystem.cpp cmd.cpp cmd_emotion.cpp cmd_general.cpp\
|
||||
@@ -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_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 port_economy.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\
|
||||
@@ -143,3 +143,38 @@ $(OBJDIR)/questlua_item.o: port_attr_lock.h
|
||||
|
||||
$(OBJDIR)/ava2_channel.o: ava2_channel.h ava2_channel_registry.h
|
||||
$(OBJDIR)/char.o $(OBJDIR)/cmd_general.o $(OBJDIR)/input_p2p.o $(OBJDIR)/p2p.o $(OBJDIR)/input_login.o: ava2_channel.h
|
||||
|
||||
$(OBJDIR)/cmd_general.o: port_features.h port_rank_runtime.h
|
||||
$(OBJDIR)/char_battle.o $(OBJDIR)/char_skill.o: port_magic_reduction.h
|
||||
$(OBJDIR)/char_battle.o: port_quiver.h
|
||||
$(OBJDIR)/char.o: port_quiver.h port_quiver_sync.inc
|
||||
$(OBJDIR)/cube.o: port_cube_catalog.inc ../../common/cube_recipe.h cube.h
|
||||
$(OBJDIR)/port_cube_actor.o $(OBJDIR)/input_db.o: port_cube_actor.h ../../common/cube_handshake.h ../../common/cube_batch.h
|
||||
$(OBJDIR)/char.o $(OBJDIR)/char_item.o $(OBJDIR)/main.o: port_cube_actor.h
|
||||
$(OBJDIR)/item_manager.o: port_cube_flush.inc item_manager.h
|
||||
$(OBJDIR)/cube.o: ../../common/cube_batch.h
|
||||
$(OBJDIR)/port_cube_actor.o $(OBJDIR)/char.o $(OBJDIR)/item.o: ../../common/cube_mutation.h
|
||||
$(OBJDIR)/item.o: port_cube_item.inc port_cube_actor.h
|
||||
$(OBJDIR)/questpc.o $(OBJDIR)/questmanager.o: port_cube_quest.h questpc.h
|
||||
$(OBJDIR)/port_cube_actor.o: questpc.h port_switchbot.h item.h
|
||||
$(OBJDIR)/port_cube_actor.o: ../../common/cube_gold_outbox.h ../../common/cube_gold_intent.h ../../common/cube_store.h
|
||||
$(OBJDIR)/port_cube_actor.o $(OBJDIR)/input_db.o: ../../common/cube_gold_source.h
|
||||
$(OBJDIR)/port_switchbot.o $(OBJDIR)/cube.o: port_cube_actor.h
|
||||
$(CPPOBJS) $(MAINOBJ): char.h item.h questpc.h questmanager.h
|
||||
$(OBJDIR)/port_cube_recovery.o $(OBJDIR)/input_db.o $(OBJDIR)/input_login.o $(OBJDIR)/main.o: port_cube_recovery.h ../../common/cube_recovery.h ../../common/cube_owner_types.h
|
||||
$(OBJDIR)/port_cube_actor.o: ../../common/cube_owner_types.h
|
||||
$(OBJDIR)/port_cube_actor.o $(OBJDIR)/port_cube_recovery.o $(OBJDIR)/input_db.o: ../../common/cube_image.h
|
||||
$(OBJDIR)/port_cube_actor.o: ../../common/cube_craft.h ../../common/cube_receipt.h
|
||||
$(OBJDIR)/item_manager_idrange.o: port_cube_ids.h ../../common/cube_item_ids.h
|
||||
$(OBJDIR)/port_cube_factory.o $(OBJDIR)/item_manager.o: port_cube_factory.h
|
||||
$(OBJDIR)/port_cube_actor.o: port_cube_factory.h
|
||||
$(OBJDIR)/port_cube_actor.o: ../../common/cube_live_image.h
|
||||
$(OBJDIR)/port_cube_recovery.o: ../../common/cube_handshake.h
|
||||
$(OBJDIR)/port_cube_actor.o $(OBJDIR)/port_cube_publish.o $(OBJDIR)/item.o: ../../common/cube_presentation.h
|
||||
$(OBJDIR)/port_cube_actor.o $(OBJDIR)/port_cube_publish.o: port_cube_publish.h
|
||||
$(OBJDIR)/port_cube_actor.o $(OBJDIR)/port_cube_restore.o: port_cube_restore.h
|
||||
$(OBJDIR)/item.o: port_cube_lifecycle.inc event_queue.h event.h
|
||||
$(OBJDIR)/port_cube_apply.o $(OBJDIR)/port_cube_actor.o: port_cube_apply.h
|
||||
$(OBJDIR)/item_manager.o: port_cube_registry.inc
|
||||
$(OBJDIR)/port_cube_factory.o: port_cube_ids.h ../../common/economy.h
|
||||
$(OBJDIR)/port_cube_recovery.o $(OBJDIR)/input_db.o: ../../common/cube_receipt.h
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#include "MarkManager.h"
|
||||
|
||||
#include "crc32.h"
|
||||
#include <sstream>
|
||||
|
||||
CGuildMarkImage * CGuildMarkManager::__NewImage()
|
||||
{
|
||||
@@ -47,29 +48,27 @@ void CGuildMarkManager::SetMarkPathPrefix(const char * prefix)
|
||||
// 마크 인덱스 불러오기 (서버에서만 사용)
|
||||
bool CGuildMarkManager::LoadMarkIndex()
|
||||
{
|
||||
char buf[64];
|
||||
snprintf(buf, sizeof(buf), "mark/%s_index", m_pathPrefix.c_str());
|
||||
FILE * fp = fopen(buf, "r");
|
||||
|
||||
if (!fp)
|
||||
return false;
|
||||
|
||||
DWORD guildID;
|
||||
DWORD markID;
|
||||
|
||||
char line[256];
|
||||
|
||||
while (fgets(line, sizeof(line)-1, fp))
|
||||
{
|
||||
sscanf(line, "%u %u", &guildID, &markID);
|
||||
line[0] = '\0';
|
||||
AddMarkIDByGuildID(guildID, markID);
|
||||
}
|
||||
|
||||
LoadMarkImages();
|
||||
|
||||
fclose(fp);
|
||||
return true;
|
||||
char filename[64];snprintf(filename,sizeof(filename),"mark/%s_index",m_pathPrefix.c_str());
|
||||
FILE* file=fopen(filename,"r");if(!file)return false;
|
||||
std::map<DWORD,DWORD> staged;std::set<DWORD> used;char line[256];bool valid=true;
|
||||
while(true) {
|
||||
const long begin=ftell(file);if(begin<0){valid=false;break;}
|
||||
if(!fgets(line,sizeof(line),file))break;
|
||||
const long end=ftell(file);
|
||||
if(end<begin || end-begin>=static_cast<long>(sizeof(line))){valid=false;break;}
|
||||
const size_t length=static_cast<size_t>(end-begin);
|
||||
if(memchr(line,0,length) || (length==sizeof(line)-1 && line[length-1]!='\n')){valid=false;break;}
|
||||
std::istringstream fields(std::string(line,length));fields>>std::ws;if(fields.eof())continue;
|
||||
uint64_t guild=0,mark=0;std::string tail;
|
||||
if(!(fields>>guild>>mark)||fields>>tail || !guild || guild>UINT16_MAX ||
|
||||
mark>=MAX_IMAGE_COUNT*CGuildMarkImage::MARK_TOTAL_COUNT || staged.count(static_cast<DWORD>(guild)) ||
|
||||
!used.insert(static_cast<DWORD>(mark)).second){valid=false;break;}
|
||||
staged.emplace(static_cast<DWORD>(guild),static_cast<DWORD>(mark));
|
||||
}
|
||||
if(ferror(file))valid=false;fclose(file);if(!valid)return false;
|
||||
std::set<DWORD> free;
|
||||
for(DWORD id=0;id<MAX_IMAGE_COUNT*CGuildMarkImage::MARK_TOTAL_COUNT;++id)if(!used.count(id))free.insert(id);
|
||||
m_mapGID_MarkID.swap(staged);m_setFreeMarkID.swap(free);LoadMarkImages();return true;
|
||||
}
|
||||
|
||||
bool CGuildMarkManager::SaveMarkIndex()
|
||||
@@ -149,13 +148,11 @@ CGuildMarkImage * CGuildMarkManager::__GetImage(DWORD imgIdx)
|
||||
|
||||
bool CGuildMarkManager::AddMarkIDByGuildID(DWORD guildID, DWORD markID)
|
||||
{
|
||||
if (markID >= MAX_IMAGE_COUNT * CGuildMarkImage::MARK_TOTAL_COUNT)
|
||||
return false;
|
||||
|
||||
//sys_log(0, "MarkManager: guild_id=%d mark_id=%d", guildID, markID);
|
||||
m_mapGID_MarkID.insert(std::map<DWORD, DWORD>::value_type(guildID, markID));
|
||||
m_setFreeMarkID.erase(markID);
|
||||
return true;
|
||||
if(!guildID || guildID>UINT16_MAX || markID>=MAX_IMAGE_COUNT*CGuildMarkImage::MARK_TOTAL_COUNT)return false;
|
||||
const auto existing=m_mapGID_MarkID.find(guildID);
|
||||
if(existing!=m_mapGID_MarkID.end())return existing->second==markID;
|
||||
if(!m_setFreeMarkID.count(markID))return false;
|
||||
m_mapGID_MarkID.emplace(guildID,markID);m_setFreeMarkID.erase(markID);return true;
|
||||
}
|
||||
|
||||
DWORD CGuildMarkManager::GetMarkID(DWORD guildID)
|
||||
@@ -188,24 +185,24 @@ DWORD CGuildMarkManager::__AllocMarkID(DWORD guildID)
|
||||
|
||||
DWORD CGuildMarkManager::GetMarkImageCount() const
|
||||
{
|
||||
return m_mapIdx_Image.size();
|
||||
return static_cast<DWORD>(m_mapIdx_Image.size());
|
||||
}
|
||||
|
||||
DWORD CGuildMarkManager::GetMarkCount() const
|
||||
{
|
||||
return m_mapGID_MarkID.size();
|
||||
return static_cast<DWORD>(m_mapGID_MarkID.size());
|
||||
}
|
||||
|
||||
// SERVER
|
||||
void CGuildMarkManager::CopyMarkIdx(char * pcBuf) const
|
||||
bool CGuildMarkManager::CopyMarkIdx(char* buffer, size_t capacity) const
|
||||
{
|
||||
WORD * pwBuf = (WORD *) pcBuf;
|
||||
|
||||
for (std::map<DWORD, DWORD>::const_iterator it = m_mapGID_MarkID.begin(); it != m_mapGID_MarkID.end(); ++it)
|
||||
{
|
||||
*(pwBuf++) = it->first; // guild id
|
||||
*(pwBuf++) = it->second; // mark id
|
||||
}
|
||||
if(m_mapGID_MarkID.size()>capacity/(sizeof(WORD)*2) || (!buffer && !m_mapGID_MarkID.empty()))return false;
|
||||
for(const auto& entry:m_mapGID_MarkID)if(!entry.first || entry.first>UINT16_MAX || entry.second>=MAX_IMAGE_COUNT*CGuildMarkImage::MARK_TOTAL_COUNT)return false;
|
||||
for(const auto& entry:m_mapGID_MarkID) {
|
||||
const WORD guild=static_cast<WORD>(entry.first), mark=static_cast<WORD>(entry.second);
|
||||
memcpy(buffer,&guild,sizeof(guild));memcpy(buffer+sizeof(guild),&mark,sizeof(mark));buffer+=sizeof(WORD)*2;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// SERVER
|
||||
@@ -218,7 +215,7 @@ DWORD CGuildMarkManager::SaveMark(DWORD guildID, BYTE * pbMarkImage)
|
||||
if ((idMark = __AllocMarkID(guildID)) == INVALID_MARK_ID)
|
||||
{
|
||||
sys_err("CGuildMarkManager: cannot alloc mark id %u", guildID);
|
||||
return false;
|
||||
return INVALID_MARK_ID;
|
||||
}
|
||||
else
|
||||
sys_log(0, "SaveMark: mark id alloc %u", idMark);
|
||||
|
||||
@@ -45,7 +45,7 @@ class CGuildMarkManager : public singleton<CGuildMarkManager>
|
||||
DWORD GetMarkID(DWORD guildID);
|
||||
|
||||
// SERVER
|
||||
void CopyMarkIdx(char * pcBuf) const;
|
||||
bool CopyMarkIdx(char* buffer, size_t capacity) const;
|
||||
DWORD SaveMark(DWORD guildID, BYTE * pbMarkImage);
|
||||
void DeleteMark(DWORD guildID);
|
||||
void GetDiffBlocks(DWORD imgIdx, const DWORD * crcList, std::map<BYTE, const SGuildMarkBlock *> & mapDiffBlocks);
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
#include "char_manager.h"
|
||||
#include "OXEvent.h"
|
||||
#include "desc.h"
|
||||
#include <limits>
|
||||
|
||||
bool COXEventManager::Initialize()
|
||||
{
|
||||
@@ -36,7 +37,7 @@ void COXEventManager::Destroy()
|
||||
|
||||
OXEventStatus COXEventManager::GetStatus()
|
||||
{
|
||||
BYTE ret = quest::CQuestManager::instance().GetEventFlag("oxevent_status");
|
||||
const int ret = quest::CQuestManager::instance().GetEventFlag("oxevent_status");
|
||||
|
||||
switch (ret)
|
||||
{
|
||||
@@ -240,15 +241,16 @@ EVENTFUNC(oxevent_timer)
|
||||
bool COXEventManager::Quiz(unsigned char level, int timelimit)
|
||||
{
|
||||
if (m_vec_quiz.size() == 0) return false;
|
||||
if (level > m_vec_quiz.size()) level = m_vec_quiz.size() - 1;
|
||||
if (m_vec_quiz[level].size() <= 0) return false;
|
||||
const size_t selected = std::min(static_cast<size_t>(level), m_vec_quiz.size() - 1);
|
||||
const size_t count = m_vec_quiz[selected].size();
|
||||
if (!count || count > static_cast<size_t>(std::numeric_limits<int>::max())) return false;
|
||||
|
||||
if (timelimit < 0) timelimit = 30;
|
||||
|
||||
int idx = number(0, m_vec_quiz[level].size()-1);
|
||||
const int idx = number(0, static_cast<int>(count) - 1);
|
||||
|
||||
SendNoticeMap(LC_TEXT("문제 입니다."), OXEVENT_MAP_INDEX, true);
|
||||
SendNoticeMap(m_vec_quiz[level][idx].Quiz, OXEVENT_MAP_INDEX, true);
|
||||
SendNoticeMap(m_vec_quiz[selected][idx].Quiz, OXEVENT_MAP_INDEX, true);
|
||||
SendNoticeMap(LC_TEXT("맞으면 O, 틀리면 X로 이동해주세요"), OXEVENT_MAP_INDEX, true);
|
||||
|
||||
if (m_timedEvent != NULL) {
|
||||
@@ -257,14 +259,14 @@ bool COXEventManager::Quiz(unsigned char level, int timelimit)
|
||||
|
||||
OXEventInfoData* answer = AllocEventInfo<OXEventInfoData>();
|
||||
|
||||
answer->answer = m_vec_quiz[level][idx].answer;
|
||||
answer->answer = m_vec_quiz[selected][idx].answer;
|
||||
|
||||
timelimit -= 15;
|
||||
m_timedEvent = event_create(oxevent_timer, answer, PASSES_PER_SEC(timelimit));
|
||||
|
||||
SetStatus(OXEVENT_QUIZ);
|
||||
|
||||
m_vec_quiz[level].erase(m_vec_quiz[level].begin()+idx);
|
||||
m_vec_quiz[selected].erase(m_vec_quiz[selected].begin()+idx);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -327,7 +329,8 @@ bool COXEventManager::CheckAnswer(bool answer)
|
||||
|
||||
TPacketGCChat pack_chat;
|
||||
pack_chat.header = HEADER_GC_CHAT;
|
||||
pack_chat.size = sizeof(TPacketGCChat) + len;
|
||||
static_assert(sizeof(TPacketGCChat) + sizeof(chatbuf) <= UINT16_MAX, "bounded OX chat packet");
|
||||
pack_chat.size = static_cast<WORD>(sizeof(TPacketGCChat) + static_cast<size_t>(len));
|
||||
pack_chat.type = CHAT_TYPE_COMMAND;
|
||||
pack_chat.id = 0;
|
||||
|
||||
|
||||
+658
-519
File diff suppressed because it is too large
Load Diff
+72
-133
@@ -1,163 +1,102 @@
|
||||
#ifndef __HEADER_PET_SYSTEM__
|
||||
#define __HEADER_PET_SYSTEM__
|
||||
#ifndef __HEADER_PET_SYSTEM__
|
||||
#define __HEADER_PET_SYSTEM__
|
||||
|
||||
#include <unordered_map>
|
||||
#include "../../common/tables.h"
|
||||
|
||||
class CItem;
|
||||
class CHARACTER;
|
||||
|
||||
// TODO: 펫으로서의 능력치? 라던가 친밀도, 배고픔 기타등등... 수치
|
||||
struct SPetAbility
|
||||
{
|
||||
};
|
||||
|
||||
/**
|
||||
*/
|
||||
class CPetActor //: public CHARACTER
|
||||
class CPetActor
|
||||
{
|
||||
public:
|
||||
enum EPetOptions
|
||||
{
|
||||
EPetOption_Followable = 1 << 0,
|
||||
EPetOption_Mountable = 1 << 1,
|
||||
EPetOption_Summonable = 1 << 2,
|
||||
EPetOption_Combatable = 1 << 3,
|
||||
};
|
||||
|
||||
|
||||
protected:
|
||||
friend class CPetSystem;
|
||||
|
||||
CPetActor(LPCHARACTER owner, DWORD vnum, DWORD options = EPetOption_Followable | EPetOption_Summonable);
|
||||
// CPetActor(LPCHARACTER owner, DWORD vnum, const SPetAbility& petAbility, DWORD options = EPetOption_Followable | EPetOption_Summonable);
|
||||
|
||||
CPetActor(BYTE petType = 0);
|
||||
virtual ~CPetActor();
|
||||
|
||||
virtual bool Update(DWORD deltaTime);
|
||||
DWORD Summon(LPITEM summonItem, const char* petName, DWORD mobVnum);
|
||||
void Unsummon(bool isReal = true);
|
||||
|
||||
void GiveBuffSkill();
|
||||
void ClearBuffSkill();
|
||||
|
||||
BYTE GetType() const { return m_petType; }
|
||||
void SetType(const BYTE type) { m_petType = type; }
|
||||
|
||||
LPCHARACTER GetPet();
|
||||
bool IsSummoned();
|
||||
|
||||
void SetSummonItem(const DWORD pItemID) { m_dwSummonItemID = pItemID; }
|
||||
LPITEM GetSummonItem();
|
||||
|
||||
#ifdef ENABLE_NEW_PET_SYSTEM
|
||||
bool PointChange(BYTE byType, int amount, bool bBroadcast = false);
|
||||
BYTE GetMaxLevelByEvolution(BYTE evolution);
|
||||
DWORD GetNextExp();
|
||||
void IncreaseEvolve();
|
||||
bool IncreaseBonus(const BYTE bonusType, const BYTE bonusStep);
|
||||
bool IncreaseSkill(const BYTE skillIndex);
|
||||
BYTE CheckSkillIndex(LPITEM summonItem, BYTE skillIndex);
|
||||
BYTE CheckEmptyIndex(LPITEM summonItem);
|
||||
|
||||
long GetApplyValue(BYTE byIndex) const { return m_aApplies[byIndex].lValue; }
|
||||
void SetApplyValue(BYTE byIndex, long lValue) { m_aApplies[byIndex].lValue = lValue; }
|
||||
|
||||
BYTE GetSkillBookIndex(BYTE byIndex) const { return m_aSkills[byIndex].bType; }
|
||||
void SetSkillBookIndex(BYTE byIndex, BYTE byBookIndex) { m_aSkills[byIndex].bType = byBookIndex; }
|
||||
|
||||
short GetSkillApplyLevel(BYTE byIndex) const { return m_aSkills[byIndex].sLevel; }
|
||||
void SetSkillApplyLevel(BYTE byIndex, short sValue) { m_aSkills[byIndex].sLevel = sValue; }
|
||||
|
||||
long GetAge() const { return m_lAge; }
|
||||
void SetAge(long lAge) { m_lAge = lAge; }
|
||||
#endif
|
||||
|
||||
protected:
|
||||
virtual bool _UpdateFollowAI(); ///< 주인을 따라다니는 AI 처리
|
||||
virtual bool _UpdatAloneActionAI(float fMinDist, float fMaxDist); ///< 주인 근처에서 혼자 노는 AI 처리
|
||||
BYTE m_petType;
|
||||
DWORD m_dwSummonItemID;
|
||||
DWORD m_pkPetVID;
|
||||
|
||||
/// @TODO
|
||||
//virtual bool _UpdateCombatAI();
|
||||
|
||||
private:
|
||||
bool Follow(float fMinDistance = 50.f);
|
||||
|
||||
public:
|
||||
LPCHARACTER GetCharacter() const { return m_pkChar; }
|
||||
LPCHARACTER GetOwner() const { return m_pkOwner; }
|
||||
DWORD GetVID() const { return m_dwVID; }
|
||||
DWORD GetVnum() const { return m_dwVnum; }
|
||||
|
||||
bool HasOption(EPetOptions option) const { return m_dwOptions & option; }
|
||||
|
||||
void SetName(const char* petName);
|
||||
|
||||
bool Mount();
|
||||
void Unmount();
|
||||
|
||||
DWORD Summon(const char* petName, LPITEM pSummonItem, bool bSpawnFar = false);
|
||||
void Unsummon();
|
||||
|
||||
bool IsSummoned() const { return 0 != m_pkChar; }
|
||||
void SetSummonItem (LPITEM pItem);
|
||||
DWORD GetSummonItemVID () { return m_dwSummonItemVID; }
|
||||
// 버프 주는 함수와 거두는 함수.
|
||||
// 이게 좀 괴랄한게, 서버가 ㅄ라서,
|
||||
// POINT_MOV_SPEED, POINT_ATT_SPEED, POINT_CAST_SPEED는 PointChange()란 함수만 써서 변경해 봐야 소용이 없는게,
|
||||
// PointChange() 이후에 어디선가 ComputePoints()를 하면 싹다 초기화되고,
|
||||
// 더 웃긴건, ComputePoints()를 부르지 않으면 클라의 POINT는 전혀 변하지 않는다는 거다.
|
||||
// 그래서 버프를 주는 것은 ComputePoints() 내부에서 petsystem->RefreshBuff()를 부르도록 하였고,
|
||||
// 버프를 빼는 것은 ClearBuff()를 부르고, ComputePoints를 하는 것으로 한다.
|
||||
void GiveBuff();
|
||||
void ClearBuff();
|
||||
|
||||
private:
|
||||
DWORD m_dwVnum;
|
||||
DWORD m_dwVID;
|
||||
DWORD m_dwOptions;
|
||||
DWORD m_dwLastActionTime;
|
||||
DWORD m_dwSummonItemVID;
|
||||
DWORD m_dwSummonItemVnum;
|
||||
|
||||
short m_originalMoveSpeed;
|
||||
|
||||
std::string m_name;
|
||||
|
||||
LPCHARACTER m_pkChar; // Instance of pet(CHARACTER)
|
||||
LPCHARACTER m_pkOwner;
|
||||
|
||||
// SPetAbility m_petAbility; // 능력치
|
||||
#ifdef ENABLE_NEW_PET_SYSTEM
|
||||
BYTE m_byEvolution;
|
||||
long m_lDuration;
|
||||
long m_lMaxDuration;
|
||||
long m_lAge;
|
||||
TPetApply m_aApplies[PET_APPLY_MAX_NUM];
|
||||
TPetSkill m_aSkills[PET_SKILLS_MAX_NUM];
|
||||
#endif
|
||||
};
|
||||
|
||||
/**
|
||||
*/
|
||||
class CPetSystem
|
||||
{
|
||||
public:
|
||||
typedef std::unordered_map<DWORD, CPetActor*> TPetActorMap; /// <VNUM, PetActor> map. (한 캐릭터가 같은 vnum의 펫을 여러개 가질 일이 있을까..??)
|
||||
|
||||
public:
|
||||
CPetSystem(LPCHARACTER owner);
|
||||
virtual ~CPetSystem();
|
||||
|
||||
CPetActor* GetByVID(DWORD vid) const;
|
||||
CPetActor* GetByVnum(DWORD vnum) const;
|
||||
LPPET GetByVID(DWORD vid) const;
|
||||
LPPET GetByID(DWORD itemID) const;
|
||||
|
||||
bool Update(DWORD deltaTime);
|
||||
void Destroy();
|
||||
size_t CountSummoned() const;
|
||||
|
||||
size_t CountSummoned() const; ///< 현재 소환된(실체화 된 캐릭터가 있는) 펫의 개수
|
||||
LPPET Summon(DWORD mobVnum, LPITEM pSummonItem, const char* petName, BYTE petType);
|
||||
void HandlePetCostumeItem();
|
||||
|
||||
public:
|
||||
void SetUpdatePeriod(DWORD ms);
|
||||
void DeletePet(DWORD itemID);
|
||||
void DeletePet(LPPET petActor);
|
||||
void ChangeGmPetStatus();
|
||||
|
||||
CPetActor* Summon(DWORD mobVnum, LPITEM pSummonItem, const char* petName, bool bSpawnFar, DWORD options = CPetActor::EPetOption_Followable | CPetActor::EPetOption_Summonable);
|
||||
BYTE PetItemSocketMax(DWORD itemVnum);
|
||||
|
||||
void Unsummon(DWORD mobVnum, bool bDeleteFromList = false);
|
||||
void Unsummon(CPetActor* petActor, bool bDeleteFromList = false);
|
||||
|
||||
// TODO: 진짜 펫 시스템이 들어갈 때 구현. (캐릭터가 보유한 펫의 정보를 추가할 때 라던가...)
|
||||
CPetActor* AddPet(DWORD mobVnum, const char* petName, const SPetAbility& ability, DWORD options = CPetActor::EPetOption_Followable | CPetActor::EPetOption_Summonable | CPetActor::EPetOption_Combatable);
|
||||
|
||||
void DeletePet(DWORD mobVnum);
|
||||
void DeletePet(CPetActor* petActor);
|
||||
void RefreshBuff();
|
||||
#ifdef ENABLE_NEW_PET_SYSTEM
|
||||
void PointChange(BYTE byType, int amount, bool bBroadcast = false);
|
||||
void HandleNewPetItem();
|
||||
LPPET GetNewPet();
|
||||
#endif
|
||||
|
||||
private:
|
||||
TPetActorMap m_petActorMap;
|
||||
LPCHARACTER m_pkOwner; ///< 펫 시스템의 Owner
|
||||
DWORD m_dwUpdatePeriod; ///< 업데이트 주기 (ms단위)
|
||||
DWORD m_dwLastUpdateTime;
|
||||
LPEVENT m_pkPetSystemUpdateEvent;
|
||||
std::unordered_map<DWORD, LPPET> m_petActorMap;
|
||||
LPCHARACTER m_pkOwner;
|
||||
};
|
||||
|
||||
/**
|
||||
// Summon Pet
|
||||
CPetSystem* petSystem = mainChar->GetPetSystem();
|
||||
CPetActor* petActor = petSystem->Summon(~~~);
|
||||
|
||||
DWORD petVID = petActor->GetVID();
|
||||
if (0 == petActor)
|
||||
{
|
||||
ERROR_LOG(...)
|
||||
};
|
||||
|
||||
|
||||
// Unsummon Pet
|
||||
petSystem->Unsummon(petVID);
|
||||
|
||||
// Mount Pet
|
||||
petActor->Mount()..
|
||||
|
||||
|
||||
CPetActor::Update(...)
|
||||
{
|
||||
// AI : Follow, actions, etc...
|
||||
}
|
||||
|
||||
*/
|
||||
|
||||
|
||||
|
||||
#endif //__HEADER_PET_SYSTEM__
|
||||
#endif
|
||||
|
||||
@@ -18,6 +18,9 @@ class CAffect
|
||||
enum EAffectTypes
|
||||
{
|
||||
AFFECT_NONE,
|
||||
#ifdef ENABLE_OFFLINESHOP_SYSTEM
|
||||
AFFECT_DECORATION = 703,
|
||||
#endif
|
||||
AFFECT_AUTO_PICK_UP = 705,
|
||||
|
||||
AFFECT_MOV_SPEED = 200,
|
||||
|
||||
@@ -12,26 +12,38 @@
|
||||
#include <cctype>
|
||||
#include <map>
|
||||
#include <sys/time.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#include "char_manager.h"
|
||||
#include "questmanager.h"
|
||||
#include "config.h"
|
||||
#include "../../common/point_drop.h"
|
||||
#include "../../common/point_journal.h"
|
||||
|
||||
namespace {
|
||||
struct PendingPoints { Ava2ShopRequest request; unsigned handle; int attempts; time_t next; };
|
||||
std::map<std::string, PendingPoints> pendingPoints;
|
||||
LPEVENT pointRetryEvent = NULL;
|
||||
std::string s_pointLogPath = "log/point_rewards_pending.log";
|
||||
|
||||
PointJournal pointJournal;
|
||||
bool AppendDurableIntent(const Ava2ShopRequest& r){return pointJournal.Intent(r);}
|
||||
bool AppendDurableDone(const char* token,uint8_t status,uint32_t granted,int64_t balance){return pointJournal.Done(token,status,granted,balance);}
|
||||
|
||||
EVENTINFO(PointRetryInfo) {};
|
||||
EVENTFUNC(RetryPoints) {
|
||||
if(pointJournal.NeedsCompaction() && !pointJournal.Compact())sys_err("POINT_DROP: %s",pointJournal.Error().c_str());
|
||||
for(auto it=pendingPoints.begin();it!=pendingPoints.end();) {
|
||||
auto& p=it->second;
|
||||
if(get_global_time()<p.next){++it;continue;}
|
||||
if(p.attempts>=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 +56,14 @@ 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);
|
||||
if((status!=0 && status!=1 && status!=2 && status!=7) || balance<0 ||
|
||||
amount>found->second.request.count || (status!=0 && amount!=0)) {
|
||||
sys_err("POINT_DROP: malformed settlement result; keep durable token %s pending",token);
|
||||
return true;
|
||||
}
|
||||
if(!AppendDurableDone(token,status,amount,balance)){sys_err("POINT_DROP: %s",pointJournal.Error().c_str());return true;}
|
||||
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 +73,44 @@ 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() {
|
||||
std::map<std::string,Ava2ShopRequest> recovered;
|
||||
if(!pointJournal.Open(s_pointLogPath,recovered))sys_err("POINT_DROP: %s",pointJournal.Error().c_str());
|
||||
if(pointJournal.NeedsCompaction() && !pointJournal.Compact())sys_err("POINT_DROP: %s",pointJournal.Error().c_str());
|
||||
for(const auto& record:recovered){PendingPoints pending={record.second,0,1,get_global_time()+2};pendingPoints.emplace(record.first,pending);}
|
||||
if(!pendingPoints.empty()&&!pointRetryEvent)pointRetryEvent=event_create(RetryPoints,AllocEventInfo<PointRetryInfo>(),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(!pointJournal.Ready()){sys_err("POINT_DROP: issuance paused: %s",pointJournal.Error().c_str());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<unsigned long long>(boot),static_cast<unsigned long long>(++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<PointRetryInfo>(),PASSES_PER_SEC(1));
|
||||
}
|
||||
ACMD(do_ishop) {
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
#pragma once
|
||||
#include <string>
|
||||
#include <cstddef>
|
||||
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();
|
||||
|
||||
@@ -20,7 +20,7 @@ static const Ava2TicketOffer kAva2Tickets[]={
|
||||
struct Ava2ShopPrice { DWORD vnum,count; };
|
||||
struct Ava2ShopStart { TPacketGCShopStart shop; Ava2ShopPrice prices[SHOP_HOST_ITEM_MAX_NUM]; };
|
||||
#pragma pack(pop)
|
||||
static_assert(sizeof(Ava2ShopStart)==2044,"native currency shop payload");
|
||||
static_assert(sizeof(Ava2ShopStart)==2204,"native currency shop payload");
|
||||
static_assert(sizeof(Ava2ShopPrice)==8,"AVA2 item price layout");
|
||||
class CAva2TicketShop : public CShop {
|
||||
public:
|
||||
|
||||
+723
-291
File diff suppressed because it is too large
Load Diff
+348
-225
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,6 @@
|
||||
#include "stdafx.h"
|
||||
#include "port_magic_reduction.h"
|
||||
#include "PetSystem.h"
|
||||
#include "new_mob_timer.h"
|
||||
#include "utils.h"
|
||||
#include "config.h"
|
||||
@@ -44,6 +46,7 @@
|
||||
#include "port_battlepass_hooks.h"
|
||||
#include "ava2_itemshop.h"
|
||||
#include <algorithm>
|
||||
#include "port_quiver.h"
|
||||
DWORD AdjustExpByLevel(const LPCHARACTER ch, const DWORD exp)
|
||||
{
|
||||
if (PLAYER_EXP_TABLE_MAX < ch->GetLevel())
|
||||
@@ -719,9 +722,9 @@ void CHARACTER::RewardGold(LPCHARACTER pkAttacker)
|
||||
|
||||
for (int i = 0; i < iSplitCount; ++i)
|
||||
{
|
||||
if (isAutoLoot)
|
||||
if (isAutoLoot && pkAttacker->GiveGold(iGold / iSplitCount))
|
||||
{
|
||||
pkAttacker->GiveGold(iGold / iSplitCount);
|
||||
// Successfully credited; otherwise keep the reward as a ground pile.
|
||||
}
|
||||
else if ((item = ITEM_MANAGER::instance().CreateItem(1, iGold / iSplitCount)))
|
||||
{
|
||||
@@ -2546,6 +2549,12 @@ static void GiveExp(LPCHARACTER from, LPCHARACTER to, int iExp)
|
||||
|
||||
iExp = AdjustExpByLevel(to, iExp);
|
||||
|
||||
#ifdef ENABLE_NEW_PET_SYSTEM
|
||||
CPetSystem* pet = to->GetPetSystem();
|
||||
if (pet)
|
||||
pet->PointChange(POINT_PET_EXP, iExp * 5);
|
||||
#endif
|
||||
|
||||
to->PointChange(POINT_EXP, iExp, true);
|
||||
from->CreateFly(FLY_EXP, to);
|
||||
|
||||
@@ -2868,12 +2877,19 @@ int CHARACTER::GetArrowAndBow(LPITEM * ppkBow, LPITEM * ppkArrow, int iArrowCoun
|
||||
LPITEM pkArrow;
|
||||
|
||||
if (!(pkArrow = GetWear(WEAR_ARROW)) || pkArrow->GetType() != ITEM_WEAPON ||
|
||||
pkArrow->GetProto()->bSubType != WEAPON_ARROW)
|
||||
(pkArrow->GetProto()->bSubType != WEAPON_ARROW && pkArrow->GetProto()->bSubType != WEAPON_QUIVER))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
iArrowCount = MIN(iArrowCount, pkArrow->GetCount());
|
||||
if (pkArrow->GetSubType() == WEAPON_QUIVER)
|
||||
{
|
||||
if (!PortQuiverUsable(pkArrow))
|
||||
return 0;
|
||||
iArrowCount = MIN(iArrowCount, 200);
|
||||
}
|
||||
else
|
||||
iArrowCount = MIN(iArrowCount, pkArrow->GetCount());
|
||||
|
||||
*ppkBow = pkBow;
|
||||
*ppkArrow = pkArrow;
|
||||
@@ -2883,6 +2899,9 @@ int CHARACTER::GetArrowAndBow(LPITEM * ppkBow, LPITEM * ppkArrow, int iArrowCoun
|
||||
|
||||
void CHARACTER::UseArrow(LPITEM pkArrow, DWORD dwArrowCount)
|
||||
{
|
||||
if (pkArrow->GetSubType() == WEAPON_QUIVER)
|
||||
return;
|
||||
|
||||
int iCount = pkArrow->GetCount();
|
||||
DWORD dwVnum = pkArrow->GetVnum();
|
||||
iCount = iCount - MIN(iCount, dwArrowCount);
|
||||
@@ -3003,7 +3022,12 @@ class CFuncShoot
|
||||
NormalAttackAffect(m_me, pkVictim);
|
||||
|
||||
// µ¥¹ÌÁö °è»ê
|
||||
iDam = iDam * (100 - pkVictim->GetPoint(POINT_RESIST_MAGIC)) / 100;
|
||||
#ifdef ENABLE_MAGIC_REDUCTION_SYSTEM
|
||||
iDam = PortMagicDamageAfterResistance(iDam, pkVictim->GetPoint(POINT_RESIST_MAGIC),
|
||||
m_me->GetPoint(POINT_RESIST_MAGIC_REDUCTION), m_me->GetJob()==JOB_SURA);
|
||||
#else
|
||||
iDam = iDam * (100 - pkVictim->GetPoint(POINT_RESIST_MAGIC)) / 100;
|
||||
#endif
|
||||
|
||||
//sys_log(0, "%s arrow %s dam %d", m_me->GetName(), pkVictim->GetName(), iDam);
|
||||
|
||||
|
||||
@@ -107,7 +107,7 @@ int CHARACTER::ChangeEmpire(BYTE empire)
|
||||
|
||||
std::unique_ptr<SQLMsg> msg(DBManager::instance().DirectQuery(szQuery));
|
||||
|
||||
if (msg->Get()->uiAffectedRows > 0)
|
||||
if (msg->Get()->HasAffectedRows())
|
||||
{
|
||||
// 5. 제국 변경 이력을 추가한다.
|
||||
SetChangeEmpireCount();
|
||||
|
||||
+1658
-627
File diff suppressed because it is too large
Load Diff
@@ -359,7 +359,11 @@ LPCHARACTER CHARACTER_MANAGER::SpawnMob(DWORD dwVnum, long lMapIndex, long x, lo
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (!(pkMob->m_table.bType == CHAR_TYPE_NPC || pkMob->m_table.bType == CHAR_TYPE_WARP || pkMob->m_table.bType == CHAR_TYPE_GOTO) || mining::IsVeinOfOre (dwVnum))
|
||||
if (!(pkMob->m_table.bType == CHAR_TYPE_NPC || pkMob->m_table.bType == CHAR_TYPE_WARP || pkMob->m_table.bType == CHAR_TYPE_GOTO
|
||||
#ifdef ENABLE_NEW_PET_SYSTEM
|
||||
|| pkMob->m_table.bType == CHAR_TYPE_PET
|
||||
#endif
|
||||
) || mining::IsVeinOfOre (dwVnum))
|
||||
{
|
||||
LPSECTREE tree = SECTREE_MANAGER::instance().Get(lMapIndex, x, y);
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "stdafx.h"
|
||||
#include "port_magic_reduction.h"
|
||||
#include <sstream>
|
||||
|
||||
#include "utils.h"
|
||||
@@ -442,7 +443,15 @@ bool CHARACTER::LearnSkillByBook(DWORD dwSkillVnum, BYTE bProb)
|
||||
// bType이 0이면 처음부터 책으로 수련 가능
|
||||
if (pkSk->dwType != 0)
|
||||
{
|
||||
if (GetSkillMasterType(dwSkillVnum) != SKILL_MASTER)
|
||||
if (GetSkillMasterType(dwSkillVnum) != SKILL_MASTER && (dwSkillVnum >= SKILL_FINISH && dwSkillVnum <= SKILL_CHEONUN))
|
||||
{
|
||||
if (GetSkillMasterType(dwSkillVnum) > SKILL_MASTER)
|
||||
{
|
||||
ChatPacket(CHAT_TYPE_INFO, LC_TEXT("이 스킬은 책으로 더이상 수련할 수 없습니다."));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else if (GetSkillMasterType(dwSkillVnum) != SKILL_MASTER)
|
||||
{
|
||||
if (GetSkillMasterType(dwSkillVnum) > SKILL_MASTER)
|
||||
ChatPacket(CHAT_TYPE_INFO, LC_TEXT("이 스킬은 책으로 더이상 수련할 수 없습니다."));
|
||||
@@ -751,7 +760,7 @@ void CHARACTER::SkillLevelUp(DWORD dwVnum, BYTE bMethod)
|
||||
else if (bMethod == SKILL_UP_BY_BOOK)
|
||||
{
|
||||
if (pkSk->dwType != 0) // 직업에 속하지 않았거나 포인트로 올릴수 없는 스킬은 처음부터 책으로 배울 수 있다.
|
||||
if (GetSkillMasterType(pkSk->dwVnum) != SKILL_MASTER)
|
||||
if (GetSkillMasterType(pkSk->dwVnum) != SKILL_MASTER && (pkSk->dwVnum < SKILL_FINISH || pkSk->dwVnum > SKILL_CHEONUN))
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1320,7 +1329,12 @@ struct FuncSplashDamage
|
||||
// 으아아아악
|
||||
// 예전에 적용안했던 버그가 있어서 방어력 계산을 다시하면 유저가 난리남
|
||||
//iDam -= pkChrVictim->GetPoint(POINT_MAGIC_DEF_GRADE);
|
||||
iDam = iDam * (100 - pkChrVictim->GetPoint(POINT_RESIST_MAGIC)) / 100;
|
||||
#ifdef ENABLE_MAGIC_REDUCTION_SYSTEM
|
||||
iDam = PortMagicDamageAfterResistance(iDam, pkChrVictim->GetPoint(POINT_RESIST_MAGIC),
|
||||
m_pkChr->GetPoint(POINT_RESIST_MAGIC_REDUCTION), m_pkChr->GetJob()==JOB_SURA);
|
||||
#else
|
||||
iDam = iDam * (100 - pkChrVictim->GetPoint(POINT_RESIST_MAGIC)) / 100;
|
||||
#endif
|
||||
break;
|
||||
|
||||
default:
|
||||
|
||||
@@ -1254,3 +1254,62 @@ void CHARACTER::StateHorse()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
#ifdef ENABLE_NEW_PET_SYSTEM
|
||||
void CHARACTER::StatePet()
|
||||
{
|
||||
float START_FOLLOW_DISTANCE = 200.0f;
|
||||
float START_RUN_DISTANCE = 300.0f;
|
||||
float RESPAWN_DISTANCE = 3000.0f;
|
||||
int APPROACH = 200;
|
||||
|
||||
bool bDoMoveAlone = true;
|
||||
bool bRun = true;
|
||||
|
||||
m_dwStateDuration = 0;
|
||||
LPCHARACTER victim = GetOwner();
|
||||
|
||||
if (!victim)
|
||||
return;
|
||||
|
||||
m_pkMobInst->m_posLastAttacked = GetXYZ();
|
||||
|
||||
float fDist = DISTANCE_APPROX(GetX() - victim->GetX(), GetY() - victim->GetY());
|
||||
|
||||
if (fDist >= RESPAWN_DISTANCE)
|
||||
{
|
||||
float fOwnerRot = victim->GetRotation() * 3.141592f / 180.f;
|
||||
float fx = -APPROACH * cos(fOwnerRot);
|
||||
float fy = -APPROACH * sin(fOwnerRot);
|
||||
Show(victim->GetMapIndex(), victim->GetX() + fx, victim->GetY() + fy);
|
||||
}
|
||||
else if (fDist >= START_FOLLOW_DISTANCE)
|
||||
{
|
||||
if (fDist > START_RUN_DISTANCE)
|
||||
SetNowWalking(!bRun);
|
||||
|
||||
Follow(victim, APPROACH);
|
||||
m_dwStateDuration = 1;
|
||||
}
|
||||
else if (bDoMoveAlone && (get_dword_time() > m_dwLastAttackTime))
|
||||
{
|
||||
m_dwLastAttackTime = get_dword_time() + number(5000, 12000);
|
||||
SetRotation(number(0, 359));
|
||||
|
||||
float fx, fy;
|
||||
float fDist = number(200, 400);
|
||||
|
||||
GetDeltaByDegree(GetRotation(), fDist, &fx, &fy);
|
||||
|
||||
if (!(SECTREE_MANAGER::instance().IsMovablePosition(GetMapIndex(), GetX() + (int) fx, GetY() + (int) fy)
|
||||
&& SECTREE_MANAGER::instance().IsMovablePosition(GetMapIndex(), GetX() + (int) fx/2, GetY() + (int) fy/2)))
|
||||
return;
|
||||
|
||||
SetNowWalking(true);
|
||||
|
||||
if (Goto(GetX() + (int) fx, GetY() + (int) fy))
|
||||
SendMovePacket(FUNC_WAIT, 0, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
+55
-30
@@ -24,6 +24,17 @@ ACMD(do_port_vip);
|
||||
ACMD(do_port_bp);
|
||||
ACMD(do_battle_pass);
|
||||
ACMD(do_event_manager);
|
||||
|
||||
#ifdef ENABLE_NEW_PET_SYSTEM
|
||||
ACMD(do_pet_egg);
|
||||
ACMD(do_pet_evolve);
|
||||
ACMD(do_pet_add_slot);
|
||||
ACMD(do_change_name);
|
||||
#endif
|
||||
#ifdef UNLOCK_INVENTORY_WORLDARD
|
||||
ACMD(do_reload_inventory);
|
||||
ACMD(do_unlock_inventory);
|
||||
#endif
|
||||
ACMD(do_user_horse_ride);
|
||||
ACMD(do_user_horse_back);
|
||||
ACMD(do_user_horse_feed);
|
||||
@@ -186,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);
|
||||
@@ -206,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);
|
||||
@@ -215,7 +226,7 @@ ACMD(do_monarch_tax);
|
||||
ACMD(do_monarch_mob);
|
||||
ACMD(do_monarch_notice);
|
||||
|
||||
//군주 관리 기능
|
||||
//군주 관리 기능
|
||||
ACMD(do_rmcandidacy);
|
||||
ACMD(do_setmonarch);
|
||||
ACMD(do_rmmonarch);
|
||||
@@ -223,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);
|
||||
@@ -254,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);
|
||||
@@ -274,30 +285,32 @@ 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_mt_economy);
|
||||
|
||||
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 },
|
||||
@@ -323,7 +336,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 },
|
||||
@@ -421,8 +434,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 },
|
||||
@@ -505,6 +518,10 @@ struct command_info cmd_info[] =
|
||||
{ "add_attr", do_add_attr, 0, POS_DEAD, GM_IMPLEMENTOR },
|
||||
{ "add_socket", do_add_socket, 0, POS_DEAD, GM_IMPLEMENTOR },
|
||||
|
||||
#ifdef UNLOCK_INVENTORY_WORLDARD
|
||||
{ "reload_inventory", do_reload_inventory, 0, POS_DEAD, GM_PLAYER },
|
||||
{ "unlock_inventory", do_unlock_inventory, 0, POS_DEAD, GM_PLAYER },
|
||||
#endif
|
||||
{ "user_horse_ride", do_user_horse_ride, 0, POS_FISHING, GM_PLAYER },
|
||||
{ "user_horse_back", do_user_horse_back, 0, POS_FISHING, GM_PLAYER },
|
||||
{ "user_horse_feed", do_user_horse_feed, 0, POS_FISHING, GM_PLAYER },
|
||||
@@ -562,7 +579,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 },
|
||||
@@ -572,7 +589,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 },
|
||||
@@ -630,7 +647,15 @@ struct command_info cmd_info[] =
|
||||
{ "event_manager", do_event_manager, 0, POS_DEAD, GM_PLAYER },
|
||||
{ "battle_pass", do_battle_pass, 0, POS_DEAD, GM_PLAYER },
|
||||
{ "mt_bp", do_port_bp, 0, POS_DEAD, GM_PLAYER },
|
||||
{ "\n", NULL, 0, POS_DEAD, GM_IMPLEMENTOR } /* 반드시 이 것이 마지막이어야 한다. */
|
||||
#ifdef ENABLE_NEW_PET_SYSTEM
|
||||
{ "pet_egg", do_pet_egg, 0, POS_DEAD, GM_PLAYER },
|
||||
{ "pet_evolve", do_pet_evolve, 0, POS_DEAD, GM_PLAYER },
|
||||
{ "pet_add_slot", do_pet_add_slot, 0, POS_DEAD, GM_PLAYER },
|
||||
{ "change_name", do_change_name, 0, POS_DEAD, GM_PLAYER },
|
||||
#endif
|
||||
{ "mt_economy", do_mt_economy, 0, POS_DEAD, GM_PLAYER },
|
||||
{ "gem", do_gem, 0, POS_DEAD, GM_PLAYER },
|
||||
{ "\n", NULL, 0, POS_DEAD, GM_IMPLEMENTOR } /* 반드시 이 것이 마지막이어야 한다. */
|
||||
};
|
||||
|
||||
void interpreter_set_privilege(const char *cmd, int lvl)
|
||||
@@ -653,7 +678,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)
|
||||
@@ -688,7 +713,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;
|
||||
@@ -705,7 +730,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))
|
||||
@@ -717,24 +742,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:
|
||||
@@ -747,17 +772,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));
|
||||
|
||||
+505
-272
File diff suppressed because it is too large
Load Diff
@@ -1449,12 +1449,13 @@ ACMD(do_set)
|
||||
{
|
||||
case 0: // gold
|
||||
{
|
||||
int gold = 0;
|
||||
str_to_number(gold, arg3);
|
||||
long long gold = 0;
|
||||
if(!str_to_number(gold,arg3))break;
|
||||
if(gold < -tch->GetGold() || gold > GOLD_MAX_64-tch->GetGold())break;
|
||||
DBManager::instance().SendMoneyLog(MONEY_LOG_MISC, 3, gold);
|
||||
int before_gold = tch->GetGold();
|
||||
int64_t before_gold = tch->GetGold();
|
||||
tch->PointChange(POINT_GOLD, gold, true);
|
||||
int after_gold = tch->GetGold();
|
||||
int64_t after_gold = tch->GetGold();
|
||||
if (0 == after_gold && 0 != before_gold)
|
||||
{
|
||||
LogManager::instance().CharLog(tch, gold, "ZERO_GOLD", "GM");
|
||||
@@ -2980,7 +2981,7 @@ ACMD(do_build)
|
||||
// 건설 재료 소모하기 (테섭에서는 GM도 소모)
|
||||
{
|
||||
// 건설 비용 소모
|
||||
ch->PointChange(POINT_GOLD, -t->dwPrice);
|
||||
ch->PointChange(POINT_GOLD, -static_cast<int64_t>(t->dwPrice));
|
||||
|
||||
// 아이템 자재 사용하기
|
||||
{
|
||||
|
||||
@@ -791,6 +791,8 @@ const int aiWeaponSocketQty[WEAPON_NUM_TYPES] =
|
||||
3, // WEAPON_FAN,
|
||||
0, // WEAPON_ARROW,
|
||||
0, // WEAPON_MOUNT_SPEAR
|
||||
3, // WEAPON_CLAW (numeric reservation)
|
||||
0, // WEAPON_QUIVER
|
||||
};
|
||||
|
||||
const int aiArmorSocketQty[ARMOR_NUM_TYPES] =
|
||||
@@ -921,8 +923,8 @@ const TApplyInfo aApplyInfo[MAX_APPLY_NUM] =
|
||||
{ POINT_NONE }, // 95
|
||||
{ POINT_NONE }, // 96
|
||||
{ POINT_NONE }, // 97
|
||||
{ POINT_NONE }, // 98
|
||||
{ POINT_NONE }, // 99
|
||||
{ POINT_RESIST_MAGIC_REDUCTION }, // APPLY_RESIST_MAGIC_REDUCTION 98
|
||||
{ POINT_RESIST_HUMAN }, // APPLY_RESIST_HUMAN 99
|
||||
{ POINT_NONE }, // 100
|
||||
{ POINT_NONE }, // 101
|
||||
{ POINT_NONE }, // 102
|
||||
@@ -1331,6 +1333,8 @@ TValueName c_aApplyTypeNames[] =
|
||||
{ "MAGIC_ATTBONUS_PER", APPLY_MAGIC_ATTBONUS_PER },
|
||||
{ "MELEE_MAGIC_ATTBONUS_PER", APPLY_MELEE_MAGIC_ATTBONUS_PER },
|
||||
|
||||
{ "RESIST_HUMAN", APPLY_RESIST_HUMAN },
|
||||
{ "RESIST_MAGIC_REDUCTION", APPLY_RESIST_MAGIC_REDUCTION },
|
||||
{ "ATTBONUS_STONE", APPLY_ATTBONUS_STONE },
|
||||
{ "ATTBONUS_BOSS", APPLY_ATTBONUS_BOSS },
|
||||
{ "ENCHANT_ELEC", APPLY_ENCHANT_ELEC },
|
||||
@@ -1353,3 +1357,47 @@ long FN_get_apply_type(const char *apply_type_string)
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
#ifdef ENABLE_NEW_PET_SYSTEM
|
||||
std::map<BYTE, std::vector<std::pair<DWORD, WORD>>> petEvolutionItems{
|
||||
{0, {{55004, 10}, {30058, 10}, {30073, 10}, {30041, 10}, {30017, 10}, {30074, 5}, {30088, 5} }},
|
||||
{1, {{55005, 10}, {27994, 2}, {30035, 10}, {30089, 10}, {30031, 10}, {30011, 10}, {30080, 5} }},
|
||||
{2, {{55006, 10}, {27992, 2}, {27993, 2}, {30083, 10}, {30086, 10}, {30077, 10}, {30550, 5} }}
|
||||
};
|
||||
|
||||
std::map<BYTE, std::vector<std::pair<BYTE, long>>> petSkillBonus
|
||||
{
|
||||
{1, {{APPLY_ATTBONUS_STONE,10} }},
|
||||
{2, {{APPLY_ATTBONUS_MONSTER,10} }},
|
||||
{3, {{APPLY_ATTBONUS_BOSS,10} }},
|
||||
{4, {{APPLY_STR,10} }},
|
||||
{5, {{APPLY_INT,10} }},
|
||||
{6, {{APPLY_DEX,10} }},
|
||||
{7, {{APPLY_CON,10} }},
|
||||
{8, {{APPLY_ATTBONUS_ANIMAL,15} }},
|
||||
{9, {{APPLY_ATTBONUS_ORC,15} }},
|
||||
{10, {{APPLY_ATTBONUS_MILGYO,15} }},
|
||||
{11, {{APPLY_ATTBONUS_UNDEAD,15} }},
|
||||
{12, {{APPLY_ATTBONUS_DEVIL,15} }},
|
||||
{13, {{APPLY_EXP_DOUBLE_BONUS,10} }},
|
||||
{14, {{APPLY_ITEM_DROP_BONUS,10} }},
|
||||
{15, {{APPLY_GOLD_DOUBLE_BONUS,20} }},
|
||||
{16, {{APPLY_ATTBONUS_HUMAN,5} }},
|
||||
{17, {{APPLY_RESIST_HUMAN,5} }},
|
||||
{18, {{APPLY_SKILL_DAMAGE_BONUS,5} }},
|
||||
{19, {{APPLY_SKILL_DEFEND_BONUS,5} }},
|
||||
{20, {{APPLY_NORMAL_HIT_DAMAGE_BONUS,10} }},
|
||||
{21, {{APPLY_NORMAL_HIT_DEFEND_BONUS,10} }},
|
||||
{22, {{APPLY_ANTI_CRITICAL_PCT,10} }},
|
||||
{23, {{APPLY_ANTI_PENETRATE_PCT,10} }},
|
||||
{24, {{APPLY_CAST_SPEED,15} }},
|
||||
{25, {{APPLY_BLOCK,10} }},
|
||||
{26, {{APPLY_POISON_REDUCE,10} }},
|
||||
{27, {{APPLY_RESIST_ICE,10} }},
|
||||
{28, {{APPLY_RESIST_EARTH,10} }},
|
||||
{29, {{APPLY_RESIST_DARK,10} }},
|
||||
};
|
||||
|
||||
BYTE petEvolutionLimits[PET_MAX_EVOLUTION_CONST + 1]{ 40, 75, 100, 120 };
|
||||
#endif
|
||||
|
||||
@@ -186,5 +186,12 @@ long FN_get_apply_type(const char *apply_type_string);
|
||||
// END_OF_ACCESSORY_REFINE
|
||||
|
||||
long FN_get_apply_type(const char *apply_type_string);
|
||||
|
||||
#ifdef ENABLE_NEW_PET_SYSTEM
|
||||
extern std::map<BYTE, std::vector<std::pair<DWORD, WORD>>> petEvolutionItems;
|
||||
extern std::map<BYTE, std::vector<std::pair<BYTE, long>>> petSkillBonus;
|
||||
extern BYTE petEvolutionLimits[PET_MAX_EVOLUTION_CONST + 1];
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#define _cube_cpp_
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "port_cube_actor.h"
|
||||
#include "constants.h"
|
||||
#include "utils.h"
|
||||
#include "log.h"
|
||||
@@ -397,8 +398,11 @@ bool Cube_load (const char *file)
|
||||
continue;
|
||||
|
||||
// set value1, value2
|
||||
if ((v = strtok(NULL, delim)))
|
||||
const char* port_value = NULL;
|
||||
if ((v = strtok(NULL, delim))) {
|
||||
port_value = v;
|
||||
str_to_number(value1, v);
|
||||
}
|
||||
|
||||
if ((v = strtok(NULL, delim)))
|
||||
str_to_number(value2, v);
|
||||
@@ -429,6 +433,14 @@ bool Cube_load (const char *file)
|
||||
{
|
||||
cube_data->percent = value1;
|
||||
}
|
||||
else TOKEN("category")
|
||||
{
|
||||
cube_data->portCategory = port_value ? port_value : "";
|
||||
}
|
||||
else TOKEN("copy")
|
||||
{
|
||||
cube_data->portCopy = value1 > 0;
|
||||
}
|
||||
else TOKEN("gold")
|
||||
{
|
||||
// 제조에 필요한 금액
|
||||
@@ -509,6 +521,7 @@ static bool FN_update_cube_status(LPCHARACTER ch)
|
||||
// return new item
|
||||
bool Cube_make (LPCHARACTER ch)
|
||||
{
|
||||
if(PortCubeActorHeld(ch))return false;
|
||||
// 주어진 아이템을 필요로하는 조합을 찾는다. (큐브데이타로 칭함)
|
||||
// 큐브 데이타가 있다면 아이템의 재료를 체크한다.
|
||||
// 새로운 아이템을 만든다.
|
||||
@@ -554,7 +567,7 @@ bool Cube_make (LPCHARACTER ch)
|
||||
|
||||
// 제조시 필요한 골드 차감
|
||||
if (0 < cube_proto->gold)
|
||||
ch->PointChange(POINT_GOLD, -(cube_proto->gold), false);
|
||||
ch->PointChange(POINT_GOLD, -static_cast<int64_t>(cube_proto->gold), false);
|
||||
|
||||
percent_number = number(1,100);
|
||||
if ( percent_number<=cube_proto->percent)
|
||||
@@ -980,3 +993,6 @@ void Cube_request_material_info(LPCHARACTER ch, int requestStartIndex, int reque
|
||||
|
||||
|
||||
}
|
||||
|
||||
// PORT: current loaded Cube catalogue and read-only batch preflight.
|
||||
#include "port_cube_catalog.inc"
|
||||
|
||||
@@ -31,6 +31,8 @@ struct CUBE_DATA
|
||||
std::vector<CUBE_VALUE> reward;
|
||||
int percent;
|
||||
unsigned int gold; // 제조시 필요한 금액
|
||||
std::string portCategory = "WORLDARD";
|
||||
bool portCopy = false;
|
||||
|
||||
CUBE_DATA();
|
||||
|
||||
|
||||
@@ -1255,7 +1255,7 @@ void DBManager::AnalyzeReturnQuery(SQLMsg * pMsg)
|
||||
m_map_dbstring.clear();
|
||||
m_vec_GreetMessage.clear();
|
||||
|
||||
for (uint i = 0; i < pMsg->Get()->uiNumRows; ++i)
|
||||
for (uint64_t i = 0; i < pMsg->Get()->uiNumRows; ++i)
|
||||
{
|
||||
MYSQL_ROW row = mysql_fetch_row(pMsg->Get()->pSQLResult);
|
||||
//ch->SetSafeboxSize(SAFEBOX_PAGE_SIZE * atoi(row[0]));
|
||||
@@ -1285,7 +1285,7 @@ void DBManager::AnalyzeReturnQuery(SQLMsg * pMsg)
|
||||
|
||||
if (ch)
|
||||
{
|
||||
if (pMsg->Get()->uiAffectedRows == 0 || pMsg->Get()->uiAffectedRows == (uint32_t)-1)
|
||||
if (!pMsg->Get()->HasAffectedRows() || !pMsg->Get()->uiInsertID || pMsg->Get()->uiInsertID > INT32_MAX)
|
||||
{
|
||||
sys_log(0, "GIVE LOTTO FAIL TO pid %u", ch->GetPlayerID());
|
||||
}
|
||||
@@ -1298,7 +1298,7 @@ void DBManager::AnalyzeReturnQuery(SQLMsg * pMsg)
|
||||
sys_log(0, "GIVE LOTTO SUCCESS TO %s (pid %u)", ch->GetName(), qi->dwIdent);
|
||||
//ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("¾ÆÀÌÅÛ È¹µæ: %s"), pkItem->GetName());
|
||||
|
||||
pkItem->SetSocket(0, pMsg->Get()->uiInsertID);
|
||||
pkItem->SetSocket(0, static_cast<int32_t>(pMsg->Get()->uiInsertID));
|
||||
pkItem->SetSocket(1, pdw[2]);
|
||||
}
|
||||
else
|
||||
@@ -1440,7 +1440,7 @@ void DBManager::AnalyzeReturnQuery(SQLMsg * pMsg)
|
||||
{
|
||||
TPacketCGLogin3 * pinfo = (TPacketCGLogin3 *) qi->pvData ;
|
||||
|
||||
if( pMsg->Get()->uiAffectedRows == 0 || pMsg->Get()->uiAffectedRows == (uint32_t)-1 )
|
||||
if( pMsg->Get()->uiAffectedRows == 0 || pMsg->Get()->uiAffectedRows == UINT64_MAX )
|
||||
{
|
||||
LPDESC d = DESC_MANAGER::instance().FindByLoginKey(qi->dwIdent) ;
|
||||
sys_log(0, "[AUTH_BRAZIL] NOID") ;
|
||||
@@ -1471,7 +1471,7 @@ void DBManager::AnalyzeReturnQuery(SQLMsg * pMsg)
|
||||
{
|
||||
TPacketCGLogin3 * pinfo = (TPacketCGLogin3 *) qi->pvData ;
|
||||
|
||||
if( pMsg->Get()->uiAffectedRows == 0 || pMsg->Get()->uiAffectedRows == (uint32_t)-1 )
|
||||
if( pMsg->Get()->uiAffectedRows == 0 || pMsg->Get()->uiAffectedRows == UINT64_MAX )
|
||||
{
|
||||
LPDESC d = DESC_MANAGER::instance().FindByLoginKey(qi->dwIdent) ;
|
||||
sys_log(0, "[AUTH_JAPAN] NOID") ;
|
||||
@@ -1526,7 +1526,7 @@ const std::vector<std::string>& DBManager::GetGreetMessage()
|
||||
return m_vec_GreetMessage;
|
||||
}
|
||||
|
||||
void DBManager::SendMoneyLog(BYTE type, DWORD vnum, int gold)
|
||||
void DBManager::SendMoneyLog(BYTE type, DWORD vnum, int64_t gold)
|
||||
{
|
||||
if (!gold)
|
||||
return;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#ifndef __INC_METIN_II_DB_MANAGER_H__
|
||||
#define __INC_METIN_II_DB_MANAGER_H__
|
||||
|
||||
#include "../../common/length.h"
|
||||
#include "../../libsql/AsyncSQL.h"
|
||||
#include "any_function.h"
|
||||
|
||||
@@ -95,7 +96,7 @@ class DBManager : public singleton<DBManager>
|
||||
void Process();
|
||||
void AnalyzeReturnQuery(SQLMsg * pmsg);
|
||||
|
||||
void SendMoneyLog(BYTE type, DWORD vnum, int gold);
|
||||
void SendMoneyLog(BYTE type, DWORD vnum, int64_t gold);
|
||||
|
||||
void LoginPrepare(BYTE bBillType, DWORD dwBillID, long lRemainSecs, LPDESC d, DWORD * pdwClientKey, int * paiPremiumTimes = NULL);
|
||||
void SendAuthLogin(LPDESC d);
|
||||
|
||||
@@ -539,7 +539,9 @@ void DESC_MANAGER::SendClientPackageCryptKey( LPDESC desc )
|
||||
|
||||
if( packet.KeyStreamLen > 0 )
|
||||
{
|
||||
desc->Packet( packet.GetStreamData(), packet.GetStreamSize() );
|
||||
const BYTE* stream = packet.GetStreamData();
|
||||
if (stream) desc->Packet(stream, static_cast<int>(packet.GetStreamSize()));
|
||||
else sys_err("invalid client package stream length");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -559,7 +561,9 @@ void DESC_MANAGER::SendClientPackageSDBToLoadMap( LPDESC desc, const char* pMapN
|
||||
|
||||
if( packet.iStreamLen > 0 )
|
||||
{
|
||||
desc->Packet( packet.GetStreamData(), packet.GetStreamSize());
|
||||
const BYTE* stream = packet.GetStreamData();
|
||||
if (stream) desc->Packet(stream, static_cast<int>(packet.GetStreamSize()));
|
||||
else sys_err("invalid client package stream length");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user