diff --git a/src/client/Audio/Audio.cpp b/src/client/Audio/Audio.cpp index 6120161..568b3f2 100644 --- a/src/client/Audio/Audio.cpp +++ b/src/client/Audio/Audio.cpp @@ -53,8 +53,11 @@ namespace jrc const context = new AudioContextCtor(); const bgmGain = context.createGain(); const sfxGain = context.createGain(); - bgmGain.connect(context.destination); - sfxGain.connect(context.destination); + // (music and sounds meet in one node before the speakers: the page's live stream listens there) + const master = context.createGain(); + master.connect(context.destination); + bgmGain.connect(master); + sfxGain.connect(master); const state = { context, @@ -126,6 +129,8 @@ namespace jrc Module.MapleAudio = { unlock, + context, + master, close() { if (state.currentMusic) { @@ -349,6 +354,17 @@ namespace jrc #endif } + void Sound::play_item_use(int32_t itemid) + { + std::string strid = std::to_string(itemid); + strid.insert(0, strid.size() < 8 ? 8 - strid.size() : 0, '0'); + nl::node src = nl::nx::sound["Item.img"][strid]["Use"]; + if (src) + { + Sound(src).play(); + } + } + void Sound::play(size_t id) { if (!samples.count(id)) @@ -376,6 +392,11 @@ namespace jrc if (data) { size_t id = ad.id(); + // (made once: a hit or use sound built again each time is the same clip) + if (samples.count(id)) + { + return id; + } #ifndef MS_PLATFORM_WASM samples[id] = BASS_SampleLoad( @@ -497,3 +518,28 @@ namespace jrc #endif } } + +#ifdef MS_PLATFORM_WASM +// (a check from the page's console: plays Sound.nx's sound at "Img.img/a/b/..." and says which clip it made, 0 none) +extern "C" EMSCRIPTEN_KEEPALIVE int dordo_play_sound(const char* path) +{ + std::string rest = path ? path : ""; + nl::node at = nl::nx::sound; + size_t from = 0; + while (from <= rest.size()) + { + size_t slash = rest.find('/', from); + std::string part = rest.substr(from, slash == std::string::npos ? std::string::npos : slash - from); + if (!part.empty()) + at = at[part]; + if (slash == std::string::npos) + break; + from = slash + 1; + } + if (!at) + return -1; + jrc::Sound sound(at); + sound.play(); + return at.data_type() == nl::node::type::audio ? 1 : -2; +} +#endif diff --git a/src/client/Audio/Audio.h b/src/client/Audio/Audio.h index 12d2500..672ce77 100644 --- a/src/client/Audio/Audio.h +++ b/src/client/Audio/Audio.h @@ -56,6 +56,9 @@ namespace jrc void play() const; + // The sound an item makes when used (Sound.nx Item.img//Use: potions and the like), if any. + static void play_item_use(int32_t itemid); + static Error init(); static void close(); static bool set_sfxvolume(uint8_t volume); diff --git a/src/client/CMakeLists.txt b/src/client/CMakeLists.txt index b4da4db..917915d 100644 --- a/src/client/CMakeLists.txt +++ b/src/client/CMakeLists.txt @@ -41,6 +41,8 @@ if(EMSCRIPTEN) "--embed-file=${CMAKE_CURRENT_SOURCE_DIR}/fonts/Arial/Arial-Bold.ttf@fonts/Arial/Arial-Bold.ttf" --pre-js ${CMAKE_CURRENT_SOURCE_DIR}/LazyFS/lazyfs.js -sASSERTIONS=1 + # (function names kept in the build, so a crash in a fren's browser says where it happened) + --profiling-funcs ) if(DEBUG_SYMBOLS) diff --git a/src/client/Character/Char.cpp b/src/client/Character/Char.cpp index 5b3cb3e..1158c89 100644 --- a/src/client/Character/Char.cpp +++ b/src/client/Character/Char.cpp @@ -1,4 +1,5 @@ #include "Char.h" +#include #include #include @@ -25,6 +26,11 @@ namespace jrc effects.drawbelow(absp, alpha); + if (chair_item && state == SIT) + { + chair_art.draw(DrawArgument(absp, flip), alpha); + } + Color color; if (invincible) { @@ -72,6 +78,19 @@ namespace jrc effects.drawabove(absp, alpha); + if (state == DIED) + { + // (dropping from well above for the first ~1 s, speeding up as it goes, then where it lands) + constexpr double FALL_MS = 960.0, FALL_FROM = 320.0; + double p = std::min(1.0, dead_ms / FALL_MS); + int16_t above = static_cast(std::lround(FALL_FROM * (1.0 - p * p))); + Point at = absp - Point(0, above); + if (tomb_landed) + tomb_land.draw(DrawArgument(at), alpha); + else + tomb_fall.draw(DrawArgument(at), alpha); + } + for (auto& number : damagenumbers) { number.draw(viewx, viewy, alpha); @@ -85,6 +104,25 @@ namespace jrc }); effects.update(); chatballoon.update(); + + if (chair_item) + { + chair_art.update(); + } + + if (state == DIED) + { + dead_ms += Constants::TIMESTEP; + if (!tomb_landed) + { + if (tomb_fall.update()) + tomb_landed = true; + } + else + { + tomb_land.update(); + } + } invincible.update(); ironbody.update(); @@ -300,8 +338,30 @@ namespace jrc look.set_direction(f); } + void Char::set_chair(int32_t itemid) + { + chair_item = itemid > 0 ? itemid : 0; + if (chair_item) + { + // Item.nx Install/0301.img/03010000/effect (the Relaxer: one picture, behind the sitter) + std::string strid = "0" + std::to_string(chair_item); + chair_art = Animation(nl::nx::item["Install"][strid.substr(0, 4) + ".img"][strid]["effect"]); + } + else + { + chair_art = Animation(); + } + } + void Char::set_state(State st) { + if (st == DIED && state != DIED) + { + tomb_fall = Animation(nl::nx::effect["Tomb.img"]["fall"]); + tomb_land = Animation(nl::nx::effect["Tomb.img"]["land"]); + tomb_landed = false; + dead_ms = 0; + } state = st; Stance::Id stance = Stance::by_state(state); diff --git a/src/client/Character/Char.h b/src/client/Character/Char.h index 4f5d717..5d91d23 100644 --- a/src/client/Character/Char.h +++ b/src/client/Character/Char.h @@ -153,6 +153,22 @@ namespace jrc bool attacking; bool flip; + // (dead: the tombstone falling onto where the character was, then sitting there; seen by everyone, whoever + // died; dead_ms counts from the moment of death) + Animation tomb_fall; + Animation tomb_land; + bool tomb_landed = false; + int32_t dead_ms = 0; + + // (a chair from the Set-up tab under it while it sits: the item, 0 for none, and its art) + int32_t chair_item = 0; + Animation chair_art; + public: + /// Sit on (or with 0, get off) a chair item: its art is drawn behind the character while it sits. + void set_chair(int32_t itemid); + int32_t get_chair() const { return chair_item; } + protected: + private: Text namelabel; ChatBalloon chatballoon; diff --git a/src/client/Character/Look/CharLook.cpp b/src/client/Character/Look/CharLook.cpp index 7bc293f..0608613 100644 --- a/src/client/Character/Look/CharLook.cpp +++ b/src/client/Character/Look/CharLook.cpp @@ -74,6 +74,27 @@ namespace jrc Point faceshift = drawinfo.getfacepos(interstance, interframe); DrawArgument faceargs = args + DrawArgument{ faceshift, false, Point{} }; + if (interstance == Stance::DEAD) + { + // Dead: the ghost (the body's own "dead" picture), floating up over where the tombstone lands, with its + // head on, crying. The head, face and hair have no "dead" pictures, so they're the standing ones, moved + // from a standing body's neck (-4, -32) to the ghost's (1, -28), and a little see-through like it. + DrawArgument ghost = args + DrawArgument(Point(0, -44)); + body->draw(interstance, Body::BODY, interframe, ghost); + + constexpr Stance::Id HEADSTANCE = Stance::STAND1; + DrawArgument headargs = ghost + DrawArgument(Point(5, 4), 0.85f); + Point headface = drawinfo.getfacepos(HEADSTANCE, 0); + DrawArgument crying = headargs + DrawArgument{ headface, false, Point{} }; + hair->draw(HEADSTANCE, Hair::BELOWBODY, 0, headargs); + hair->draw(HEADSTANCE, Hair::DEFAULT, 0, headargs); + body->draw(HEADSTANCE, Body::HEAD, 0, headargs); + hair->draw(HEADSTANCE, Hair::SHADE, 0, headargs); + face->draw(Expression::CRY, 0, crying); + hair->draw(HEADSTANCE, Hair::OVERHEAD, 0, headargs); + return; + } + if (Stance::is_climbing(interstance)) { body->draw(interstance, Body::BODY, interframe, args); diff --git a/src/client/Character/Player.cpp b/src/client/Character/Player.cpp index 6e48b06..79f309d 100644 --- a/src/client/Character/Player.cpp +++ b/src/client/Character/Player.cpp @@ -18,6 +18,7 @@ #include "Player.h" #include "PlayerStates.h" +#include "../Audio/Audio.h" #include "../Constants.h" #include "../Data/EquipData.h" #include "../Data/WeaponData.h" @@ -27,6 +28,11 @@ #include "../Net/Packets/GameplayPackets.h" #include "../Net/Packets/InventoryPackets.h" +#include "nlnx/nx.hpp" + +#include +#include + namespace jrc { const PlayerNullState nullstate; @@ -102,6 +108,12 @@ namespace jrc return; } + // (one jump a press: Jump held down, or the keyboard's own repeat of it, does nothing more until it's let go) + if (action == KeyAction::JUMP && down && is_key_down(KeyAction::JUMP)) + { + return; + } + const PlayerState* pst = get_state(state); if (pst) { @@ -199,6 +211,12 @@ namespace jrc { case InventoryType::USE: UseItemPacket(slot, itemid).dispatch(); + Sound::play_item_use(itemid); + break; + case InventoryType::SETUP: + // (a chair on a hotkey) + if (itemid / 10000 == 301) + sit_chair(itemid); break; default: return; @@ -219,11 +237,23 @@ namespace jrc Char::draw(viewx, viewy, alpha); } + void Player::set_death_notice(std::function notice) + { + death_notice = std::move(notice); + } + int8_t Player::update(const Physics& physics) { if (state == DIED) { Char::update(physics, 1.0f); + + if (death_notice && dead_ms >= 2000) + { + auto notice = std::move(death_notice); + death_notice = nullptr; + notice(); + } } else { @@ -258,6 +288,52 @@ namespace jrc return get_layer(); } + void Player::remember_key(KeyAction::Id action, bool down) + { + keysdown[action] = down; + } + + void Player::spirit_fly(double hspeed, double vspeed, Range walls, Range borders) + { + phobj.type = PhysicsObject::FIXATED; + phobj.onground = false; + phobj.hspeed = hspeed; + phobj.vspeed = vspeed; + phobj.move(); + if (phobj.crnt_x() < walls.first()) phobj.limitx(walls.first()); + if (phobj.crnt_x() > walls.second()) phobj.limitx(walls.second()); + if (phobj.crnt_y() < borders.first()) phobj.limity(borders.first()); + if (phobj.crnt_y() > borders.second()) phobj.limity(borders.second()); + if (hspeed > 0.05) set_direction(true); + else if (hspeed < -0.05) set_direction(false); + + uint8_t stancebyte = flip ? state : state + 1; + Movement newmove(phobj, stancebyte); + if (lastmove.hasmoved(newmove)) + { + MovePlayerPacket(newmove).dispatch(); + lastmove = newmove; + } + } + + void Player::spirit_follow(Point position) + { + phobj.type = PhysicsObject::FIXATED; + phobj.hspeed = 0.0; + phobj.vspeed = 0.0; + phobj.move(); + phobj.set_x(position.x()); + phobj.set_y(position.y()); + + uint8_t stancebyte = flip ? state : state + 1; + Movement newmove(phobj, stancebyte); + if (lastmove.hasmoved(newmove)) + { + MovePlayerPacket(newmove).dispatch(); + lastmove = newmove; + } + } + int8_t Player::get_integer_attackspeed() const { int32_t weapon_id = look.get_equips().get_weapon(); @@ -281,8 +357,25 @@ namespace jrc } } + void Player::sit_chair(int32_t itemid) + { + if (state == DIED || is_sitting() || is_climbing() || attacking || !phobj.onground) + return; + UseChairPacket(itemid).dispatch(); + set_chair(itemid); + Char::set_state(Char::SIT); + nullstate.update_state(*this); + } + void Player::set_state(State st) { + // (off the chair: the server and everyone else are told; the art goes) + if (chair_item && st != Char::SIT) + { + CancelChairPacket(-1).dispatch(); + set_chair(0); + } + if (!attacking) { Char::set_state(st); @@ -469,6 +562,10 @@ namespace jrc phobj.vacc = 0.0; set_state(DIED); + + // the tombstone's sound (the tombstone itself: Char, on entering DIED) + static const Sound tombstone(nl::nx::sound["Game.img"]["Tombstone"]); + tombstone.play(); } void Player::revive() @@ -478,6 +575,7 @@ namespace jrc return; } + death_notice = nullptr; phobj.type = PhysicsObject::NORMAL; phobj.clear_flags(); nullstate.update_state(*this); @@ -537,6 +635,7 @@ namespace jrc if (level > oldlevel) { show_effect_id(CharEffect::LEVELUP); + Sound(Sound::LEVELUP).play(); } stats.set_stat(Maplestat::LEVEL, level); } @@ -571,8 +670,34 @@ namespace jrc } } + bool Player::just_latched() const + { + int64_t now = std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count(); + return now - latched_at < 300; + } + void Player::set_ladder(Optional ldr) { + // Just let go of a rope (jumped off it, mostly): it can't catch us again for a moment. Otherwise holding + // Up + a side + Jump grabs it again the very next frame and jumps off again, over and over (and the jump + // sound with it). Other ropes still catch, so hopping rope to rope works. + int64_t now = std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count(); + if (ldr && ldr.get() == left_ladder && now - left_ladder_at < 500) + { + return; + } + if (ladder && !ldr) + { + left_ladder = ladder.get(); + left_ladder_at = now; + } + if (ldr && !ladder) + { + latched_at = now; + } + ladder = ldr; if (ladder) diff --git a/src/client/Character/Player.h b/src/client/Character/Player.h index 1290fba..9615298 100644 --- a/src/client/Character/Player.h +++ b/src/client/Character/Player.h @@ -17,6 +17,8 @@ ////////////////////////////////////////////////////////////////////////////// #pragma once #include "Char.h" + +#include #include "CharStats.h" #include "SkillBook.h" #include "QuestLog.h" @@ -96,6 +98,10 @@ namespace jrc MobAttackResult damage(const MobAttack& attack); /// Enter the local dead state until the server respawns the player. void die(); + /// Sit on a chair from the Set-up tab (standing on the ground, not busy); getting up tells the server. + void sit_chair(int32_t itemid); + /// What to do 2 s after dying (the "you have died" dialog): time to see the tombstone land and the ghost. + void set_death_notice(std::function notice); /// Leave the local dead state after a successful revive or respawn. void revive(); /// Return whether the player is currently dead locally. @@ -149,6 +155,21 @@ namespace jrc void set_seat(Optional seat); /// Change players xpos to the ladder x and change stance to Char::LADDER or Char::ROPE. void set_ladder(Optional ladder); + /// Whether the player caught a rope or ladder in the last 0.3 s (too soon to jump off it again). + bool just_latched() const; + + /// Where the player is drawn this frame (screen position, interpolated between steps). + Point drawn_at(double viewx, double viewy, float alpha) const + { + return phobj.get_absolute(viewx, viewy, alpha); + } + /// Remember a key as held or not without acting on it (a monster spirit's arrows). + void remember_key(KeyAction::Id action, bool down); + /// Monster spirit (Gameplay/Spirit): drift by this much this step, through anything, kept inside the map, + /// and tell the server where we are. + void spirit_fly(double hspeed, double vspeed, Range walls, Range borders); + /// Monster spirit holding a monster: be where it is (the camera and the server follow). + void spirit_follow(Point position); /// Obtain a reference to the player's stats. CharStats& get_stats(); @@ -170,6 +191,9 @@ namespace jrc Monsterbook& get_monsterbook(); private: + // (dead: the dialog waits a moment, so the tombstone (Char) can be seen landing) + std::function death_notice; + CharStats stats; bool female; Inventory inventory; @@ -191,6 +215,9 @@ namespace jrc Randomizer randomizer; Optional ladder; + const Ladder* left_ladder = nullptr; + int64_t left_ladder_at = 0; + int64_t latched_at = 0; bool underwater; bool gm_hidden = false; }; diff --git a/src/client/Character/PlayerStates.cpp b/src/client/Character/PlayerStates.cpp index f2c3be3..8b0a23f 100644 --- a/src/client/Character/PlayerStates.cpp +++ b/src/client/Character/PlayerStates.cpp @@ -386,7 +386,8 @@ namespace jrc player.set_state(Char::STAND); break; case KeyAction::UP: - player.set_state(Char::SWIM); + // (Up from lying down swims only in water: on land it put the character into swimming on dry ground) + player.set_state(player.is_underwater() ? Char::SWIM : Char::STAND); break; default: break; @@ -488,6 +489,12 @@ namespace jrc switch (ka) { case KeyAction::JUMP: + // (held Jump is sent every step: catching a rope with it still down would hop straight off again, + // so a rope just caught holds on for 0.3 s first) + if (player.just_latched()) + { + break; + } if (player.is_key_down(KeyAction::LEFT)) { play_jumpsound(); diff --git a/src/client/Configuration.cpp b/src/client/Configuration.cpp index 7f29b14..c678b70 100644 --- a/src/client/Configuration.cpp +++ b/src/client/Configuration.cpp @@ -17,6 +17,11 @@ ////////////////////////////////////////////////////////////////////////////// #include "Configuration.h" +#ifdef MS_PLATFORM_WASM +#include +#include +#endif + #include namespace jrc @@ -43,6 +48,7 @@ namespace jrc settings.emplace(); settings.emplace(); settings.emplace(); + settings.emplace(); settings.emplace(); settings.emplace(); settings.emplace(); @@ -82,6 +88,33 @@ namespace jrc } // Replace default values with loaded values. +#ifdef MS_PLATFORM_WASM + // The settings file lives in the page's memory and is gone on reload: windows' places, the minimap's mode + // and the volumes are kept in the browser instead (only those: not where to connect, which the page says) + char* stored = static_cast(EM_ASM_PTR({ + var text = ""; + try { text = localStorage.getItem("dordoSettings") || ""; } catch (e) {} + return stringToNewUTF8(text); + })); + if (stored) + { + std::string text = stored; + free(stored); + size_t from = 0; + while (from < text.size()) + { + size_t end = text.find('\n', from); + std::string line = text.substr(from, end == std::string::npos ? std::string::npos : end - from); + size_t split = line.find('='); + if (split != std::string::npos && split + 2 < line.size() && kept_in_browser(line.substr(0, split - 1))) + rawsettings[line.substr(0, split - 1)] = line.substr(split + 2); + if (end == std::string::npos) + break; + from = end + 1; + } + } +#endif + for (auto& setting : settings) { auto rsiter = rawsettings.find(setting.second->name); @@ -90,8 +123,22 @@ namespace jrc } } + bool Configuration::kept_in_browser(const std::string& name) + { + return name.rfind("Pos", 0) == 0 || name.rfind("MiniMap", 0) == 0 || name == "BGMVolume" || name == "SFXVolume"; + } + void Configuration::save() const { +#ifdef MS_PLATFORM_WASM + std::string kept; + for (auto& setting : settings) + { + if (kept_in_browser(setting.second->name)) + kept += setting.second->to_string() + "\n"; + } + EM_ASM({ try { localStorage.setItem("dordoSettings", UTF8ToString($0)); } catch (e) {} }, kept.c_str()); +#endif // Open the settings file. std::ofstream config(FILENAME); if (config.is_open()) diff --git a/src/client/Configuration.h b/src/client/Configuration.h index 71dff98..f104c6d 100644 --- a/src/client/Configuration.h +++ b/src/client/Configuration.h @@ -41,6 +41,8 @@ namespace jrc void load(); // Save the current settings. void save() const; + // (in a browser: the settings kept between visits) + static bool kept_in_browser(const std::string& name); // Base class for an entry in the settings file. class Entry @@ -280,6 +282,12 @@ namespace jrc PosQUEST() : PointEntry("PosQUEST", "(200,100)") {} }; + // Dordo Story's stream window (unset: the top left, under the minimap) + struct PosSTREAM : public Configuration::PointEntry + { + PosSTREAM() : PointEntry("PosSTREAM", "(-1,-1)") {} + }; + struct PosQUESTHELPER : public Configuration::PointEntry { // Unset positions use the screen's right edge on first opening. @@ -303,7 +311,7 @@ namespace jrc struct MiniMapType : public Configuration::ByteEntry { - MiniMapType() : ByteEntry("MiniMapType", "2") {} + MiniMapType() : ByteEntry("MiniMapType", "0") {} // (0: rolled up, 1: normal, 2: big) }; struct MiniMapSimpleMode : public Configuration::BoolEntry diff --git a/src/client/Data/ItemData.cpp b/src/client/Data/ItemData.cpp index 9a96570..c9764d7 100644 --- a/src/client/Data/ItemData.cpp +++ b/src/client/Data/ItemData.cpp @@ -82,7 +82,7 @@ namespace jrc } } - std::string ItemData::get_eqcategory(int32_t id) const + std::string ItemData::get_eqcategory(int32_t id) { constexpr char const* categorynames[15] = { diff --git a/src/client/Data/ItemData.h b/src/client/Data/ItemData.h index ae0a300..d2091bf 100644 --- a/src/client/Data/ItemData.h +++ b/src/client/Data/ItemData.h @@ -27,6 +27,8 @@ namespace jrc class ItemData : public Cache { public: + // The Character.nx folder an equip id lives in ("Cap", "Weapon"…), or "" for anything else + static std::string get_eqcategory(int32_t); // Returns wether the item was loaded correctly. bool is_valid() const; // Returns wether the item was loaded correctly. @@ -51,7 +53,7 @@ namespace jrc // Creates an item from the game's Item.nx with the specified id. ItemData(int32_t itemid); - std::string get_eqcategory(int32_t) const; + BoolPair icons; int32_t itemid; diff --git a/src/client/Data/QuestData.cpp b/src/client/Data/QuestData.cpp index e7461d9..f861a35 100644 --- a/src/client/Data/QuestData.cpp +++ b/src/client/Data/QuestData.cpp @@ -174,6 +174,21 @@ namespace jrc } } + // Dordo Story's changes to what quest NPCs say (the server's Say.img XML has the same): Pio asks for ten of each + // part (1008: "ten of each", #b10#k beside each) + void QuestData::dordo_say(int32_t qid, std::vector& lines) + { + if (qid != 1008) + return; + for (auto& line : lines) + { + for (size_t at; (at = line.find("Just collect one of each")) != std::string::npos; ) + line.replace(at, 24, "Just collect ten of each"); + for (size_t at; (at = line.find("#b1#k")) != std::string::npos; ) + line.replace(at, 5, "#b10#k"); + } + } + QuestData::QuestData(int32_t quest_id) : id(quest_id) { std::string strid = std::to_string(id); @@ -202,6 +217,9 @@ namespace jrc start_npc = start["npc"]; end_npc = complete["npc"]; + // (no NPC named to finish it: it's handed in where it was given, as in the original; Pio's recycled goods) + if (end_npc <= 0) + end_npc = start_npc; start_scripted = !start["startscript"].get_string().empty(); end_scripted = !complete["endscript"].get_string().empty(); requirements[0] = parse_requirements(start); @@ -225,6 +243,25 @@ namespace jrc reward.job = entry["job"] ? static_cast(entry["job"].get_integer()) : 0; item_rewards.push_back(reward); } + + // Dordo Story's own changes to quests (the server's Quest.wz XML has the same): Pio's recycled goods + // (1008) asks for ten of each part, not one + if (id == 1008) + { + for (auto& item : requirements[1].items) + item.count = 10; + for (auto& reward : item_rewards) + if (reward.count < 0) + reward.count = -10; + for (auto& text : descriptions) + { + for (size_t at; (at = text.find("/ #r1#k")) != std::string::npos; ) + text.replace(at, 7, "/ #r10#k"); + } + // (and Pio says so) + for (auto& lines : dialogs) + dordo_say(id, lines); + } } bool QuestData::is_valid() const @@ -314,7 +351,9 @@ namespace jrc std::vector QuestData::get_dialog_branch(bool start, const std::string& branch) const { - return parse_dialog_lines(nl::nx::quest["Say.img"][std::to_string(id)][start ? "0" : "1"].resolve(branch)); + std::vector lines = parse_dialog_lines(nl::nx::quest["Say.img"][std::to_string(id)][start ? "0" : "1"].resolve(branch)); + dordo_say(id, lines); + return lines; } std::map QuestData::get_quiz_questions(bool start) const diff --git a/src/client/Data/QuestData.h b/src/client/Data/QuestData.h index 83436e4..c5d5783 100644 --- a/src/client/Data/QuestData.h +++ b/src/client/Data/QuestData.h @@ -170,6 +170,7 @@ namespace jrc bool start_scripted; bool end_scripted; std::array, 2> dialogs; + static void dordo_say(int32_t qid, std::vector& lines); std::vector item_rewards; }; } diff --git a/src/client/Gameplay/Combat/Attack.h b/src/client/Gameplay/Combat/Attack.h index 7f66583..67bbf11 100644 --- a/src/client/Gameplay/Combat/Attack.h +++ b/src/client/Gameplay/Combat/Attack.h @@ -20,6 +20,7 @@ #include #include +#include #include @@ -64,6 +65,29 @@ namespace jrc Rectangle range; float hrange = 1.0f; bool toleft = false; + + // The area the attack covers on the map: range is relative to origin and faces right; flipped when the + // attacker faces left (hrange stretches the near edge) + Rectangle get_world_range() const + { + int16_t near = static_cast(range.l() * hrange); + if (toleft) + { + return { + static_cast(origin.x() + near), + static_cast(origin.x() + range.r()), + static_cast(origin.y() + range.t()), + static_cast(origin.y() + range.b()) + }; + } + + return { + static_cast(origin.x() - range.r()), + static_cast(origin.x() - near), + static_cast(origin.y() + range.t()), + static_cast(origin.y() + range.b()) + }; + } }; @@ -146,5 +170,7 @@ namespace jrc uint16_t level; bool secondweapon; bool flip; + // a plain attack's spark on whoever it hits (Character.nx Afterimage/hit.img/), "" for none + std::string regularhit = ""; }; } diff --git a/src/client/Gameplay/Combat/Combat.cpp b/src/client/Gameplay/Combat/Combat.cpp index 86bb420..aa97cf6 100644 --- a/src/client/Gameplay/Combat/Combat.cpp +++ b/src/client/Gameplay/Combat/Combat.cpp @@ -19,6 +19,7 @@ #include "../../Character/SkillId.h" #include "../../Data/SkillData.h" +#include "../../Data/WeaponData.h" #include "../../IO/KeyAction.h" #include "../../IO/Messages.h" #include "../../Net/Packets/AttackAndSkillPackets.h" @@ -43,10 +44,11 @@ namespace jrc Combat::Combat(Player& in_player, MapChars& in_chars, MapMobs& in_mobs, - Physics& in_physics) : + MapReactors& in_reactors, Physics& in_physics) : player(in_player), chars(in_chars), mobs(in_mobs), + reactors(in_reactors), physics(in_physics), attackresults([&](const AttackResult& attack) { apply_attack(attack); @@ -144,6 +146,8 @@ namespace jrc AttackResult result = mobs.send_attack(attack); result.attacker = player.get_oid(); + // (boxes and other hittable reactors in the swing get hit too) + reactors.send_attack(attack); extract_effects(player, move, result); apply_use_movement(move); @@ -382,6 +386,27 @@ namespace jrc } } + // The spark a plain attack leaves on a monster, as the original picks it: by the weapon's kind of afterimage, + // slashing (swords, axes, spears) or blunt (maces, knuckles, bare hands), and by the swing: the second of a + // combo ("...2") and the finishers ("...F") have their own; ranged weapons have none (their bullets hit). + std::string Combat::regular_hit_name(const Char& user) + { + int32_t weapon_id = user.get_look().get_equips().get_weapon(); + std::string ai = weapon_id > 0 ? WeaponData::get(weapon_id).get_afterimage() : "barehands"; + std::string kind; + if (ai.rfind("sword", 0) == 0 || ai == "axe" || ai == "poleArm" || ai == "spear") + kind = "sword"; + else if (ai == "mace" || ai == "knuckle" || ai == "barehands") + kind = "mace"; + else + return ""; + const std::string& stance = Stance::names[user.get_look().get_stance()]; + char last = stance.empty() ? '1' : stance.back(); + std::string name = kind + (last == 'F' ? "F" : last == '2' ? "2" : "1"); + // (not every kind has every swing: mace2 doesn't exist, say) + return nl::nx::character["Afterimage"]["hit.img"][name] ? name : kind + "1"; + } + void Combat::extract_effects(const Char& user, const SpecialMove& move, const AttackResult& result) { AttackUser attackuser = { @@ -390,6 +415,10 @@ namespace jrc user.is_twohanded(), !result.toleft }; + if (move.get_id() == 0) + { + attackuser.regularhit = regular_hit_name(user); + } if (result.bullet) { auto bullet_delay = [&](size_t index) { diff --git a/src/client/Gameplay/Combat/Combat.h b/src/client/Gameplay/Combat/Combat.h index 39d4fb0..a9e8354 100644 --- a/src/client/Gameplay/Combat/Combat.h +++ b/src/client/Gameplay/Combat/Combat.h @@ -22,6 +22,7 @@ #include "../MapleMap/MapChars.h" #include "../MapleMap/MapMobs.h" +#include "../MapleMap/MapReactors.h" #include "../Physics/Physics.h" #include "../../Character/Player.h" @@ -33,7 +34,7 @@ namespace jrc { public: Combat(Player& player, MapChars& chars, MapMobs& mobs, - Physics& physics); + MapReactors& reactors, Physics& physics); // Draw bullets, damage numbers etc. void draw(double viewx, double viewy, float alpha) const; @@ -53,6 +54,8 @@ namespace jrc void show_player_buff(int32_t skillid); private: + static std::string regular_hit_name(const Char& user); + struct DamageEffect { AttackUser user; @@ -90,6 +93,7 @@ namespace jrc Player& player; MapChars& chars; MapMobs& mobs; + MapReactors& reactors; Physics& physics; std::unordered_map skills; diff --git a/src/client/Gameplay/Combat/RegularAttack.cpp b/src/client/Gameplay/Combat/RegularAttack.cpp index 4113cc8..7ff1822 100644 --- a/src/client/Gameplay/Combat/RegularAttack.cpp +++ b/src/client/Gameplay/Combat/RegularAttack.cpp @@ -17,6 +17,12 @@ ////////////////////////////////////////////////////////////////////////////// #include "RegularAttack.h" +#include "../MapleMap/Mob.h" + +#include "nlnx/nx.hpp" + +#include + namespace jrc { void RegularAttack::apply_useeffects(Char&) const {} @@ -39,7 +45,17 @@ namespace jrc } } - void RegularAttack::apply_hiteffects(const AttackUser&, Mob&) const {} + void RegularAttack::apply_hiteffects(const AttackUser& user, Mob& target) const + { + if (user.regularhit.empty()) + return; + // (made once per kind of spark) + static std::map sparks; + auto iter = sparks.find(user.regularhit); + if (iter == sparks.end()) + iter = sparks.emplace(user.regularhit, Animation(nl::nx::character["Afterimage"]["hit.img"][user.regularhit])).first; + target.show_effect(iter->second, 0, 0, user.flip); + } Animation RegularAttack::get_bullet(const Char& user, int32_t bulletid) const { diff --git a/src/client/Gameplay/MapleMap/Drop.cpp b/src/client/Gameplay/MapleMap/Drop.cpp index eeb55ac..1fd8382 100644 --- a/src/client/Gameplay/MapleMap/Drop.cpp +++ b/src/client/Gameplay/MapleMap/Drop.cpp @@ -17,8 +17,20 @@ ////////////////////////////////////////////////////////////////////////////// #include "Drop.h" +#include + namespace jrc { + namespace + { + // The pop and fall, slowed to the original's pace: up about 80 px, in the air about 0.85 s when it lands + // level with where it started, turning about one and a half times a second (per 8 ms step). Upstream used + // the player's gravity and a 5 px/step launch: half the time in the air and four turns a second. + constexpr double DROP_LAUNCH = 3.2; + constexpr double DROP_GRAVITY = 0.064; + constexpr float DROP_SPIN = 0.075f; + } + Drop::Drop(int32_t id, int32_t own, Point start, Point dst, int8_t type, int8_t mode, bool pldrp) : MapObject(id) { @@ -37,11 +49,17 @@ namespace jrc { case 0: case 1: + { state = DROPPED; basey = static_cast(dest.y() - 4); - phobj.vspeed = -5.0f; - phobj.hspeed = static_cast(dest.x() - start.x()) / 48; + phobj.vspeed = -DROP_LAUNCH; + phobj.set_flag(PhysicsObject::NOGRAVITY); // (its own gentler gravity, in update) + // sideways at the pace that puts it on its spot just as it comes down there + double fall = basey - phobj.crnt_y(); + double steps = (DROP_LAUNCH + std::sqrt(std::max(0.0, DROP_LAUNCH * DROP_LAUNCH + 2.0 * DROP_GRAVITY * fall))) / DROP_GRAVITY; + phobj.hspeed = static_cast(dest.x() - start.x()) / std::max(1.0, steps); break; + } case 2: state = FLOATING; basey = phobj.crnt_y(); @@ -56,6 +74,10 @@ namespace jrc int8_t Drop::update(const Physics& physics) { + if (state == DROPPED && !phobj.onground) + { + phobj.vspeed += DROP_GRAVITY; + } physics.move_object(phobj); if (state == DROPPED) @@ -64,14 +86,14 @@ namespace jrc { phobj.hspeed = 0.0; phobj.type = PhysicsObject::FIXATED; + phobj.clear_flag(PhysicsObject::NOGRAVITY); state = FLOATING; angle.set(0.0f); set_position(dest.x(), dest.y() - 4); } else { - static const float SPINSTEP = 0.2f; - angle += SPINSTEP; + angle += DROP_SPIN; } } @@ -107,6 +129,7 @@ namespace jrc void Drop::expire(int8_t type, const PhysicsObject* lt) { + phobj.clear_flag(PhysicsObject::NOGRAVITY); // (picked up mid-fall: the pickup float has ordinary gravity) switch (type) { case 0: diff --git a/src/client/Gameplay/MapleMap/MapChars.cpp b/src/client/Gameplay/MapleMap/MapChars.cpp index d0821f9..f074b4d 100644 --- a/src/client/Gameplay/MapleMap/MapChars.cpp +++ b/src/client/Gameplay/MapleMap/MapChars.cpp @@ -1,5 +1,7 @@ #include "MapChars.h" +#include "../../Util/AssetReady.h" + namespace jrc { void MapChars::draw(Layer::Id layer, double viewx, double viewy, float alpha) const @@ -9,6 +11,9 @@ namespace jrc void MapChars::update(const Physics& physics) { + // (one whose art isn't in memory yet waits here, in order, and is looked at again next time: putting it on + // the map now would stop the game to load it) + std::queue waiting; for (; !spawns.empty(); spawns.pop()) { const CharSpawn& spawn = spawns.front(); @@ -18,6 +23,10 @@ namespace jrc if (ochar) { + } + else if (!AssetReady::look(spawn.get_look())) + { + waiting.push(spawn); } else { @@ -26,6 +35,7 @@ namespace jrc ); } } + spawns = std::move(waiting); chars.update(physics); } @@ -40,11 +50,23 @@ namespace jrc void MapChars::remove(int32_t cid) { chars.remove(cid); + + // (left before their look arrived: they never appear) + std::queue kept; + for (; !spawns.empty(); spawns.pop()) + { + if (spawns.front().get_cid() != cid) + { + kept.push(spawns.front()); + } + } + spawns = std::move(kept); } void MapChars::clear() { chars.clear(); + spawns = {}; } void MapChars::send_movement(int32_t cid, const std::vector& movements) diff --git a/src/client/Gameplay/MapleMap/MapDrops.cpp b/src/client/Gameplay/MapleMap/MapDrops.cpp index 843d1c6..1a49be9 100644 --- a/src/client/Gameplay/MapleMap/MapDrops.cpp +++ b/src/client/Gameplay/MapleMap/MapDrops.cpp @@ -23,6 +23,7 @@ #include "../../Constants.h" #include "../../Data/ItemData.h" +#include "../../Util/AssetReady.h" #include "nlnx/node.hpp" #include "nlnx/nx.hpp" @@ -59,11 +60,20 @@ namespace jrc void MapDrops::update(const Physics& physics) { + // (a drop whose item isn't in memory yet waits here while its data comes down, instead of the whole game + // stopping mid-frame to fetch it: a monster dropping a pile of new things no longer hitches) + std::queue waiting; for (; !spawns.empty(); spawns.pop()) { const DropSpawn& spawn = spawns.front(); int32_t oid = spawn.get_oid(); + if (!spawn.is_meso() && !drops.contains(oid) && !AssetReady::item(spawn.get_itemid())) + { + waiting.push(std::move(spawns.front())); + continue; + } + if (Optional drop = drops.get(oid)) { drop->makeactive(); @@ -86,6 +96,8 @@ namespace jrc } } + spawns = std::move(waiting); + for (auto& mesoicon : mesoicons) { mesoicon.update(); @@ -106,12 +118,25 @@ namespace jrc if (Optional drop = drops.get(oid)) { drop->expire(mode, looter); + return; + } + + // (picked up or gone before it ever fell: it never will) + std::queue keep; + for (; !spawns.empty(); spawns.pop()) + { + if (spawns.front().get_oid() != oid) + { + keep.push(std::move(spawns.front())); + } } + spawns = std::move(keep); } void MapDrops::clear() { drops.clear(); + spawns = {}; } void MapDrops::try_pickup(int32_t oid, const Drop& drop, Point playerpos, int32_t& closest_distance_sq, Loot& closest_loot) const diff --git a/src/client/Gameplay/MapleMap/MapMobs.cpp b/src/client/Gameplay/MapleMap/MapMobs.cpp index 09ba833..831657c 100644 --- a/src/client/Gameplay/MapleMap/MapMobs.cpp +++ b/src/client/Gameplay/MapleMap/MapMobs.cpp @@ -17,6 +17,8 @@ ////////////////////////////////////////////////////////////////////////////// #include "MapMobs.h" +#include "../../Util/AssetReady.h" + #include "Mob.h" #include @@ -33,6 +35,9 @@ namespace jrc void MapMobs::update(const Physics& physics) { + // (one whose art isn't in memory yet waits here, in order, and is looked at again next time: putting it on + // the map now would stop the game to load it) + std::queue waiting; for ( ; !spawns.empty(); spawns.pop()) { const MobSpawn& spawn = spawns.front(); @@ -46,6 +51,10 @@ namespace jrc } mob->makeactive(); } + else if (!AssetReady::mob(spawn.get_id())) + { + waiting.push(spawn); + } else { mobs.add( @@ -53,6 +62,7 @@ namespace jrc ); } } + spawns = std::move(waiting); mobs.update(physics); } @@ -70,11 +80,23 @@ namespace jrc { mob->kill(animation); } + + // (gone before its art arrived: it never appears) + std::queue kept; + for ( ; !spawns.empty(); spawns.pop()) + { + if (spawns.front().get_oid() != oid) + { + kept.push(spawns.front()); + } + } + spawns = std::move(kept); } void MapMobs::clear() { mobs.clear(); + spawns = {}; } void MapMobs::set_control(int32_t oid, bool control) @@ -108,26 +130,7 @@ namespace jrc AttackResult MapMobs::send_attack(const Attack& attack) { Point origin = attack.origin; - Rectangle range = attack.range; - int16_t hrange = static_cast(range.l() * attack.hrange); - if (attack.toleft) - { - range = { - origin.x() + hrange, - origin.x() + range.r(), - origin.y() + range.t(), - origin.y() + range.b() - }; - } - else - { - range = { - origin.x() - range.r(), - origin.x() - hrange, - origin.y() + range.t(), - origin.y() + range.b() - }; - } + Rectangle range = attack.get_world_range(); uint8_t mobcount = attack.mobcount; AttackResult result = attack; @@ -268,4 +271,114 @@ namespace jrc return {}; } } + + void MapMobs::shudder(int32_t oid) + { + if (Optional mob = mobs.get(oid)) + { + mob->shudder(); + } + } + + void MapMobs::set_possessed(int32_t oid, bool on) + { + if (Optional mob = mobs.get(oid)) + { + mob->set_possessed(on); + } + } + + void MapMobs::steer(int32_t oid, int8_t direction) + { + if (Optional mob = mobs.get(oid)) + { + mob->steer(direction); + } + } + + int32_t MapMobs::find_near(Point position, int16_t reach) const + { + int32_t best = 0; + int32_t bestdist = static_cast(reach) * reach; + for (auto& mmo : mobs) + { + Optional mob = mmo.second.get(); + if (!mob || !mob->is_active() || !mob->is_alive() || mob->is_possessed()) + { + continue; + } + Point body = mob->get_body_position(); + int32_t dx = body.x() - position.x(); + int32_t dy = body.y() - position.y(); + int32_t dist = dx * dx + dy * dy; + if (dist <= bestdist) + { + bestdist = dist; + best = mmo.first; + } + } + return best; + } + + bool MapMobs::is_on(int32_t oid, Point position) const + { + if (Optional mob = mobs.get(oid)) + { + return mob->is_in_range(Rectangle(position - Point(4, 4), position + Point(4, 4))); + } + return false; + } + + void MapMobs::spirit_jump(int32_t oid) + { + if (Optional mob = mobs.get(oid)) + { + mob->spirit_jump(); + } + } + + bool MapMobs::spirit_attack(int32_t oid, int8_t number) + { + if (Optional mob = mobs.get(oid)) + { + return mob->start_attack(number, true); + } + return false; + } + + std::string MapMobs::get_name(int32_t oid) const + { + if (Optional mob = mobs.get(oid)) + { + return mob->get_name(); + } + return ""; + } + + void MapMobs::play_attack(int32_t oid, int8_t number) + { + if (Optional mob = mobs.get(oid)) + { + mob->start_attack(number, false); + } + } + + std::vector> MapMobs::catch_attacks(const Rectangle& target) + { + std::vector> caught; + for (auto& mmo : mobs) + { + Optional mob = mmo.second.get(); + if (!mob) + { + continue; + } + int8_t which = 0; + if (MobAttack attack = mob->catch_attack(target, which)) + { + caught.emplace_back(attack, which); + } + } + return caught; + } } diff --git a/src/client/Gameplay/MapleMap/MapMobs.h b/src/client/Gameplay/MapleMap/MapMobs.h index a534d74..60fdd0a 100644 --- a/src/client/Gameplay/MapleMap/MapMobs.h +++ b/src/client/Gameplay/MapleMap/MapMobs.h @@ -69,6 +69,22 @@ namespace jrc // Return the head position of a mob. Point get_mob_head_position(int32_t oid) const; + // Dordo Story's monster spirits (see Gameplay/Spirit): shake a mob, hand it to this client's spirit or take + // it back, steer it, find one near the spirit, and ask whether a point is on one. + void shudder(int32_t oid); + void set_possessed(int32_t oid, bool on); + void steer(int32_t oid, int8_t direction); + int32_t find_near(Point position, int16_t reach) const; + bool is_on(int32_t oid, Point position) const; + void spirit_jump(int32_t oid); + bool spirit_attack(int32_t oid, int8_t number); + std::string get_name(int32_t oid) const; + + // Mob attacks: another client's mob attacking (its activity byte arrived), and whether any mob's blow or + // projectile catches this player now (each gives the attack and which one it was). + void play_attack(int32_t oid, int8_t number); + std::vector> catch_attacks(const Rectangle& target); + private: std::vector find_closest(Rectangle range, Point origin, uint8_t mobcount) const; diff --git a/src/client/Gameplay/MapleMap/MapNpcs.cpp b/src/client/Gameplay/MapleMap/MapNpcs.cpp index 3ac0f64..f5a5940 100644 --- a/src/client/Gameplay/MapleMap/MapNpcs.cpp +++ b/src/client/Gameplay/MapleMap/MapNpcs.cpp @@ -17,6 +17,10 @@ ////////////////////////////////////////////////////////////////////////////// #include "MapNpcs.h" +#include + +#include "../../Util/AssetReady.h" + #include "Npc.h" #include "../QuestDelivery.h" @@ -24,6 +28,8 @@ #include "../../Net/Packets/NpcInteractionPackets.h" +#include + namespace jrc { void MapNpcs::draw(Layer::Id layer, double viewx, double viewy, float alpha) const @@ -33,6 +39,9 @@ namespace jrc void MapNpcs::update(const Physics& physics) { + // (one whose art isn't in memory yet waits here, in order, and is looked at again next time: putting it on + // the map now would stop the game to load it) + std::queue waiting; for (; !spawns.empty(); spawns.pop()) { quest_refresh_delay = 0; @@ -44,6 +53,10 @@ namespace jrc { npc->makeactive(); } + else if (!AssetReady::npc(spawn.get_id())) + { + waiting.push(spawn); + } else { npcs.add( @@ -51,24 +64,37 @@ namespace jrc ); } } + spawns = std::move(waiting); npcs.update(physics); // Poll the existing rules at a bounded rate so inventory, levels, // cooldowns and quest packets all update markers without extra network - // requests or scanning every NPC's quest list on every animation frame. + // requests. One NPC a step, round the map, so a town full of NPCs never + // checks all their quests in the same frame. if (quest_refresh_delay <= Constants::TIMESTEP) { const Player& player = Stage::get().get_player(); + size_t i = 0, which = quest_refresh_next++; + size_t count = 0; for (auto& entry : npcs) { + (void)entry; + count++; + } + for (auto& entry : npcs) + { + if (count == 0 || i++ != which % count) + continue; auto* npc = static_cast(entry.second.get()); if (npc && npc->is_active()) npc->set_quest_marker(player.get_quests().get_npc_marker(npc->get_id(), player.get_level(), player.get_stats().get_job().get_id(), player.get_inventory(), Stage::get().get_mapid())); + break; } - quest_refresh_delay = 500; + // (every NPC looked at about twice a second, however many there are) + quest_refresh_delay = count > 0 ? std::max(Constants::TIMESTEP, 500 / static_cast(count)) : 500; } else quest_refresh_delay -= Constants::TIMESTEP; @@ -85,14 +111,73 @@ namespace jrc { if (auto npc = npcs.get(oid)) npc->deactivate(); + + // (gone before its art arrived: it never appears) + std::queue kept; + for (; !spawns.empty(); spawns.pop()) + { + if (spawns.front().get_oid() != oid) + kept.push(spawns.front()); + } + spawns = std::move(kept); } void MapNpcs::clear() { npcs.clear(); + spawns = {}; quest_refresh_delay = 0; } + void MapNpcs::talk_to(const Npc& npc) const + { + if (!QuestDelivery::offer_quests(npc.get_id(), npc.get_oid(), npc.isscripted())) + { + TalkToNPCPacket(npc.get_oid()) + .dispatch(); + } + } + + bool MapNpcs::talk_nearest(Point playerpos) const + { + const Npc* nearest = nullptr; + int32_t best = 0; + for (const auto& mmo : npcs) + { + const Npc* npc = static_cast(mmo.second.get()); + if (!npc || !npc->is_active()) + continue; + + Point pos = npc->get_position(); + int32_t dx = std::abs(pos.x() - playerpos.x()); + int32_t dy = std::abs(pos.y() - playerpos.y()); + if (dx > TALK_RANGE_X || dy > TALK_RANGE_Y) + continue; + + if (!nearest || dx + dy < best) + { + nearest = npc; + best = dx + dy; + } + } + + if (!nearest) + return false; + + talk_to(*nearest); + return true; + } + + void MapNpcs::tap_targets(std::vector>& out, Point viewpos) const + { + for (auto& mmo : npcs) + { + const Npc* npc = static_cast(mmo.second.get()); + if (npc && npc->is_active()) + out.push_back(npc->tap_rect(viewpos)); + } + } + Cursor::State MapNpcs::send_cursor(bool pressed, Point position, Point viewpos) { for (auto& mmo : npcs) @@ -102,13 +187,9 @@ namespace jrc { if (pressed) { - // Body and marker hit tests intentionally share the same - // conversation entry point. - if (!QuestDelivery::offer_quests(npc->get_id(), npc->get_oid(), npc->isscripted())) - { - TalkToNPCPacket(npc->get_oid()) - .dispatch(); - } + // Body and marker hit tests (and the NPC chat key) intentionally + // share the same conversation entry point. + talk_to(*npc); return Cursor::IDLE; } else diff --git a/src/client/Gameplay/MapleMap/MapNpcs.h b/src/client/Gameplay/MapleMap/MapNpcs.h index 9164a46..1263641 100644 --- a/src/client/Gameplay/MapleMap/MapNpcs.h +++ b/src/client/Gameplay/MapleMap/MapNpcs.h @@ -26,6 +26,8 @@ namespace jrc { + class Npc; + class MapNpcs { public: @@ -40,9 +42,12 @@ namespace jrc void remove(int32_t oid); // Remove all npcs. void clear(); + // The NPC chat key (Space by default): talk to the NPC nearest the player, if one is within reach + bool talk_nearest(Point playerpos) const; // Send mouse input to clickable npcs. Cursor::State send_cursor(bool pressed, Point position, Point viewpos); + void tap_targets(std::vector>& out, Point viewpos) const; MapObjects* get_npcs() { @@ -55,9 +60,16 @@ namespace jrc } private: + void talk_to(const Npc& npc) const; + + // how far from the player (feet to feet) the NPC chat key reaches + static constexpr int32_t TALK_RANGE_X = 150; + static constexpr int32_t TALK_RANGE_Y = 120; + MapObjects npcs; std::queue spawns; uint16_t quest_refresh_delay = 0; + size_t quest_refresh_next = 0; }; } diff --git a/src/client/Gameplay/MapleMap/MapReactors.cpp b/src/client/Gameplay/MapleMap/MapReactors.cpp index aa30eb8..bfd55e4 100644 --- a/src/client/Gameplay/MapleMap/MapReactors.cpp +++ b/src/client/Gameplay/MapleMap/MapReactors.cpp @@ -17,8 +17,12 @@ ////////////////////////////////////////////////////////////////////////////// #include "MapReactors.h" +#include "../../Util/AssetReady.h" + #include "Reactor.h" +#include "../../Net/Packets/AttackAndSkillPackets.h" + namespace jrc { void MapReactors::draw(Layer::Id layer, double viewx, double viewy, float alpha) const @@ -28,6 +32,11 @@ namespace jrc void MapReactors::update(const Physics& physics) { + Reactor::play_due_knocks(); + + // (one whose art isn't in memory yet waits here, in order, and is looked at again next time: putting it on + // the map now would stop the game to load it) + std::queue waiting; for (; !spawns.empty(); spawns.pop()) { const ReactorSpawn& spawn = spawns.front(); @@ -37,11 +46,16 @@ namespace jrc { reactor->makeactive(); } + else if (!AssetReady::reactor(spawn.get_id())) + { + waiting.push(spawn); + } else { reactors.add(spawn.instantiate(physics)); } } + spawns = std::move(waiting); reactors.update(physics); } @@ -59,10 +73,48 @@ namespace jrc { reactor->destroy(state, position); } + + // (gone before its art arrived: it never appears) + std::queue kept; + for (; !spawns.empty(); spawns.pop()) + { + if (spawns.front().get_oid() != oid) + { + kept.push(spawns.front()); + } + } + spawns = std::move(kept); + } + + void MapReactors::send_attack(const Attack& attack) + { + Rectangle range = attack.get_world_range(); + // which way the hit comes from (the server only checks it for one-sided reactors): 0/2 facing left, + // 1/3 facing right; +2 on the ground + int16_t stance = attack.toleft ? 2 : 3; + + for (auto& mmo : reactors) + { + Reactor* reactor = static_cast(mmo.second.get()); + if (reactor && reactor->is_hittable() && reactor->overlaps(range)) + { + DamageReactorPacket(reactor->get_oid(), attack.toleft ? 0 : 1, stance, attack.skill).dispatch(); + reactor->play_hit_sound(); + } + } + } + + void MapReactors::trigger(int32_t oid, int8_t state) + { + if (Optional reactor = reactors.get(oid)) + { + reactor->set_state(state); + } } void MapReactors::clear() { reactors.clear(); + spawns = {}; } } diff --git a/src/client/Gameplay/MapleMap/MapReactors.h b/src/client/Gameplay/MapleMap/MapReactors.h index 121bb2f..d2f46f5 100644 --- a/src/client/Gameplay/MapleMap/MapReactors.h +++ b/src/client/Gameplay/MapleMap/MapReactors.h @@ -18,6 +18,8 @@ #pragma once #include "MapObjects.h" +#include "../Combat/Attack.h" + #include "../Spawn.h" #include @@ -40,6 +42,11 @@ namespace jrc // Remove all reactors. void clear(); + // An attack swung by the player: every reactor it covers that reacts to hits (boxes, plants) gets hit + void send_attack(const Attack& attack); + // The server moved a reactor on to a new state (it was hit) + void trigger(int32_t oid, int8_t state); + private: MapObjects reactors; diff --git a/src/client/Gameplay/MapleMap/Mob.cpp b/src/client/Gameplay/MapleMap/Mob.cpp index 1e7e5a1..b826e89 100644 --- a/src/client/Gameplay/MapleMap/Mob.cpp +++ b/src/client/Gameplay/MapleMap/Mob.cpp @@ -12,6 +12,8 @@ #include +#include + namespace jrc { Mob::Mob(int32_t oid, @@ -165,6 +167,46 @@ namespace jrc { animations[JUMP] = jumpsrc; } + + // its own attacks: a blow in front of it, or a spell / projectile with a reach + for (int8_t n = 0; n < 2; n++) + { + std::string key = "attack" + std::to_string(n + 1); + nl::node atk = animsrc[key].size() > 0 ? animsrc[key] : src[key]; + if (atk.size() == 0) + { + continue; + } + nl::node ai = atk["info"]; + AttackKind& kind = attacks[n]; + kind.exists = true; + kind.animation = atk; + kind.after = static_cast(ai["attackAfter"].get_integer(400)); + nl::node range = ai["range"]; + if (range["lt"].data_type() == nl::node::type::vector) + { + kind.box = true; + kind.area = Rectangle(range["lt"], range["rb"]); + } + else + { + kind.centre = range["sp"]; + kind.radius = static_cast(range["r"].get_integer(150)); + } + if (ai["ball"].size() > 0) + { + kind.ball = true; + kind.ballanimation = ai["ball"]; + // (bulletSpeed reads as px a tenth of a second: 140 crosses a 200 px reach in ~0.15 s) + kind.ballspeed = ai["bulletSpeed"].get_integer(200) * Constants::TIMESTEP / 100.0; + } + bool magic = ai["magic"].get_bool(); + kind.damage = static_cast(ai["PADamage"].get_integer(magic ? 0 : watk)); + if (kind.damage <= 0) + { + kind.damage = magic ? matk : watk; + } + } if (hitsrc.size() > 0) { animations[HIT] = hitsrc; @@ -285,6 +327,11 @@ namespace jrc return phobj.fhlayer; } + if (death_wait > 0 && --death_wait == 0 && dying && stance != DIE) + { + apply_death(); + } + bool aniend = animations.at(stance).update(); if (aniend && stance == DIE) { @@ -319,6 +366,50 @@ namespace jrc effects.update(); showhp.update(); + if (shudder_ticks > 0) + { + shudder_ticks--; + } + + // an attack playing: at its moment the blow lands (or the projectile leaves), and it ends with its animation + blow = 0; + if (attacking) + { + AttackKind& kind = attacks[attacking - 1]; + attack_ms += Constants::TIMESTEP; + if (!attack_landed && attack_ms >= kind.after) + { + attack_landed = true; + if (kind.ball) + { + Projectile shot; + shot.animation = kind.ballanimation; + Point from = get_body_position(); + shot.x = from.x(); + shot.y = from.y(); + shot.right = flip; + shot.speed = kind.ballspeed; + shot.reach = kind.box ? std::abs(kind.area.l()) : kind.radius; + shot.which = attacking; + projectiles.push_back(shot); + } + else + { + blow = attacking; + } + } + if (kind.animation.update() && attack_landed) + { + attacking = 0; + } + } + for (auto shot = projectiles.begin(); shot != projectiles.end();) + { + shot->animation.update(); + shot->x += shot->right ? shot->speed : -shot->speed; + shot->travelled += shot->speed; + shot = shot->travelled > shot->reach ? projectiles.erase(shot) : shot + 1; + } if (!dying) { @@ -326,8 +417,17 @@ namespace jrc { if (phobj.is_flag_not_set(PhysicsObject::TURNATEDGES)) { - flip = !flip; phobj.set_flag(PhysicsObject::TURNATEDGES); + if (possessed && control) + { + // (a spirit walking it off an edge: it stops there rather than turning round by itself) + set_stance(STAND); + update_movement(); + } + else + { + flip = !flip; + } if (stance == HIT) { @@ -375,7 +475,48 @@ namespace jrc physics.move_object(phobj); - if (control) + if (possessed && control) + { + // Walked by a spirit (on the spirit's own screen; everyone else just sees the moves it sends): left, right or standing, as steered (a hit's knockback plays out first, a jump + // until it lands, an attack until it's done). The server passes these moves on to everyone; sent on + // every change and every 0.2 s while walking. + counter++; + if (stance == JUMP) + { + if (phobj.onground && counter > 10) + { + set_stance(STAND); + update_movement(); + counter = 0; + } + } + else if (attacking) + { + } + else if (stance != HIT || counter > 40) + { + bool walk = steering != 0 && canmove; + bool wantflip = steering > 0 ? true : steering < 0 ? false : flip; + Stance want = walk ? MOVE : STAND; + if (want != stance || wantflip != flip) + { + flip = wantflip; + set_stance(want); + if (canfly) + { + flydirection = STRAIGHT; + } + update_movement(); + counter = 0; + } + else if (stance == MOVE && counter >= 25) + { + update_movement(); + counter = 0; + } + } + } + else if (control) { counter++; @@ -472,9 +613,129 @@ namespace jrc ).dispatch(); } + void Mob::shudder() + { + shudder_ticks = 90; // (~0.7 s) + } + + void Mob::set_possessed(bool on) + { + possessed = on; + steering = 0; + counter = 0; + if (on && control && stance != DIE) + { + set_stance(STAND); + update_movement(); + } + } + + bool Mob::is_possessed() const + { + return possessed; + } + + void Mob::steer(int8_t direction) + { + steering = direction; + } + + void Mob::spirit_jump() + { + if (!canjump || !phobj.onground || stance == JUMP || attacking || dying) + { + return; + } + set_stance(JUMP); + counter = 0; + update_movement(); + } + + bool Mob::has_attack(int8_t number) const + { + return number >= 1 && number <= 2 && attacks[number - 1].exists; + } + + bool Mob::start_attack(int8_t number, bool send) + { + if (!has_attack(number) || attacking || dying || !active) + { + return false; + } + attacking = number; + attack_ms = 0; + attack_landed = false; + attacks[number - 1].animation.reset(); + if (stance == MOVE) + { + set_stance(STAND); + } + if (send) + { + // (the activity byte: 24 for attack1, 26 for attack2, +1 facing left; the server checks the attack is + // ready and passes it on to everyone else's screen) + int8_t activity = static_cast(24 + 2 * (number - 1) + (flip ? 0 : 1)); + MoveMobPacket( + oid, + 1, 0, activity, 0, 0, 0, 0, + get_position(), + Movement(phobj, value_of(stance, flip)) + ).dispatch(); + } + return true; + } + + Rectangle Mob::attack_area(const AttackKind& kind) const + { + Point at = get_position(); + if (kind.box) + { + // (drawn facing left; turned round when it faces right) + int16_t l = flip ? -kind.area.r() : kind.area.l(); + int16_t r = flip ? -kind.area.l() : kind.area.r(); + return Rectangle(at.x() + l, at.x() + r, at.y() + kind.area.t(), at.y() + kind.area.b()); + } + int16_t cx = at.x() + (flip ? -kind.centre.x() : kind.centre.x()); + int16_t cy = at.y() + kind.centre.y(); + return Rectangle(cx - kind.radius, cx + kind.radius, cy - kind.radius, cy + kind.radius); + } + + MobAttack Mob::catch_attack(const Rectangle& target, int8_t& which) + { + if (!active || dying) + { + return {}; + } + if (blow && attacks[blow - 1].exists && attack_area(attacks[blow - 1]).overlaps(target)) + { + which = blow - 1; + int32_t damage = attacks[blow - 1].damage; + blow = 0; + return { damage, get_position(), id, oid }; + } + for (auto shot = projectiles.begin(); shot != projectiles.end(); ++shot) + { + Point p(static_cast(shot->x), static_cast(shot->y)); + if (target.contains(p)) + { + which = shot->which - 1; + int32_t damage = attacks[shot->which - 1].damage; + projectiles.erase(shot); + return { damage, p, id, oid }; + } + } + return {}; + } + void Mob::draw(double viewx, double viewy, float alpha) const { Point absp = phobj.get_absolute(viewx, viewy, alpha); + if (shudder_ticks > 0) + { + // a quick side-to-side shake that dies away + float strength = shudder_ticks / 90.0f; + absp.shift_x(static_cast(std::lround(std::sin(shudder_ticks * 0.9f) * 4.0f * strength))); + } Point headpos = get_head_position(absp); effects.drawbelow(absp, alpha); @@ -483,7 +744,8 @@ namespace jrc { float interopc = opacity.get(alpha); - animations.at(stance).draw( + const Animation& showing = attacking ? attacks[attacking - 1].animation : animations.at(stance); + showing.draw( DrawArgument(absp, flip && !noflip, interopc), alpha ); @@ -500,6 +762,12 @@ namespace jrc } effects.drawabove(absp, alpha); + + for (auto& shot : projectiles) + { + Point at(static_cast(std::lround(shot.x + viewx)), static_cast(std::lround(shot.y + viewy))); + shot.animation.draw(DrawArgument(at, shot.right), alpha); + } } void Mob::set_control(int8_t mode) @@ -589,6 +857,11 @@ namespace jrc { apply_death(); } + else if (stance != DIE) + { + // (a hit on its way here plays it sooner: apply_damage sees it dying) + death_wait = 40; + } break; case 2: fading = true; diff --git a/src/client/Gameplay/MapleMap/Mob.h b/src/client/Gameplay/MapleMap/Mob.h index eb6edaa..d7c03f9 100644 --- a/src/client/Gameplay/MapleMap/Mob.h +++ b/src/client/Gameplay/MapleMap/Mob.h @@ -1,6 +1,9 @@ #pragma once #include "LivingObject.h" +#include +#include + #include "../Combat/Attack.h" #include "../Combat/Bullet.h" #include "../Combat/DamageNumber.h" @@ -89,6 +92,30 @@ namespace jrc bool is_in_range(const Rectangle& range) const; /// Check if this mob is still alive. bool is_alive() const; + + /// Dordo Story's monster spirits. Shudder: a spirit just took hold of (or let go of) this mob, and everyone + /// who can see it sees it shake. + void shudder(); + /// This client's spirit holds the mob: no more wandering about on its own, it goes where it's steered. + void set_possessed(bool on); + bool is_possessed() const; + /// Which way the spirit is walking it: -1 left, 0 stand still, 1 right. + void steer(int8_t direction); + const std::string& get_name() const + { + return name; + } + /// A spirit makes it jump (if it can, and is on the ground). + void spirit_jump(); + + /// The mob's own attacks (attack1, attack2 in its files), if it has them. + bool has_attack(int8_t number) const; + /// Play attack 1 or 2: its animation, then at its moment a blow (or a projectile flying off). Sent to the + /// server (who passes it on) when this client is the one moving it. + bool start_attack(int8_t number, bool send); + /// Does an attack of this mob (a blow landing now, or one of its projectiles) catch this rectangle? Gives the + /// attack and which one it was (0 = attack1, for the server), and counts as used. + MobAttack catch_attack(const Rectangle& target, int8_t& which); /// Return the body center used for combat targeting. Point get_body_position() const; /// Return the head position. @@ -133,6 +160,41 @@ namespace jrc /// Return the current animation bounds in world space. Rectangle get_bounds(Point position) const; + bool possessed = false; + int8_t steering = 0; + uint16_t shudder_ticks = 0; + + // attack1 / attack2 from the mob's files + struct AttackKind + { + bool exists = false; + Animation animation; + uint16_t after = 0; // ms from the start until it lands (or the projectile leaves) + bool box = false; // a box in front of it (lt, rb) or a circle (sp, r) + Rectangle area; + Point centre; + int16_t radius = 0; + bool ball = false; // fires a projectile + Animation ballanimation; + double ballspeed = 0.0; // px a step + int32_t damage = 0; + }; + struct Projectile + { + Animation animation; + double x = 0.0, y = 0.0, speed = 0.0, travelled = 0.0, reach = 0.0; + bool right = false; + int8_t which = 0; + }; + std::array attacks; + int8_t attacking = 0; // 1 or 2 while an attack plays + uint16_t attack_ms = 0; + bool attack_landed = false; + int8_t blow = 0; // an attack's moment came this step: anyone in its area is hit + std::vector projectiles; + + Rectangle attack_area(const AttackKind& kind) const; + std::map animations; std::string name; Sound hitsound; @@ -171,6 +233,9 @@ namespace jrc bool dying; bool dead; bool awaitdeath; + // (told it died, but no hit on this screen is about to play its death: it plays on its own after this many + // steps; on every screen but the one moving it, a killing blow never sets awaitdeath) + uint16_t death_wait = 0; bool control; bool aggro; Stance stance; diff --git a/src/client/Gameplay/MapleMap/Npc.cpp b/src/client/Gameplay/MapleMap/Npc.cpp index af21fd3..b92f862 100644 --- a/src/client/Gameplay/MapleMap/Npc.cpp +++ b/src/client/Gameplay/MapleMap/Npc.cpp @@ -18,6 +18,8 @@ //#pragma once #include "Npc.h" +#include "../../Graphics/GraphicsGL.h" + #include "nlnx/node.hpp" #include "nlnx/nx.hpp" @@ -52,6 +54,11 @@ namespace jrc hidename = info["hideName"].get_bool(); mouseonly = info["talkMouseOnly"].get_bool(); scripted = info["script"].size() > 0 || info["shop"].get_bool(); + // (the town MapleTVs: their two black panels show what the page paints there; the stored offsets are + // shorts, some saved unsigned, hence the casts) + mapletv = info["MapleTV"].get_bool(); + tv_ad = { static_cast(info["MapleTVadX"].get_integer()), static_cast(info["MapleTVadY"].get_integer()) }; + tv_msg = { static_cast(info["MapleTVmsgX"].get_integer()), static_cast(info["MapleTVmsgY"].get_integer()) }; for (const auto& npcnode : src) { @@ -99,6 +106,19 @@ namespace jrc animations.at(stance).draw(DrawArgument(absp, flip), alpha); } + if (mapletv) + { + // the panels are 240 x 180 and 240 x 90 inside a 1 px black edge, offsets from the feet (mirrored + // when the NPC is) + auto panel = [&](Point at, int16_t w, int16_t h) { + int16_t l = flip ? static_cast(absp.x() - at.x() - w) : static_cast(absp.x() + at.x()); + int16_t t = absp.y() + at.y(); + return Rectangle(l, l + w, t, t + h); + }; + GraphicsGL::get().draw_tv(GraphicsGL::TV_AD, panel(tv_ad, 240, 180), 1.0f); + GraphicsGL::get().draw_tv(GraphicsGL::TV_MSG, panel(tv_msg, 240, 90), 1.0f); + } + if (!hidename) { namelabel.draw(absp); @@ -183,6 +203,13 @@ namespace jrc quest_marker_offset = Point(0, -sprite_top - bottom - 6); } + Rectangle Npc::tap_rect(Point viewpos) const + { + Point absp = get_position() + viewpos; + Point dim = animations.count(stance) ? animations.at(stance).get_dimensions() : Point(); + return Rectangle(absp.x() - dim.x() / 2, absp.x() + dim.x() / 2, absp.y() - dim.y(), absp.y()); + } + bool Npc::inrange(Point cursorpos, Point viewpos) const { if (!active) diff --git a/src/client/Gameplay/MapleMap/Npc.h b/src/client/Gameplay/MapleMap/Npc.h index f716fcb..02460a8 100644 --- a/src/client/Gameplay/MapleMap/Npc.h +++ b/src/client/Gameplay/MapleMap/Npc.h @@ -51,6 +51,8 @@ namespace jrc bool isscripted() const; // Check if the npc is in range of the cursor. bool inrange(Point cursorpos, Point viewpos) const; + // its body, where inrange looks (screen space) + Rectangle tap_rect(Point viewpos) const; void set_quest_marker(Questlog::NpcMarker marker); @@ -78,6 +80,9 @@ namespace jrc bool hidename; bool scripted; bool mouseonly; + bool mapletv = false; + Point tv_ad; + Point tv_msg; int32_t npcid; bool flip; diff --git a/src/client/Gameplay/MapleMap/Reactor.cpp b/src/client/Gameplay/MapleMap/Reactor.cpp index b8791bc..6f39042 100644 --- a/src/client/Gameplay/MapleMap/Reactor.cpp +++ b/src/client/Gameplay/MapleMap/Reactor.cpp @@ -17,30 +17,203 @@ ////////////////////////////////////////////////////////////////////////////// #include "Reactor.h" +#include "../../Audio/Audio.h" #include "../../Util/Misc.h" #include "nlnx/nx.hpp" +#include +#include + namespace jrc { Reactor::Reactor(int32_t o, int32_t r, int8_t s, Point p) - : MapObject(o, p), rid(r), state(s) { + : MapObject(o, p), rid(r), state(s), hitting(false), dying(false) { std::string strid = string_format::extend_id(rid, 7); - nl::node src = nl::nx::reactor[strid + ".img"]; + src = nl::nx::reactor[strid + ".img"]; + + // Some reactors borrow another one's looks (their own node keeps the states' events) + art = src; + std::string link = src["info"]["link"]; + if (!link.empty()) + { + if (nl::node linked = nl::nx::reactor[link + ".img"]) + { + art = linked; + } + } + + normal = art[std::to_string(state)]; + + // Its knocks: its own, else the ones of the reactor it borrows its looks from, else the plain box's + // (Maple Island's boxes, 0002001, have none of their own: their twin 0002000 does) + sounds = nl::nx::sound["Reactor.img"][std::to_string(rid)]; + if (!sounds && !link.empty()) + sounds = nl::nx::sound["Reactor.img"][std::to_string(std::atoi(link.c_str()))]; + if (!sounds) + sounds = nl::nx::sound["Reactor.img"]["2000"]; + + // (read in now so the first hit isn't silent while one is still being decoded) + for (nl::node sound : sounds) + { + if (nl::node hitsound = sound["Hit"]) + Sound pre(hitsound); + } + } + + namespace + { + constexpr int64_t KNOCK_DELAY_MS = 330; + + int64_t reactor_now_ms() + { + return std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count(); + } + } + + nl::node Reactor::hit_sound(int8_t at) const + { + // (its state's knock; a state past the last one with a knock (a borrowed box's) uses that last one) + nl::node hitsound = sounds[std::to_string(at)]["Hit"]; + for (int8_t back = at; !hitsound && back > 0; back--) + hitsound = sounds[std::to_string(back - 1)]["Hit"]; + return hitsound; + } + + std::vector>& Reactor::pending_knocks() + { + static std::vector> knocks; + return knocks; + } + + void Reactor::play_due_knocks() + { + // (kept apart from the reactors: a box that broke on that hit is gone before its knock is due) + auto& knocks = pending_knocks(); + int64_t now = reactor_now_ms(); + for (auto it = knocks.begin(); it != knocks.end();) + { + if (now >= it->first) + { + Sound(it->second).play(); + it = knocks.erase(it); + } + else + { + ++it; + } + } + } - normal = src["0"]; + void Reactor::play_hit_sound() + { + int64_t now = reactor_now_ms(); + if (now - knocked_at < 250) + return; + // (heard a third of a second after the swing, when the blow lands, as in the original: update plays it) + if (nl::node hitsound = hit_sound(state)) + { + pending_knocks().push_back({ now + KNOCK_DELAY_MS, hitsound }); + knocked_at = now; + } + } + + Rectangle Reactor::frame_bounds() const + { + // (the same spot draw() puts it: lifted by half its height, then placed by the frame's origin) + const Animation& shown = hitting ? hit : normal; + Point dims = shown.get_dimensions(); + int16_t lift = hitting ? hit_lift : static_cast(normal.get_dimensions().y() / 2); + Point topleft = get_position() - Point(0, lift) - shown.get_origin(); + return { topleft.x(), static_cast(topleft.x() + dims.x()), topleft.y(), static_cast(topleft.y() + dims.y()) }; } void Reactor::draw(double viewx, double viewy, float alpha) const { Point absp = phobj.get_absolute(viewx, viewy, alpha); Point shift = { 0, normal.get_dimensions().y() / 2 }; - normal.draw(absp - shift, alpha); + if (hitting) + { + hit.draw(absp - Point(0, hit_lift), alpha); + } + else if (!dying) + { + normal.draw(absp - shift, alpha); + } + } + + int8_t Reactor::update(const Physics& physics) + { + if (hitting) + { + if (hit.update()) + { + hitting = false; + if (dying) + { + deactivate(); + } + } + } + else + { + normal.update(); + } + + return MapObject::update(physics); + } + + void Reactor::set_state(int8_t newstate) + { + nl::node hitsrc = art[std::to_string(state)]["hit"]; + // (the box's own knock: Sound.nx Reactor.img///Hit) + nl::node hitsound = hit_sound(state); + // (unless our own swing already knocked just now: the server's word is the same hit coming back) + if (hitsound && newstate != state && reactor_now_ms() - knocked_at > 700 + KNOCK_DELAY_MS) + { + Sound(hitsound).play(); + } + knocked_at = 0; + int16_t old_lift = static_cast(normal.get_dimensions().y() / 2); + state = newstate; + normal = art[std::to_string(state)]; + + if (hitsrc.size() > 0) + { + hit = hitsrc; + hit_lift = old_lift; + hitting = true; + } + } + + void Reactor::destroy(int8_t newstate, Point) + { + set_state(newstate); + dying = true; + if (!hitting) + { + deactivate(); + } + } + + bool Reactor::is_hittable() const + { + // a state's events say what moves it on: types 0-99 are hits (2: only from one side, which the server + // decides); 100 and up are items dropped on it, timers and the like + nl::node event = src[std::to_string(state)]["event"]["0"]; + if (!event) + { + return false; + } + + int64_t type = event["type"].get_integer(-1); + return type >= 0 && type < 100; } - void Reactor::destroy(int8_t, Point) + bool Reactor::overlaps(const Rectangle& area) const { - deactivate(); + return is_active() && !dying && frame_bounds().overlaps(area); } } diff --git a/src/client/Gameplay/MapleMap/Reactor.h b/src/client/Gameplay/MapleMap/Reactor.h index 0e5d702..f889296 100644 --- a/src/client/Gameplay/MapleMap/Reactor.h +++ b/src/client/Gameplay/MapleMap/Reactor.h @@ -19,7 +19,11 @@ #include "MapObject.h" #include "../../Graphics/Animation.h" +#include "../../Template/Rectangle.h" +#include "nlnx/node.hpp" + +#include #include namespace jrc @@ -31,14 +35,42 @@ namespace jrc int8_t state, Point position); void draw(double viewx, double viewy, float alpha) const override; + int8_t update(const Physics& physics) override; + // The server moved it on (it was hit): play the old state's hit animation, then show the new state + void set_state(int8_t state); + // (our own swing just reached it: its knock now, not when the server's word comes back) + void play_hit_sound(); + // the knocks our swings started, each played once its moment comes (MapReactors::update, every step) + static void play_due_knocks(); + static std::vector>& pending_knocks(); + // Broken or used up: play its last hit, then it's gone void destroy(int8_t state, Point position); + // Does its current state react to being hit (a box, a plant), rather than to an item or a timer? + bool is_hittable() const; + // Is any of it inside this area (map coordinates)? + bool overlaps(const Rectangle& area) const; + private: - int32_t oid; + // where the current frame is drawn, in map coordinates + Rectangle frame_bounds() const; + int32_t rid; + int64_t knocked_at = 0; + nl::node sounds; + // (the lift a hit animation is drawn with: half the height of the state it belongs to, kept while it plays, + // since by then the reactor shows the next state, and a broken box's next state is a 1x1 blank) + int16_t hit_lift = 0; + + nl::node hit_sound(int8_t state) const; int8_t state; + nl::node src; + nl::node art; Animation normal; + Animation hit; + bool hitting; + bool dying; }; } diff --git a/src/client/Gameplay/Spawn.cpp b/src/client/Gameplay/Spawn.cpp index 87ce57e..1b11a95 100644 --- a/src/client/Gameplay/Spawn.cpp +++ b/src/client/Gameplay/Spawn.cpp @@ -34,6 +34,11 @@ namespace jrc return oid; } + int32_t NpcSpawn::get_id() const + { + return id; + } + std::unique_ptr NpcSpawn::instantiate(const Physics& physics) const { auto spawnposition = physics.get_y_below(position); @@ -54,6 +59,11 @@ namespace jrc return oid; } + int32_t MobSpawn::get_id() const + { + return id; + } + std::unique_ptr MobSpawn::instantiate() const { return std::make_unique(oid, id, mode, stance, fh, newspawn, team, position); @@ -68,6 +78,11 @@ namespace jrc return oid; } + int32_t ReactorSpawn::get_id() const + { + return rid; + } + std::unique_ptr ReactorSpawn::instantiate(const Physics& physics) const { auto spawnposition = physics.get_y_below(position); @@ -119,6 +134,11 @@ namespace jrc return cid; } + const LookEntry& CharSpawn::get_look() const + { + return look; + } + std::unique_ptr CharSpawn::instantiate() const { return std::make_unique(cid, look, level, job, name, stance, position); diff --git a/src/client/Gameplay/Spawn.h b/src/client/Gameplay/Spawn.h index 65ff646..f40c9a5 100644 --- a/src/client/Gameplay/Spawn.h +++ b/src/client/Gameplay/Spawn.h @@ -37,6 +37,7 @@ namespace jrc uint16_t fh); int32_t get_oid() const; + int32_t get_id() const; std::unique_ptr instantiate(const Physics& physics) const; private: @@ -62,6 +63,7 @@ namespace jrc int8_t get_mode() const; int32_t get_oid() const; + int32_t get_id() const; std::unique_ptr instantiate() const; private: @@ -85,6 +87,7 @@ namespace jrc Point position); int32_t get_oid() const; + int32_t get_id() const; std::unique_ptr instantiate(const Physics& physics) const; private: @@ -139,6 +142,7 @@ namespace jrc Point position); int32_t get_cid() const; + const LookEntry& get_look() const; std::unique_ptr instantiate() const; private: diff --git a/src/client/Gameplay/Spirit.cpp b/src/client/Gameplay/Spirit.cpp new file mode 100644 index 0000000..b19693f --- /dev/null +++ b/src/client/Gameplay/Spirit.cpp @@ -0,0 +1,280 @@ +////////////////////////////////////////////////////////////////////////////// +// This file is part of the Journey MMORPG client (Dordo Story's changes) // +// // +// This program is free software: you can redistribute it and/or modify // +// it under the terms of the GNU Affero General Public License as // +// published by the Free Software Foundation, either version 3 of the // +// License, or (at your option) any later version. // +////////////////////////////////////////////////////////////////////////////// +#include "Spirit.h" + +#include "MapleMap/MapMobs.h" +#include "Physics/Physics.h" + +#include "../Character/Player.h" +#include "../Graphics/GraphicsGL.h" +#include "../IO/UI.h" + +#include +#include "../Net/Packets/GameplayPackets.h" + +#include +#include + +#ifdef MS_PLATFORM_WASM +#include +#endif + +namespace jrc +{ + namespace + { + // (per 8 ms step) top speed, how quickly it gets there and slows down again + constexpr double FLY_SPEED = 3.2; + constexpr double FLY_EASE = 0.12; + // how near the ball's middle has to come to a monster's body to take hold of it + constexpr int16_t REACH = 45; + // the ball: drawn this big (game pixels), floating this far above the spirit's point + constexpr int16_t BALL = 40; + constexpr int16_t BALL_RISE = 28; + + int64_t now_ms() + { + return std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count(); + } + + // the page's ring of towns (or L3's pop to Maple Island): a map id to go to, -1 for anywhere at all (Y held + // ten seconds), taken once (0: none) + int32_t warp_asked() + { +#ifdef MS_PLATFORM_WASM + return EM_ASM_INT({ + var to = Module.dordoSpiritWarp | 0; + Module.dordoSpiritWarp = 0; + return to; + }); +#else + return 0; +#endif + } + + // the page's "let go" (a controller's four face buttons, or both sticks pressed in), taken once + bool exit_asked() + { +#ifdef MS_PLATFORM_WASM + return EM_ASM_INT({ + var asked = Module.dordoSpiritExit; + Module.dordoSpiritExit = 0; + return asked ? 1 : 0; + }) != 0; +#else + return false; +#endif + } + + // tells the page whether a monster is held (phones show a "let go" button only then) + void tell_page(bool holding) + { +#ifdef MS_PLATFORM_WASM + EM_ASM({ if (Module.onSpiritHeld) Module.onSpiritHeld($0); }, holding ? 1 : 0); +#endif + } + } + + bool Spirit::active() const + { + return is_spirit; + } + + bool Spirit::possessing() const + { + return held != 0; + } + + void Spirit::begin() + { + is_spirit = true; + SpiritPacket(SpiritPacket::BECOME).dispatch(); + } + + void Spirit::map_changed() + { + if (held) + tell_page(false); + held = 0; + letting_go = false; + just_left = 0; + asked_for = 0; + hspeed = vspeed = 0.0; + } + + void Spirit::update(Player& player, MapMobs& mobs, const Physics& physics) + { + bool left = player.is_key_down(KeyAction::LEFT); + bool right = player.is_key_down(KeyAction::RIGHT); + bool up = player.is_key_down(KeyAction::UP); + bool down = player.is_key_down(KeyAction::DOWN); + bool exit = exit_asked(); + bool jump = player.is_key_down(KeyAction::JUMP); + bool attack = player.is_key_down(KeyAction::ATTACK); + bool attack2 = UI::get().is_held(GLFW_KEY_LEFT_SHIFT) || UI::get().is_held(GLFW_KEY_RIGHT_SHIFT); + bool jumped = jump && !was_jump, attacked = attack && !was_attack, attacked2 = attack2 && !was_attack2; + was_jump = jump; was_attack = attack; was_attack2 = attack2; + + // (-1: anywhere at all, the server picks) + if (int32_t to = warp_asked()) + { + if (to < 0) + SpiritPacket(SpiritPacket::RANDOM).dispatch(); + else + SpiritPacket(SpiritPacket::WARP, to).dispatch(); + } + + if (held) + { + if (!mobs.contains(held)) + { + // (gone without a word from the server, a map reset say: back to a ball) + let_go(); + return; + } + + mobs.steer(held, left == right ? 0 : (right ? 1 : -1)); + if (jumped) + mobs.spirit_jump(held); + if (attacked) + mobs.spirit_attack(held, 1); + if (attacked2) + mobs.spirit_attack(held, 2); + player.spirit_follow(mobs.get_mob_position(held)); + + if (exit && !letting_go) + { + letting_go = true; + SpiritPacket(SpiritPacket::RELEASE).dispatch(); + } + return; + } + + // flying: eased toward full speed in the held directions, and eased to a stop when let go + double wanth = left == right ? 0.0 : (right ? FLY_SPEED : -FLY_SPEED); + double wantv = up == down ? 0.0 : (down ? FLY_SPEED : -FLY_SPEED); + hspeed += (wanth - hspeed) * FLY_EASE; + vspeed += (wantv - vspeed) * FLY_EASE; + if (std::abs(hspeed) < 0.01) hspeed = 0.0; + if (std::abs(vspeed) < 0.01) vspeed = 0.0; + + const Footholdtree& fht = physics.get_fht(); + player.spirit_fly(hspeed, vspeed, fht.get_walls(), fht.get_borders()); + bob += 0.04f; + + // reaching for a monster: the nearest within reach, asked for at most twice a second + Point ball = player.get_position() - Point(0, BALL_RISE); + int64_t now = now_ms(); + int32_t near = mobs.find_near(ball, REACH); + if (just_left) + { + Point was = mobs.get_mob_body_position(just_left); + bool away = !mobs.contains(just_left) || std::abs(was.x() - ball.x()) + std::abs(was.y() - ball.y()) > REACH * 2; + if (away && now - left_at > 1500) + { + just_left = 0; + } + } + if (near && near != just_left && (near != asked_for || now - asked_at > 500)) + { + asked_for = near; + asked_at = now; + SpiritPacket(SpiritPacket::POSSESS, near).dispatch(); + } + } + + void Spirit::draw(const Player& player, double viewx, double viewy, float alpha) const + { + if (held) + { + return; + } + + Point absp = player.drawn_at(viewx, viewy, alpha); + int16_t float_y = static_cast(std::lround(std::sin(bob) * 3.0f)); + int16_t l = absp.x() - BALL / 2; + int16_t t = absp.y() - BALL_RISE - BALL / 2 + float_y; + GraphicsGL::get().draw_tv(GraphicsGL::TV_SPIRIT, Rectangle(l, l + BALL, t, t + BALL), 0.92f); + } + + void Spirit::send_cursor(bool pressed, Point cursor, Point viewpos, const MapMobs& mobs) + { + bool click = pressed && !was_pressed; + was_pressed = pressed; + if (!click || !held) + { + return; + } + + int64_t now = now_ms(); + bool twice = now - last_click < 400; + last_click = now; + if (twice && !letting_go && mobs.is_on(held, cursor - viewpos)) + { + letting_go = true; + SpiritPacket(SpiritPacket::RELEASE).dispatch(); + } + } + + void Spirit::held_hp(int32_t oid, int32_t newhp, int32_t newmax) + { + if (oid == held) + { + hp = newhp; + maxhp = newmax; + } + } + + const std::string& Spirit::held_name() const + { + return heldname; + } + + int32_t Spirit::get_hp() const + { + return held ? hp : 0; + } + + int32_t Spirit::get_maxhp() const + { + return held ? maxhp : 0; + } + + void Spirit::possessed(int32_t oid, MapMobs& mobs) + { + held = oid; + heldname = mobs.get_name(oid); + hp = maxhp = 0; + letting_go = false; + hspeed = vspeed = 0.0; + mobs.set_possessed(oid, true); + tell_page(true); + } + + void Spirit::released(int32_t oid, MapMobs& mobs) + { + mobs.set_possessed(oid, false); + if (held == oid) + { + let_go(); + } + } + + void Spirit::let_go() + { + heldname.clear(); + hp = maxhp = 0; + just_left = held; + left_at = now_ms(); + held = 0; + letting_go = false; + tell_page(false); + } +} diff --git a/src/client/Gameplay/Spirit.h b/src/client/Gameplay/Spirit.h new file mode 100644 index 0000000..ed7e4c2 --- /dev/null +++ b/src/client/Gameplay/Spirit.h @@ -0,0 +1,85 @@ +////////////////////////////////////////////////////////////////////////////// +// This file is part of the Journey MMORPG client (Dordo Story's changes) // +// // +// This program is free software: you can redistribute it and/or modify // +// it under the terms of the GNU Affero General Public License as // +// published by the Free Software Foundation, either version 3 of the // +// License, or (at your option) any later version. // +////////////////////////////////////////////////////////////////////////////// +#pragma once +#include "../Template/Point.h" + +#include +#include + +namespace jrc +{ + class Player; + class MapMobs; + class Physics; + + // Dordo Story's monster spirit: a player who came in as a glass ball (the page sets Module.Dordo.spirit = "1"). + // Nobody else sees it (the server never shows it), it flies anywhere with the arrow keys, through walls and + // floors, smoothly, and it can't fight, loot or talk to NPCs (Stage lets only the arrows through; the server + // refuses the rest anyway). Up at a portal still goes through it. + // + // Drifting close to a monster takes hold of it (the server makes this client its controller and everyone sees + // it shudder): the ball goes away, the camera follows the monster, and left / right / nothing walks it about. + // When it dies, or the spirit lets go (double-click it, or on a controller all four face buttons or both + // sticks pressed in, which the page passes on as Module.dordoSpiritExit), the ball comes back where it was. + // Holding one, Jump jumps (if it can), Attack uses its first attack and Shift its second, if it has them. + // The page's ring of towns (Module.dordoSpiritWarp = a map id) takes the spirit to one of them. + class Spirit + { + public: + bool active() const; + bool possessing() const; + + // Became a spirit (on entering the game): tells the server, which hides this character from everyone. + void begin(); + // A new map: whatever was held is gone (the server let go of it when the spirit left). + void map_changed(); + + // Fly (or walk the held monster), keep the server told where the spirit is, and reach for monsters. + void update(Player& player, MapMobs& mobs, const Physics& physics); + // The glass ball, over everything on the map (not while holding a monster). + void draw(const Player& player, double viewx, double viewy, float alpha) const; + // Double-clicking the held monster lets go of it. Cursor in screen space, viewpos the camera's offset. + void send_cursor(bool pressed, Point cursor, Point viewpos, const MapMobs& mobs); + + // From the server: this spirit now holds the monster, or no longer does, and the held one's HP. + void possessed(int32_t oid, MapMobs& mobs); + void released(int32_t oid, MapMobs& mobs); + void held_hp(int32_t oid, int32_t hp, int32_t maxhp); + + // For the status bar: what's held (its name, "" for nothing) and its HP. + const std::string& held_name() const; + int32_t get_hp() const; + int32_t get_maxhp() const; + + private: + void let_go(); + + bool is_spirit = false; + int32_t held = 0; + std::string heldname; + int32_t hp = 0; + int32_t maxhp = 0; + // (keys pressed, not held: one jump or attack a press) + bool was_jump = false, was_attack = false, was_attack2 = false; + bool letting_go = false; + + double hspeed = 0.0; + double vspeed = 0.0; + float bob = 0.0f; + + // (not straight back into the monster just left: away from it first, and a moment's pause) + int32_t just_left = 0; + int64_t left_at = 0; + int32_t asked_for = 0; + int64_t asked_at = 0; + + bool was_pressed = false; + int64_t last_click = 0; + }; +} diff --git a/src/client/Gameplay/Stage.cpp b/src/client/Gameplay/Stage.cpp index fb47f7c..62707fc 100644 --- a/src/client/Gameplay/Stage.cpp +++ b/src/client/Gameplay/Stage.cpp @@ -17,12 +17,15 @@ ////////////////////////////////////////////////////////////////////////////// #include "Stage.h" +#include "../IO/UI.h" +#include "../IO/UITypes/UINpcTalk.h" #include "../Audio/Audio.h" #include "../IO/KeyAction.h" #include "../IO/Messages.h" #include "../Net/Packets/GameplayPackets.h" #include "../Net/Packets/AttackAndSkillPackets.h" #include "../Util/Misc.h" +#include "../Util/AssetReady.h" #include "nlnx/nx.hpp" @@ -36,7 +39,7 @@ namespace jrc } Stage::Stage() - : combat(player, chars, mobs, physics) + : combat(player, chars, mobs, reactors, physics) , last_pickup_time(0) , pending_intro_warp_mapid(-1) , pending_intro_warp_delay_ms(0) @@ -86,6 +89,7 @@ namespace jrc chars.clear(); npcs.clear(); mobs.clear(); + spirit.map_changed(); drops.clear(); reactors.clear(); } @@ -139,9 +143,16 @@ namespace jrc npcs.draw(id, viewx, viewy, alpha); mobs.draw(id, viewx, viewy, alpha); chars.draw(id, viewx, viewy, alpha); - player.draw(id, viewx, viewy, alpha); + if (!spirit.active()) + { + player.draw(id, viewx, viewy, alpha); + } drops.draw(id, viewx, viewy, alpha); } + if (spirit.active()) + { + spirit.draw(player, viewx, viewy, alpha); + } combat.draw(viewx, viewy, alpha); portals.draw(viewpos, alpha); backgrounds.drawforegrounds(viewx, viewy, alpha); @@ -155,6 +166,13 @@ namespace jrc return; } + // Once this map is in, bring the windows the keys open into memory in the background, so the first S or K + // doesn't stop the game to load them (cheap once done: the answer is remembered) + if (!spirit.active() && AssetReady::map(mapid)) + { + AssetReady::game_windows(player.get_stats().get_job().get_id()); + } + combat.update(); backgrounds.update(); effect.update(); @@ -165,7 +183,14 @@ namespace jrc mobs.update(physics); chars.update(physics); drops.update(physics); - player.update(physics); + if (spirit.active()) + { + spirit.update(player, mobs, physics); + } + else + { + player.update(physics); + } if (is_intro_input_locked()) { // Direction3-style intro scenes present the actor facing left and @@ -179,7 +204,8 @@ namespace jrc portals.update(player.get_position()); camera.update(player.get_position()); - if (player.is_invincible()) + // (a spirit passes through monsters) + if (player.is_invincible() || spirit.active()) { return; } @@ -192,21 +218,31 @@ namespace jrc TakeDamagePacket(result, TakeDamagePacket::TOUCH).dispatch(); } } + + // a mob's own attack (a spirit's, mostly: ordinary mobs here don't use theirs): its blow or projectile + // catching this player, told to the server as that attack (0 = attack1) so it checks it against the mob's + Point at = player.get_position(); + for (auto& caught : mobs.catch_attacks(Rectangle(at.x() - 18, at.x() + 18, at.y() - 60, at.y()))) + { + MobAttackResult result = player.damage(caught.first); + TakeDamagePacket(caught.second, 0, result.damage, result.mobid, result.oid, result.direction).dispatch(); + if (player.is_invincible()) + { + break; + } + } } void Stage::handle_held_actions() { - if (!playable) + if (!playable || spirit.active()) { return; } - // Drive gameplay repeats from the fixed update loop so held jump/attack - // behave consistently even when platform key-repeat is absent or uneven. - if (player.is_key_down(KeyAction::JUMP)) - { - playable->send_action(KeyAction::JUMP, true); - } + // Drive gameplay repeats from the fixed update loop so held attack + // behaves consistently even when platform key-repeat is absent or uneven. + // (Jump doesn't repeat: one jump a press, let go and press again; see Player::send_action) if (player.is_key_down(KeyAction::ATTACK)) { @@ -320,6 +356,10 @@ namespace jrc void Stage::update_directional_context() { + if (spirit.active()) + { + return; // (a spirit flies: no ropes to catch) + } if (player.is_key_down(KeyAction::UP)) { check_ladders(true); @@ -380,6 +420,30 @@ namespace jrc return; } + // A monster spirit only has the arrows: flying (or walking a monster), and Up through portals while it's a + // ball; Jump and Attack only for a monster it holds (Spirit::update). No skills, items, looting, sitting or + // NPC chat. + if (spirit.active()) + { + if (type != KeyType::ACTION) + { + return; + } + KeyAction::Id keyaction = KeyAction::actionbyid(action); + if (keyaction != KeyAction::LEFT && keyaction != KeyAction::RIGHT && + keyaction != KeyAction::UP && keyaction != KeyAction::DOWN && + keyaction != KeyAction::JUMP && keyaction != KeyAction::ATTACK) + { + return; + } + if (keyaction == KeyAction::UP && down && !player.is_key_down(KeyAction::UP) && !spirit.possessing()) + { + check_portals(); + } + player.remember_key(keyaction, down); + return; + } + if (is_intro_input_locked()) { switch (type) @@ -416,6 +480,16 @@ namespace jrc // Immediate pickup on key press check_drops(); break; + case KeyAction::NPCCHAT: + { + // (not while a conversation is open: the dialog stays around when closed, just inactive) + auto npctalk = UI::get().get_element(); + if (!npctalk || !npctalk->is_active()) + { + npcs.talk_nearest(player.get_position()); + } + break; + } default: break; } @@ -427,25 +501,52 @@ namespace jrc } break; } + // (skills, items and faces on the press only: letting the key go used the potion or skill a second time) case KeyType::SKILL: - combat.use_move(action); + if (down) + combat.use_move(action); break; case KeyType::ITEM: - player.use_item(action); + if (down) + player.use_item(action); break; case KeyType::FACE: - player.set_expression(action); + if (down) + player.set_expression(action); + // (and for everyone else on the map: the server takes emotes 1-7 for the free faces) + if (down && action >= 100 && action <= 106) + { + FaceExpressionPacket(action - 99).dispatch(); + } break; default: break; } } + void Stage::npc_tap_targets(std::vector>& out) const + { + if (state != State::ACTIVE || spirit.active()) + return; + npcs.tap_targets(out, camera.position()); + } + Cursor::State Stage::send_cursor(bool pressed, Point position) { + if (spirit.active()) + { + // (no NPCs for spirits; a double-click on the monster it holds lets go) + spirit.send_cursor(pressed, position, camera.position(), mobs); + return Cursor::IDLE; + } return npcs.send_cursor(pressed, position, camera.position()); } + Spirit& Stage::get_spirit() + { + return spirit; + } + bool Stage::is_player(int32_t cid) const { return cid == player.get_oid(); diff --git a/src/client/Gameplay/Stage.h b/src/client/Gameplay/Stage.h index 77e5180..6624f8c 100644 --- a/src/client/Gameplay/Stage.h +++ b/src/client/Gameplay/Stage.h @@ -31,6 +31,7 @@ #include "MapleMap/MapNpcs.h" #include "MapleMap/MapDrops.h" #include "Physics/Physics.h" +#include "Spirit.h" #include "../Character/Player.h" #include "../IO/KeyType.h" @@ -71,6 +72,8 @@ namespace jrc void send_key(KeyType::Id keytype, int32_t keycode, bool pressed); // Send mouse input to the stage. Cursor::State send_cursor(bool pressed, Point position); + // (phones) the NPCs a tap can land on, in screen space (none for a monster spirit) + void npc_tap_targets(std::vector>& out) const; // Check if the specified id is the player's id. bool is_player(int32_t cid) const; @@ -91,6 +94,8 @@ namespace jrc int32_t get_mapid() const; // Return a reference to the attack and buff component. Combat& get_combat(); + // Dordo Story's monster spirit (when this player came in as one) + Spirit& get_spirit(); // Return a pointer to a character, possibly the player. Optional get_character(int32_t cid); @@ -119,6 +124,7 @@ namespace jrc Camera camera; Physics physics; Player player; + Spirit spirit; Optional playable; State state; diff --git a/src/client/Graphics/Animation.cpp b/src/client/Graphics/Animation.cpp index 0f6b383..5128037 100644 --- a/src/client/Graphics/Animation.cpp +++ b/src/client/Graphics/Animation.cpp @@ -48,8 +48,10 @@ namespace jrc } else if (hasa1) { + // (only where it fades to: it starts fully there, like the original; { a1, a1 } drew every such + // frame, a weapon's swipe among them, already faded out) uint8_t a1 = src["a1"]; - opacities = { a1, a1 }; + opacities = { 255, a1 }; } else { diff --git a/src/client/Graphics/GraphicsGL.cpp b/src/client/Graphics/GraphicsGL.cpp index 824028a..78c8ec7 100644 --- a/src/client/Graphics/GraphicsGL.cpp +++ b/src/client/Graphics/GraphicsGL.cpp @@ -22,6 +22,10 @@ #include "../Console.h" #include +#ifdef MS_PLATFORM_WASM +#include +#include +#endif #include namespace jrc @@ -74,8 +78,15 @@ namespace jrc } GLuint fs = glCreateShader(GL_FRAGMENT_SHADER); + // Texture positions arrive in atlas texels (up to 8192): a 16-bit mediump float can't hold those exactly + // (only every 4th texel past 4096), which on GPUs that honour mediump samples the wrong texels: chunky + // sprites, garbled text, seams. High precision wherever the GPU has it. const char *fs_source = + "#ifdef GL_FRAGMENT_PRECISION_HIGH\n" + "precision highp float;\n" + "#else\n" "precision mediump float;\n" + "#endif\n" "varying vec2 texpos;" "varying vec4 colormod;" "uniform sampler2D texture;" @@ -143,6 +154,15 @@ namespace jrc GL_RGBA, GL_UNSIGNED_BYTE, nullptr ); +#ifdef MS_PLATFORM_WASM + // The page's handle on the TV corner (dordo.js Module.dordoTv paints it): the context, the atlas (the only + // texture the game ever binds) and the corner's first row. Slots: the big panel's picture TVADW x TVADH at + // (0, row), the strip's TVMSGW x TVMSGH at (TVADW, row + TVADH - TVMSGH), a monster spirit's ball TVBALL + // square at (TVADW + TVMSGW, row). (No commas inside EM_ASM's body.) + EM_ASM({ Module.dordoGL = GLctx; Module.dordoAtlas = GL.textures[$0]; }, atlas); + EM_ASM({ Module.dordoTvRow = $0; }, PACKH); +#endif + fontborder.set_y(1); std::string font_normal = Setting().get().load(); @@ -382,7 +402,8 @@ namespace jrc { size_t used = ATLASW * border.y() + border.x() * yrange.second(); double usedpercent = static_cast(used) / (ATLASW * ATLASH); - if (usedpercent > 80.0) + // (a fraction: compared with 80.0 it was never true, so the atlas never emptied and filled up for good) + if (usedpercent > 0.8) { clearinternal(); } @@ -470,7 +491,7 @@ namespace jrc { border.set_x(0); border.shift_y(yrange.second()); - if (border.y() + h > ATLASH) + if (border.y() + h > PACKH) { clearinternal(); } @@ -557,7 +578,20 @@ namespace jrc return; } - quads.emplace_back(rect.l(), rect.r(), rect.t(), rect.b(), getoffset(bmp), color, angle); + // A bitmap that couldn't be read gets the null offset, which the shader would paint as a solid white box + const Offset& offset = getoffset(bmp); + if (&offset == &nulloffset) + { + return; + } + + quads.emplace_back(rect.l(), rect.r(), rect.t(), rect.b(), offset, color, angle); + // (only turned art: stretched art, HP bars and gauges, zooming effects, sample the same game pixels the + // original 800x600 game did, so they stay in the small picture) + if (angle != 0.0f) + { + mark_patch(quads.back()); + } } void GraphicsGL::draw_clipped(const nl::bitmap& bmp, const Rectangle& rect, @@ -574,6 +608,30 @@ namespace jrc quads.emplace_back(rect.l(), rect.r(), top, bottom, offset, color, 0.0f); } + bool GraphicsGL::draw_tv(TvSlot slot, const Rectangle& rect, float opacity) + { +#ifdef MS_PLATFORM_WASM + if (locked || !rect.overlaps(screen())) return false; + bool ready = EM_ASM_INT({ + var tv = Module.dordoTv; + if (!tv) return 0; + if ($0 < 2) tv.seen = Date.now(); + return tv.ready[$0] ? 1 : 0; + }, static_cast(slot)); + if (!ready) return false; + Offset offset = slot == TV_AD ? Offset(0, PACKH, TVADW, TVADH) + : slot == TV_MSG ? Offset(TVADW, PACKH + TVADH - TVMSGH, TVMSGW, TVMSGH) + : slot == TV_SPIRIT ? Offset(TVADW + TVMSGW, PACKH, TVBALL, TVBALL) + : slot == TV_WORLD ? Offset(TVADW + TVMSGW + TVBALL, PACKH, TVWORLD, TVWORLD) + : Offset(TVADW + TVMSGW + TVBALL + TVWORLD, PACKH, TVQR, TVQR); + quads.emplace_back(rect.l(), rect.r(), rect.t(), rect.b(), offset, Color{ 1.0f, 1.0f, 1.0f, opacity }, 0.0f); + mark_patch(quads.back()); + return true; +#else + return false; +#endif + } + Text::Layout GraphicsGL::createlayout(const std::string& text, Text::Font id, Text::Alignment alignment, int16_t maxwidth, bool formatted) { @@ -949,9 +1007,6 @@ namespace jrc quads.emplace_back(screen_rect.l(), screen_rect.r(), screen_rect.t(), screen_rect.b(), nulloffset, color, 0.0f); } - glClearColor(1.0, 1.0, 1.0, 1.0); - glClear(GL_COLOR_BUFFER_BIT); - GLsizei csize = static_cast(quads.size() * sizeof(Quad)); glEnableVertexAttribArray(attribute_coord); glEnableVertexAttribArray(attribute_color); @@ -960,25 +1015,118 @@ namespace jrc glVertexAttribPointer(attribute_coord, 4, GL_SHORT, GL_FALSE, sizeof(Quad::Vertex), 0); glVertexAttribPointer(attribute_color, 4, GL_FLOAT, GL_FALSE, sizeof(Quad::Vertex), (const void*)8); #ifdef MS_PLATFORM_WASM - // Initialize indices for GL_TRIANGLES (2 triangles per quad, 6 indices per quad) - std::vector indices; - indices.reserve(quads.size() * 6); - for (size_t i = 0; i < quads.size(); ++i) + // (two triangles a quad; the same every frame, so only ever grown) + if (indices.size() < quads.size() * 6) + { + size_t had = indices.size() / 6; + for (size_t i = had; i < quads.size(); ++i) + { + GLushort base = static_cast(i * 4); + indices.insert(indices.end(), { GLushort(base), GLushort(base + 1), GLushort(base + 2), + GLushort(base), GLushort(base + 2), GLushort(base + 3) }); + } + } + + // The page may give the canvas more pixels than the game's 800x600 (a whole multiple of it, for a sharp + // picture on big screens). The shader still works in game coordinates, so filling whatever the drawing + // buffer is right now draws the same scene at that resolution. + int buffer_width = 0; + int buffer_height = 0; + emscripten_webgl_get_drawing_buffer_size(emscripten_webgl_get_current_context(), &buffer_width, &buffer_height); + GLsizei vw = Constants::viewwidth(), vh = Constants::viewheight(); + GLsizei k = vw > 0 ? buffer_width / vw : 0; + int64_t patch_area = 0; + for (const Patch& p : patches) + { + patch_area += int64_t(p.r - p.l) * (p.b - p.t); + } + // (whole multiples only; and with lots of patches the full-size draw is cheaper anyway) + bool small = scene_ok && k >= 2 && buffer_width == vw * k && buffer_height == vh * k + && patches.size() <= 64 && patch_area * 3 < int64_t(vw) * vh; + + if (small && (scene_w != vw || scene_h != vh || !scene_fbo)) { - GLushort base = static_cast(i * 4); - indices.push_back(base + 0); - indices.push_back(base + 1); - indices.push_back(base + 2); - indices.push_back(base + 0); - indices.push_back(base + 2); - indices.push_back(base + 3); + if (!scene_fbo) + { + glGenFramebuffers(1, &scene_fbo); + glGenRenderbuffers(1, &scene_rb); + } + glBindRenderbuffer(GL_RENDERBUFFER, scene_rb); + glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, vw, vh); + glBindFramebuffer(GL_FRAMEBUFFER, scene_fbo); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, scene_rb); + scene_ok = glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE; + glBindFramebuffer(GL_FRAMEBUFFER, 0); + scene_w = vw; + scene_h = vh; + small = scene_ok; } glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLushort), indices.data(), GL_STREAM_DRAW); - glDrawElements(GL_TRIANGLES, static_cast(indices.size()), GL_UNSIGNED_SHORT, 0); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, quads.size() * 6 * sizeof(GLushort), indices.data(), GL_STREAM_DRAW); + + if (small) + { + glBindFramebuffer(GL_FRAMEBUFFER, scene_fbo); + glViewport(0, 0, vw, vh); + } + else if (buffer_width > 0 && buffer_height > 0) + { + glViewport(0, 0, buffer_width, buffer_height); + } + glClearColor(1.0, 1.0, 1.0, 1.0); + glClear(GL_COLOR_BUFFER_BIT); + glDrawElements(GL_TRIANGLES, static_cast(quads.size() * 6), GL_UNSIGNED_SHORT, 0); + + if (small) + { + glBindFramebuffer(GL_READ_FRAMEBUFFER, scene_fbo); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + glBlitFramebuffer(0, 0, vw, vh, 0, 0, buffer_width, buffer_height, GL_COLOR_BUFFER_BIT, GL_NEAREST); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + if (glGetError() != GL_NO_ERROR) + { + // (this browser won't stretch it: from the next frame on, everything is drawn at full size again) + scene_ok = false; + } + glViewport(0, 0, buffer_width, buffer_height); + + // each patch again at full size: cleared, then every quad touching it, in order + if (!patches.empty()) + { + glEnable(GL_SCISSOR_TEST); + for (const Patch& p : patches) + { + patch_indices.clear(); + for (size_t i = 0; i < quads.size(); ++i) + { + const Quad::Vertex* v = quads[i].vertices; + GLshort l = std::min(std::min(v[0].x, v[1].x), std::min(v[2].x, v[3].x)); + GLshort r = std::max(std::max(v[0].x, v[1].x), std::max(v[2].x, v[3].x)); + GLshort t = std::min(std::min(v[0].y, v[1].y), std::min(v[2].y, v[3].y)); + GLshort b = std::max(std::max(v[0].y, v[1].y), std::max(v[2].y, v[3].y)); + if (r <= p.l || l >= p.r || b <= p.t || t >= p.b) + continue; + patch_indices.insert(patch_indices.end(), indices.begin() + i * 6, indices.begin() + i * 6 + 6); + } + // (game rows run down from -VIEWYOFFSET; GL's run up from the bottom) + GLint x0 = std::max(0, p.l) * k, x1 = std::min(vw, p.r) * k; + GLint y0 = std::max(0, p.t + Constants::VIEWYOFFSET) * k; + GLint y1 = std::min(vh, p.b + Constants::VIEWYOFFSET) * k; + if (x1 <= x0 || y1 <= y0 || patch_indices.empty()) + continue; + glScissor(x0, buffer_height - y1, x1 - x0, y1 - y0); + glClear(GL_COLOR_BUFFER_BIT); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, patch_indices.size() * sizeof(GLushort), patch_indices.data(), GL_STREAM_DRAW); + glDrawElements(GL_TRIANGLES, static_cast(patch_indices.size()), GL_UNSIGNED_SHORT, 0); + } + glDisable(GL_SCISSOR_TEST); + } + } glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); #else + glClearColor(1.0, 1.0, 1.0, 1.0); + glClear(GL_COLOR_BUFFER_BIT); GLsizei fsize = static_cast(quads.size() * Quad::LENGTH); glDrawArrays(GL_QUADS, 0, fsize); #endif @@ -994,11 +1142,34 @@ namespace jrc } + void GraphicsGL::mark_patch(const Quad& quad) + { + const Quad::Vertex* v = quad.vertices; + // (a pixel round it, for a turned edge's rounding) + Patch p = { + static_cast(std::min(std::min(v[0].x, v[1].x), std::min(v[2].x, v[3].x)) - 1), + static_cast(std::max(std::max(v[0].x, v[1].x), std::max(v[2].x, v[3].x)) + 1), + static_cast(std::min(std::min(v[0].y, v[1].y), std::min(v[2].y, v[3].y)) - 1), + static_cast(std::max(std::max(v[0].y, v[1].y), std::max(v[2].y, v[3].y)) + 1) + }; + // (overlapping or touching ones become one: a pile of spinning drops is one patch, not twenty) + for (Patch& q : patches) + { + if (p.l <= q.r && q.l <= p.r && p.t <= q.b && q.t <= p.b) + { + q = { std::min(p.l, q.l), std::max(p.r, q.r), std::min(p.t, q.t), std::max(p.b, q.b) }; + return; + } + } + patches.push_back(p); + } + void GraphicsGL::clearscene() { if (!locked) { quads.clear(); + patches.clear(); } } } diff --git a/src/client/Graphics/GraphicsGL.h b/src/client/Graphics/GraphicsGL.h index 35c5558..52f2146 100644 --- a/src/client/Graphics/GraphicsGL.h +++ b/src/client/Graphics/GraphicsGL.h @@ -69,6 +69,15 @@ namespace jrc void drawtext(const DrawArgument& args, const std::string& text, const Text::Layout& layout, Text::Font font, Text::Color color, Text::Background back, const Range* vertical = nullptr); + // The MapleTV screens (Dordo Story): the page paints Fluff Net feed pictures into a corner of the atlas + // reserved for them (TV_AD: the big panel, TV_MSG: the strip above it, both at twice the game's pixels). + // Draws that slot over rect, if the page has put something there yet; says whether it did. + // (TV_SPIRIT: a monster spirit's glass ball, 128 x 128, also painted by the page) + // (TV_WORLD: the world's own icon, Dordo Story's chicken, 64 x 64, painted by the page) + // (TV_QR: the live stream link's QR code, 128 x 128, painted by the page) + enum TvSlot { TV_AD, TV_MSG, TV_SPIRIT, TV_WORLD, TV_QR }; + bool draw_tv(TvSlot slot, const Rectangle& rect, float opacity); + // Draw a rectangle filled with the specified color. void drawrectangle(int16_t x, int16_t y, int16_t w, int16_t h, float r, float g, float b, float a); // Fill the screen with the specified color. @@ -261,10 +270,29 @@ namespace jrc static const GLshort ATLASW = 8192; static const GLshort ATLASH = 8192; static const GLshort MINLOSIZE = 32; + // (the TV corner: the bottom TVROWS rows of the atlas, kept out of the packing) + static const GLshort TVADW = 480, TVADH = 360, TVMSGW = 480, TVMSGH = 180, TVBALL = 128, TVWORLD = 64, TVQR = 128; + static const GLshort TVROWS = 360; + static const GLshort PACKH = ATLASH - TVROWS; bool locked; std::vector quads; + // Dordo Story: the canvas is usually a whole multiple of the game's 800x600 (2x, 3x…), and drawing every + // layer at that size is most of what a busy map costs. So the scene is drawn once at 800x600 off-screen + // and stretched up pixel for pixel, which looks the same for art drawn at its own size. Art that isn't + // (turned, like a spinning drop, or squeezed, like the TV's picture) marks its patch, and each patch is + // drawn again at full size, everything in it in the same order, so it looks exactly as before. + struct Patch { GLshort l, r, t, b; }; + std::vector patches; + std::vector indices; + std::vector patch_indices; + GLuint scene_fbo = 0; + GLuint scene_rb = 0; + GLsizei scene_w = 0; + GLsizei scene_h = 0; + bool scene_ok = true; + void mark_patch(const Quad& quad); GLuint vbo; GLuint ibo; GLuint atlas; diff --git a/src/client/Graphics/Texture.h b/src/client/Graphics/Texture.h index 1f4e54b..611ac08 100644 --- a/src/client/Graphics/Texture.h +++ b/src/client/Graphics/Texture.h @@ -40,6 +40,8 @@ namespace jrc int16_t height() const; Point get_origin() const; Point get_dimensions() const; + // (its pixels, BGRA, for handing to the page) + const nl::bitmap& get_bitmap() const { return bitmap; } private: nl::bitmap bitmap; diff --git a/src/client/IO/Components/NpcDialogLayout.h b/src/client/IO/Components/NpcDialogLayout.h index a5d6faf..18da991 100644 --- a/src/client/IO/Components/NpcDialogLayout.h +++ b/src/client/IO/Components/NpcDialogLayout.h @@ -7,7 +7,12 @@ namespace jrc { struct NpcDialogLayout { - static constexpr int16_t PADDING = 16; + // The white text field isn't just the middle tiles: it starts WHITE_TOP rows into the top piece (under its + // grey rule) and runs WHITE_BELOW rows into the bottom piece (above the button strip's rule). Text sits + // PADDING inside that field, the same margin top and bottom. + static constexpr int16_t WHITE_TOP = 15; + static constexpr int16_t WHITE_BELOW = 9; + static constexpr int16_t PADDING = 8; int16_t tiles; int16_t text_top; int16_t visible_height; @@ -17,14 +22,17 @@ namespace jrc int16_t tile_height, int16_t bottom_height, int16_t screen_height) { tile_height = std::max(1, tile_height); - const int32_t required = std::max(8, (content_height + 2 * PADDING + tile_height - 1) / tile_height); + const int16_t text_top = std::min(WHITE_TOP, top_height) + PADDING; + // field rows outside the tiles, less the margins: what the tiles themselves don't have to hold + const int32_t extra = (top_height - std::min(WHITE_TOP, top_height)) + + std::min(WHITE_BELOW, bottom_height) - 2 * PADDING; + const int32_t required = std::max(8, (content_height - extra + tile_height - 1) / tile_height); const int32_t capacity = std::max(1, (screen_height - top_height - bottom_height - 40) / tile_height); const int16_t tiles = static_cast(std::min(required, capacity)); - const int16_t visible = std::max(1, tiles * tile_height - 2 * PADDING); + const int16_t visible = static_cast(std::max(1, tiles * tile_height + extra)); // Text starts inside the same viewport that clips it. Centering // overflowing content would make its first lines unreachable. - return {tiles, static_cast(top_height + PADDING), visible, - std::max(0, content_height - visible)}; + return {tiles, text_top, visible, std::max(0, content_height - visible)}; } struct Navigation { bool prev; bool next; bool ok; }; diff --git a/src/client/IO/Components/QuestText.cpp b/src/client/IO/Components/QuestText.cpp index 4dd3763..add65ab 100644 --- a/src/client/IO/Components/QuestText.cpp +++ b/src/client/IO/Components/QuestText.cpp @@ -56,8 +56,18 @@ namespace jrc::QuestText continue; } const char token = source[i + 1]; + // Colour and font switches take nothing after them: "#r1#k" is red, a 1, then back to black (read as a + // reference, "#r1#" swallowed the 1 and left a stray "k": "1 / k" in a quest's item count) + if (token == 'b' || token == 'r' || token == 'k' || token == 'd' || token == 'e' || token == 'n' || + token == 'g') + { + result.append(source, i, 2); + i += 2; + continue; + } size_t end = source.find('#', i + 2); - if (token == 'h' && end != std::string::npos) + // (only "#h#" or "#h #" is the player's name) + if (token == 'h' && end != std::string::npos && (end == i + 2 || (end == i + 3 && source[i + 2] == ' '))) { result += player; i = end + 1; diff --git a/src/client/IO/Components/ScrollingNotice.cpp b/src/client/IO/Components/ScrollingNotice.cpp index 5eab78b..1980121 100644 --- a/src/client/IO/Components/ScrollingNotice.cpp +++ b/src/client/IO/Components/ScrollingNotice.cpp @@ -35,6 +35,8 @@ namespace jrc notice.change_text(n); xpos.set(Constants::viewwidth()); active = n.size() > 0; + opacity = 1.0f; + fading = false; } void ScrollingNotice::draw(float alpha) const @@ -43,8 +45,8 @@ namespace jrc { int16_t interx = static_cast(std::round(xpos.get(alpha))); auto position = Point(interx, -Constants::VIEWYOFFSET - 2); - background.draw(backposition); - notice.draw(position); + background.draw(DrawArgument(backposition, opacity)); + notice.draw(DrawArgument(position, opacity)); } } @@ -59,7 +61,19 @@ namespace jrc auto xmin = static_cast(-notice.width()); if (xpos.last() < xmin) { + // once across is enough: the original looped it forever xpos.set(Constants::viewwidth()); + fading = true; + } + + if (fading) + { + opacity -= FADE_STEP; + if (opacity <= 0.0f) + { + opacity = 0.0f; + active = false; + } } } } diff --git a/src/client/IO/Components/ScrollingNotice.h b/src/client/IO/Components/ScrollingNotice.h index 43e7304..856a439 100644 --- a/src/client/IO/Components/ScrollingNotice.h +++ b/src/client/IO/Components/ScrollingNotice.h @@ -40,5 +40,9 @@ namespace jrc Text notice; Linear xpos; bool active; + // after one pass the band fades out (about 1.3 s of 8 ms updates) + float opacity = 1.0f; + bool fading = false; + static constexpr float FADE_STEP = 0.006f; }; } diff --git a/src/client/IO/Components/Textfield.h b/src/client/IO/Components/Textfield.h index f83ef70..86a648c 100644 --- a/src/client/IO/Components/Textfield.h +++ b/src/client/IO/Components/Textfield.h @@ -64,6 +64,10 @@ namespace jrc State get_state() const; Rectangle get_bounds() const; const std::string& get_text() const; + // (phones: the page's typing bar) the longest it takes (0: as wide as it is), a password's, Enter means something + size_t get_limit() const { return limit; } + bool is_secret() const { return crypt > 0; } + bool has_return() const { return static_cast(onreturn) || callbacks.count(KeyAction::RETURN) > 0; } private: void modifytext(const std::string&); diff --git a/src/client/IO/Keyboard.cpp b/src/client/IO/Keyboard.cpp index 587bcc9..d9f8738 100644 --- a/src/client/IO/Keyboard.cpp +++ b/src/client/IO/Keyboard.cpp @@ -67,6 +67,11 @@ namespace jrc textactions[GLFW_KEY_TAB] = KeyAction::TAB; } + int32_t Keyboard::glfw_code(uint8_t maplekey) + { + return maplekey < 90 ? Keytable[maplekey] : 0; + } + int32_t Keyboard::shiftcode() const { return GLFW_KEY_LEFT_SHIFT; diff --git a/src/client/IO/Keyboard.h b/src/client/IO/Keyboard.h index a6bf5bf..e04e8f0 100644 --- a/src/client/IO/Keyboard.h +++ b/src/client/IO/Keyboard.h @@ -56,6 +56,9 @@ namespace jrc std::map get_maplekeys() const; Mapping get_maple_mapping(int32_t keycode) const; + // The GLFW key a Maple key code stands for (0 if none) + static int32_t glfw_code(uint8_t maplekey); + int32_t shiftcode() const; int32_t ctrlcode() const; KeyAction::Id get_ctrl_action(int32_t keycode) const; diff --git a/src/client/IO/UI.cpp b/src/client/IO/UI.cpp index 8e0213b..8c4b5cc 100644 --- a/src/client/IO/UI.cpp +++ b/src/client/IO/UI.cpp @@ -17,16 +17,24 @@ ////////////////////////////////////////////////////////////////////////////// #include "UI.h" +#include "../Gameplay/Stage.h" #include "UIStateLogin.h" #include "UIStateGame.h" #include "UITypes/UIWorldMap.h" +#include "UITypes/UINpcTalk.h" #include "Window.h" #include "../Audio/Audio.h" #include "../Console.h" #include "../Configuration.h" #include + +#ifdef MS_PLATFORM_WASM +#include +#endif +#include #include +#include namespace jrc { @@ -49,15 +57,76 @@ namespace jrc state->draw(alpha, cursor.get_position()); scrollingnotice.draw(alpha); - cursor.draw(alpha); + if (!(state && Stage::get().get_spirit().active())) + { + cursor.draw(alpha); // (a monster spirit has no pointer) + } + } + + namespace + { + // (the page's typing bar calls in from outside the game's step; like input, it's done at the next one) + std::vector>& page_calls() + { + static std::vector> calls; + return calls; + } } void UI::update() { + std::vector> calls; + calls.swap(page_calls()); + for (auto& call : calls) + { + call(); + } + state->update(); scrollingnotice.update(); cursor.update(); + +#ifdef MS_PLATFORM_WASM + // Phones have no keys: whenever a text box gets the focus (a name, chat, a number) or loses it, the page is + // told, and its typing bar (the phone's own keyboard) comes up or goes away. + const Textfield* now = focusedtextfield ? focusedtextfield.get() : nullptr; + if (now != told_textfield || (now && now->get_text() != told_text)) + { + bool fresh = now != told_textfield; + told_textfield = now; + told_text = now ? now->get_text() : ""; + if (now) + EM_ASM({ if (Module.onTextField) Module.onTextField(1, UTF8ToString($0), $1, $2, $3, $4); }, + told_text.c_str(), static_cast(now->get_limit()), now->is_secret() ? 1 : 0, + now->has_return() ? 1 : 0, fresh ? 1 : 0); + else + EM_ASM({ if (Module.onTextField) Module.onTextField(0, "", 0, 0, 0, 1); }); + } +#endif + } + + void UI::type_text(const std::string& text) + { + if (!focusedtextfield) + return; + std::string t = text; + size_t limit = focusedtextfield->get_limit(); + if (limit > 0 && t.size() > limit) + t.resize(limit); + focusedtextfield->change_text(t); + told_text = focusedtextfield->get_text(); // (the page has it already) + } + + void UI::type_enter() + { + if (focusedtextfield) + focusedtextfield->send_key(KeyType::ACTION, KeyAction::RETURN, true); + } + + void UI::type_done() + { + remove_textfield(); } void UI::enable() @@ -137,6 +206,11 @@ namespace jrc } } + Point UI::snap_tap(Point pos) + { + return state->snap_tap(pos); + } + void UI::send_cursor(Point pos) { send_cursor(pos, cursor.get_state()); @@ -234,6 +308,31 @@ namespace jrc return; } + // Y / N press Yes / No in an NPC question, and Enter / Space press Next or OK, whatever the key layout says + // (not while typing) + if (pressed && !focusedtextfield) + { + auto npctalk = get_element(); + bool answered = false; + if (npctalk && (keycode == GLFW_KEY_Y || keycode == GLFW_KEY_N)) + { + answered = npctalk->send_answer_key(keycode == GLFW_KEY_Y); + } + else if (npctalk && (keycode == GLFW_KEY_UP || keycode == GLFW_KEY_DOWN)) + { + answered = npctalk->send_selection_key(keycode); + } + else if (npctalk && (keycode == GLFW_KEY_ENTER || keycode == GLFW_KEY_KP_ENTER || keycode == GLFW_KEY_SPACE)) + { + answered = npctalk->send_selection_key(keycode) || npctalk->send_confirm_key(); + } + if (answered) + { + is_key_down[keycode] = pressed; + return; + } + } + if (focusedtextfield) { bool ctrl = @@ -328,6 +427,12 @@ namespace jrc state->drag_icon(icon); } + bool UI::is_held(int32_t keycode) const + { + auto iter = is_key_down.find(keycode); + return iter != is_key_down.end() && iter->second; + } + Keyboard& UI::get_keyboard() { return keyboard; @@ -376,3 +481,70 @@ namespace jrc state->remove(type); } } + +#ifdef MS_PLATFORM_WASM +#include + +// The page's taps (phones): game coordinates in, the spot to click out (x << 16 | y). +extern "C" EMSCRIPTEN_KEEPALIVE int dordo_snap_tap(int x, int y) +{ + jrc::Point to = jrc::UI::get().snap_tap({ static_cast(x), static_cast(y) }); + return (static_cast(static_cast(to.x())) << 16) | static_cast(to.y()); +} +#endif + +#ifdef MS_PLATFORM_WASM +// The page's typing bar (phones): the text so far, Enter, and done. +extern "C" EMSCRIPTEN_KEEPALIVE void dordo_type_text(const char* text) +{ + std::string typed = text ? text : ""; + jrc::page_calls().push_back([typed]() { jrc::UI::get().type_text(typed); }); +} + +extern "C" EMSCRIPTEN_KEEPALIVE void dordo_type_enter() +{ + jrc::page_calls().push_back([]() { jrc::UI::get().type_enter(); }); +} + +extern "C" EMSCRIPTEN_KEEPALIVE void dordo_type_done() +{ + jrc::page_calls().push_back([]() { jrc::UI::get().type_done(); }); +} +#endif + +#ifdef MS_PLATFORM_WASM +#include "UITypes/UIStatusBar.h" + +#include "UITypes/UIStream.h" + +// The live stream's window: up with the link and how many watch, or (an empty link) gone. +extern "C" EMSCRIPTEN_KEEPALIVE void dordo_stream_info(const char* link, int watching) +{ + std::string to = link ? link : ""; + jrc::page_calls().push_back([to, watching]() { + if (to.empty()) + { + jrc::UI::get().remove(jrc::UIElement::STREAM); + return; + } + auto window = jrc::UI::get().get_element(); + if (!window) + { + jrc::UI::get().emplace(); + window = jrc::UI::get().get_element(); + } + if (window) + window->set_info(to, watching); + }); +} + +// A line from our live stream's chat (a watcher, or what we said there): in the chat box in the stream's colour. +extern "C" EMSCRIPTEN_KEEPALIVE void dordo_stream_chat(const char* line) +{ + std::string said = line ? line : ""; + jrc::page_calls().push_back([said]() { + if (auto statusbar = jrc::UI::get().get_element()) + statusbar->send_chatline(said, jrc::UIChatbar::STREAM); + }); +} +#endif diff --git a/src/client/IO/UI.h b/src/client/IO/UI.h index b1c31d1..e17f7d1 100644 --- a/src/client/IO/UI.h +++ b/src/client/IO/UI.h @@ -56,6 +56,8 @@ namespace jrc bool not_quitted() const; void send_cursor(Point pos); + // (phones) where a tap at pos is meant to land (see UIState::snap_tap) + Point snap_tap(Point pos); void send_cursor(bool pressed); void send_cursor(Point cursorpos, Cursor::State cursorstate); void send_focus(int focused); @@ -73,6 +75,8 @@ namespace jrc void remove_textfield(); void drag_icon(Icon* icon); Keyboard& get_keyboard(); + // Whether a key (GLFW code) is held down right now, from any source (keyboard, controller, phone buttons) + bool is_held(int32_t keycode) const; uint64_t get_cursor_press_id() const; void add_keymapping(uint8_t no, uint8_t type, int32_t action); @@ -99,6 +103,15 @@ namespace jrc ScrollingNotice scrollingnotice; Optional focusedtextfield; + // (phones) the text box the page's typing bar was last told about, and its text then + const Textfield* told_textfield = nullptr; + std::string told_text; + public: + // the page's typing bar: what's typed so far, Enter, and "done" (lets go of the box) + void type_text(const std::string& text); + void type_enter(); + void type_done(); + private: std::unordered_map is_key_down; uint64_t cursor_press_id; diff --git a/src/client/IO/UIDragElement.h b/src/client/IO/UIDragElement.h index 93ebcf2..61d3c95 100644 --- a/src/client/IO/UIDragElement.h +++ b/src/client/IO/UIDragElement.h @@ -20,6 +20,8 @@ namespace jrc void save_position() override { Setting::get().save(position); + // (kept for next time: a dragged window starts where it was left) + Configuration::get().save(); } }; } diff --git a/src/client/IO/UIElement.cpp b/src/client/IO/UIElement.cpp index c682b83..023b263 100644 --- a/src/client/IO/UIElement.cpp +++ b/src/client/IO/UIElement.cpp @@ -55,7 +55,7 @@ namespace jrc "CHARCREATION", "SOFTKEYBOARD", "STATUSMESSENGER", "STATUSBAR", "BUFFLIST", "NOTICE", "NPCTALK", "SHOP", "STORAGE", "STATSINFO", "ITEMINVENTORY", "EQUIPINVENTORY", "SKILLBOOK", "KEYCONFIG", "PARTY", "MINIMAP", "WORLDMAP", - "QUESTLOG", "QUESTTRACKER", "CASHSHOP", "CASHDIALOG" + "QUESTLOG", "QUESTTRACKER", "CASHSHOP", "CASHDIALOG", "QUICKSLOT", "STREAM" }; static_assert(sizeof(windows) / sizeof(*windows) == NUM_TYPES); std::cerr << "[UI layout] " << windows[type] << ' ' << kinds[static_cast(kind)] @@ -130,6 +130,18 @@ namespace jrc void UIElement::rightclick(Point) {} + void UIElement::tap_targets(std::vector>& out) const + { + for (auto& iter : buttons) + { + const Button* button = iter.second.get(); + if (button && button->is_active() && button->get_state() != Button::DISABLED) + { + out.push_back(button->bounds(position)); + } + } + } + bool UIElement::is_in_range(Point cursorpos) const { auto bounds = Rectangle(position, position + dimension); @@ -162,6 +174,17 @@ namespace jrc return { Cursor::CLICKING, true }; } + // (the button under the cursor, if any: every other one drops its highlight first, or sliding straight from + // one button to the next, like along a row of tabs, left them all lit) + for (auto& btit : buttons) + { + bool under = btit.second->is_active() && btit.second->bounds(position).contains(pos); + if (!under && btit.second->get_state() == Button::MOUSEOVER) + { + btit.second->set_state(Button::NORMAL); + } + } + for (auto& btit : buttons) { if (btit.second->is_active() && btit.second->bounds(position).contains(pos)) diff --git a/src/client/IO/UIElement.h b/src/client/IO/UIElement.h index 4936e9c..22e3d06 100644 --- a/src/client/IO/UIElement.h +++ b/src/client/IO/UIElement.h @@ -81,6 +81,8 @@ namespace jrc QUESTTRACKER, CASHSHOP, CASHDIALOG, + QUICKSLOT, + STREAM, NUM_TYPES }; @@ -104,6 +106,9 @@ namespace jrc virtual void doubleclick(Point cursorpos); virtual void rightclick(Point cursorpos); virtual bool is_in_range(Point cursorpos) const; + // (Dordo Story, phones) everything in this window a tap can mean, in screen space: its usable buttons, and + // whatever else a window adds (an NPC's list of answers). A tap near one lands on it. + virtual void tap_targets(std::vector>& out) const; virtual bool remove_cursor(bool clicked, Point cursorpos); virtual CursorResult send_cursor(bool clicked, Point cursorpos); virtual void send_scroll(double yoffset); diff --git a/src/client/IO/UIState.h b/src/client/IO/UIState.h index c60cb43..4aba688 100644 --- a/src/client/IO/UIState.h +++ b/src/client/IO/UIState.h @@ -63,6 +63,14 @@ namespace jrc virtual UIElement* get(UIElement::Type type) = 0; virtual UIElement* get_front(const std::list& types) = 0; virtual UIElement* get_front(Point pos) = 0; + + // (phones) where a tap at pos is meant to land: on a button, an NPC's answer or an NPC that's close by + // (inside a window, only that window's things), else pos itself + virtual Point snap_tap(Point pos); + static constexpr int16_t TAP_REACH = 26; + static constexpr int16_t NPC_TAP_REACH = 40; + // pos, or the nearest point of the nearest target within reach (pos already on one: pos) + static Point snap_to(const std::vector>& targets, Point pos, int16_t reach); }; class UIStateNull : public UIState diff --git a/src/client/IO/UIStateGame.cpp b/src/client/IO/UIStateGame.cpp index 6445419..fab1601 100644 --- a/src/client/IO/UIStateGame.cpp +++ b/src/client/IO/UIStateGame.cpp @@ -16,6 +16,8 @@ // along with this program. If not, see . // ////////////////////////////////////////////////////////////////////////////// #include "UIStateGame.h" +#include "UITypes/UIQuickSlot.h" +#include "UITypes/UINotice.h" #include "UITypes/UICashShop.h" #include "../Gameplay/CashShop.h" #include "UI.h" @@ -91,6 +93,7 @@ namespace jrc emplace(); emplace(stats); + emplace(); emplace(stats); emplace(); emplace( @@ -218,7 +221,8 @@ namespace jrc switch (action) { case KeyAction::CASHSHOP: - CashShop::get().enter(); + // (the shop isn't ready for frens yet) + emplace("Not implemented yet", []() {}); break; case KeyAction::CHARSTATS: emplace( @@ -658,4 +662,30 @@ namespace jrc } return nullptr; } + + Point UIStateGame::snap_tap(Point pos) + { + std::vector> targets; + // (a tap inside a window means something in that window) + if (UIElement* front = get_front(pos)) + { + front->tap_targets(targets); + return snap_to(targets, pos, TAP_REACH); + } + for (auto type : elementorder) + { + auto& element = elements[type]; + if (element && element->is_active()) + element->tap_targets(targets); + } + // the map's NPCs, a little more forgiving (they move about) + Point to = snap_to(targets, pos, TAP_REACH); + if (to == pos) + { + std::vector> npcs; + Stage::get().npc_tap_targets(npcs); + to = snap_to(npcs, pos, NPC_TAP_REACH); + } + return to; + } } diff --git a/src/client/IO/UIStateGame.h b/src/client/IO/UIStateGame.h index 853dd9f..65f76e3 100644 --- a/src/client/IO/UIStateGame.h +++ b/src/client/IO/UIStateGame.h @@ -63,6 +63,7 @@ namespace jrc UIElement* get(UIElement::Type type) override; UIElement* get_front(const std::list& types) override; UIElement* get_front(Point pos) override; + Point snap_tap(Point pos) override; private: void clear_cursors(bool clicked, Point pos, UIElement::Type except); diff --git a/src/client/IO/UIStateLogin.cpp b/src/client/IO/UIStateLogin.cpp index 7f1aa89..a472f60 100644 --- a/src/client/IO/UIStateLogin.cpp +++ b/src/client/IO/UIStateLogin.cpp @@ -287,4 +287,51 @@ namespace jrc } return nullptr; } + + Point UIState::snap_tap(Point pos) + { + return pos; + } + + Point UIState::snap_to(const std::vector>& targets, Point pos, int16_t reach) + { + int32_t best = static_cast(reach) * reach + 1; + Point to = pos; + for (const auto& r : targets) + { + int16_t l = std::min(r.l(), r.r()), rr = std::max(r.l(), r.r()); + int16_t t = std::min(r.t(), r.b()), b = std::max(r.t(), r.b()); + if (rr - l < 2 || b - t < 2) + continue; + if (pos.x() >= l && pos.x() < rr && pos.y() >= t && pos.y() < b) + return pos; // (right on one) + // the nearest point a little way inside it + int16_t inset_x = std::min(3, (rr - l) / 2), inset_y = std::min(3, (b - t) / 2); + int16_t x = std::clamp(pos.x(), l + inset_x, rr - 1 - inset_x); + int16_t y = std::clamp(pos.y(), t + inset_y, b - 1 - inset_y); + int32_t dx = x - pos.x(), dy = y - pos.y(); + if (dx * dx + dy * dy < best) + { + best = dx * dx + dy * dy; + to = Point(x, y); + } + } + return to; + } + + Point UIStateLogin::snap_tap(Point pos) + { + std::vector> targets; + if (UIElement* front = get_front(pos)) + { + front->tap_targets(targets); + return snap_to(targets, pos, TAP_REACH); + } + for (auto& element : elements.values()) + { + if (element && element->is_active()) + element->tap_targets(targets); + } + return snap_to(targets, pos, TAP_REACH); + } } diff --git a/src/client/IO/UIStateLogin.h b/src/client/IO/UIStateLogin.h index 1207726..9afbd8c 100644 --- a/src/client/IO/UIStateLogin.h +++ b/src/client/IO/UIStateLogin.h @@ -56,6 +56,7 @@ namespace jrc UIElement* get(UIElement::Type type) override; UIElement* get_front(const std::list& types) override; UIElement* get_front(Point pos) override; + Point snap_tap(Point pos) override; private: void clear_cursors(bool clicked, Point pos, UIElement::Type except); diff --git a/src/client/IO/UITypes/UICharSelect.cpp b/src/client/IO/UITypes/UICharSelect.cpp index c4930b9..f000eed 100644 --- a/src/client/IO/UITypes/UICharSelect.cpp +++ b/src/client/IO/UITypes/UICharSelect.cpp @@ -16,6 +16,7 @@ // along with this program. If not, see . // ////////////////////////////////////////////////////////////////////////////// #include "UICharSelect.h" +#include "../../Graphics/GraphicsGL.h" #include "UISoftKey.h" #include "UICharCreation.h" @@ -31,9 +32,14 @@ #include "../../Console.h" #include "../../Character/Job.h" #include "../../Net/Packets/SelectCharPackets.h" +#include "../../Util/Misc.h" #include "nlnx/nx.hpp" +#ifdef MS_PLATFORM_WASM +#include +#endif + namespace jrc { namespace @@ -51,6 +57,21 @@ namespace jrc charcount_absolute(c), slots_absolute(s) { selected_absolute = Setting::get().load(); +#ifdef MS_PLATFORM_WASM + // The last character played on this browser comes up already picked (the settings file doesn't outlive the + // page, so the page's storage keeps its id; a deleted or another account's character just isn't found). + int32_t last_cid = EM_ASM_INT({ + try { return parseInt(localStorage.getItem("dordoLastChar") || "0", 10) || 0; } catch (e) { return 0; } + }); + for (size_t i = 0; last_cid > 0 && i < characters.size(); ++i) + { + if (characters[i].cid == last_cid) + { + selected_absolute = static_cast(i); + break; + } + } +#endif selected_relative = selected_absolute % PAGESIZE; page = selected_absolute / PAGESIZE; @@ -59,13 +80,22 @@ namespace jrc nl::node common = nl::nx::ui["Login.img"]["Common"]; nl::node charselect = nl::nx::ui["Login.img"]["CharSelect"]; + nl::node scene = nl::nx::login["MapLogin.img"]; + has_scene = scene["back"].size() > 0; + if (has_scene) + { + scene_backs = MapBackgrounds(scene["back"]); + scene_tiles = MapTilesObjs(scene); + } + // Compatibility: base login background exists across more UI.nx variants // than Title/worldsel. - if (back["11"]) + // (with the login scene, that is the backdrop) + if (!has_scene && back["11"]) { sprites.emplace_back(back["11"], Point(370, 300)); } - else if (back["0"]) + else if (!has_scene && back["0"]) { sprites.emplace_back(back["0"], Point(370, 300)); } @@ -99,8 +129,7 @@ namespace jrc sprites.emplace_back(charselect["charInfo"], charinfopos); sprites.emplace_back(common["selectWorld"], selworldpos); - sprites.emplace_back(charselect["selectedWorld"]["icon"]["15"], selworldpos); - sprites.emplace_back(charselect["selectedWorld"]["name"]["15"], selworldpos); + // (the world's icon and name: Dordo Story's own, Chimken and its chicken, drawn in draw()) sprites.emplace_back(charselect["selectedWorld"]["ch"][channel_id], selworldpos); emptyslot = charselect["buyCharacter"]; @@ -115,7 +144,7 @@ namespace jrc for (uint8_t i = 0; i < PAGESIZE; ++i) { buttons[BT_CHAR0 + i] = std::make_unique( - Point(105 + (120 * (i % 4)), 170 + (200 * (i > 3))), + get_char_pos(i) - Point(25, 80), // (a character-sized box over each slot) Point(50, 80) ); } @@ -144,8 +173,24 @@ namespace jrc void UICharSelect::draw(float alpha) const { + if (has_scene) + { + scene_backs.drawbackgrounds(SCENE_VIEW.x(), SCENE_VIEW.y(), alpha); + for (auto id : Layer::IDs) + { + scene_tiles.draw(id, SCENE_VIEW, alpha); + } + scene_backs.drawforegrounds(SCENE_VIEW.x(), SCENE_VIEW.y(), alpha); + } + UIElement::draw(alpha); + // Chimken: the chicken where the world's icon was (47 x 48 at +19, +10), its name beside it (+64, +13) + Point icon = selworldpos + Point(20, 11); + GraphicsGL::get().draw_tv(GraphicsGL::TV_WORLD, Rectangle(icon, icon + Point(46, 46)), 1.0f); + world_shadow.draw(selworldpos + Point(66, 17)); + world_name.draw(selworldpos + Point(65, 16)); + for (uint8_t i = 0; i < charcount_relative; ++i) { Point charpos = get_char_pos(i); @@ -173,7 +218,7 @@ namespace jrc for (uint8_t i = charcount_relative; i < slots_relative; ++i) { - Point position_slot(130 + (120 * (i % 4)), 250 + (200 * (i > 3))); + Point position_slot = get_char_pos(i); emptyslot.draw(position_slot, alpha); } } @@ -182,6 +227,24 @@ namespace jrc { UIElement::update(); + // (in as a monster spirit: no character to pick; the server takes the account's spirit in) + if (!spirit_sent && getDordoString("spirit") == "1") + { + spirit_sent = true; + UI::get().disable(); + SpiritLoginPacket().dispatch(); +#ifdef MS_PLATFORM_WASM + // (the page covers this screen with a swirling void until the map comes in) + EM_ASM({ if (Module.onSpiritVoid) Module.onSpiritVoid(); }); +#endif + } + + if (has_scene) + { + scene_backs.update(); + scene_tiles.update(); + } + emptyslot.update(); for (auto& chit : charlooks) @@ -419,6 +482,9 @@ namespace jrc Setting::get().save(selected_absolute); int32_t cid = characters[selected_absolute].cid; +#ifdef MS_PLATFORM_WASM + EM_ASM({ try { localStorage.setItem("dordoLastChar", String($0)); } catch (e) {} }, cid); +#endif switch (require_pic) { case 0: @@ -574,6 +640,13 @@ namespace jrc Point UICharSelect::get_char_pos(size_t i) const { + if (has_scene) + { + // feet on the rope bridge's deck boards (their top edge is at 369, the log ends start at 378), toward + // the back as in the original, spread between the tree and the info panel + return { static_cast(205 + 112 * i), 365 }; + } + int16_t x = 130 + (120 * (i % 4)); int16_t y = 250 + (200 * (i > 3)); return { x, y }; diff --git a/src/client/IO/UITypes/UICharSelect.h b/src/client/IO/UITypes/UICharSelect.h index d68b44c..195c6e0 100644 --- a/src/client/IO/UITypes/UICharSelect.h +++ b/src/client/IO/UITypes/UICharSelect.h @@ -16,12 +16,15 @@ // along with this program. If not, see . // ////////////////////////////////////////////////////////////////////////////// #pragma once +#include "../../Graphics/Text.h" #include "../UIElement.h" #include "../Components/Charset.h" #include "../Components/Nametag.h" #include "../../Character/Look/CharLook.h" +#include "../../Gameplay/MapleMap/MapBackgrounds.h" +#include "../../Gameplay/MapleMap/MapTilesObjs.h" #include "../../Graphics/Sprite.h" #include "../../Net/Login.h" @@ -53,6 +56,7 @@ namespace jrc const CharEntry& get_character(int32_t cid); private: + bool spirit_sent = false; enum class PicAction { NONE, @@ -83,7 +87,7 @@ namespace jrc BT_CHAR0 }; - static constexpr uint8_t PAGESIZE = 8; + static constexpr uint8_t PAGESIZE = 4; // (one row: they stand along the rope bridge) Sprite emptyslot; Charset levelset; @@ -93,6 +97,9 @@ namespace jrc Point charinfopos; std::vector characters; + // (Dordo Story's world: its name, with a shadow under it) + Text world_name = Text(Text::A18M, Text::LEFT, Text::YELLOW, "Chimken"); + Text world_shadow = Text(Text::A18M, Text::LEFT, Text::BROWN, "Chimken"); std::vector charlooks; std::vector nametags; int8_t require_pic; @@ -154,5 +161,13 @@ namespace jrc LUK }; OutlinedText infolabels[NUM_LABELS]; + + // The old login map, seen where the character select is (characters stand on its rope bridge): the + // camera offset that puts the map's point (0, -1200) in the middle of the 800x600 screen + static constexpr Point SCENE_VIEW = { 400, 1500 }; + // The old login map's layers, seen where the character select is (characters stand on its rope bridge) + MapBackgrounds scene_backs; + MapTilesObjs scene_tiles; + bool has_scene; }; } diff --git a/src/client/IO/UITypes/UIChatBar.cpp b/src/client/IO/UITypes/UIChatBar.cpp index 8b16c49..a0c7cf6 100644 --- a/src/client/IO/UITypes/UIChatBar.cpp +++ b/src/client/IO/UITypes/UIChatBar.cpp @@ -1,5 +1,9 @@ #include "UIChatBar.h" +#ifdef MS_PLATFORM_WASM +#include +#endif + #include "../UI.h" #include "../Components/MapleButton.h" @@ -125,6 +129,9 @@ namespace jrc chatfield = { Text::A11M, Text::LEFT, Text::BLACK, { { -435, -58 }, { -40, -35} }, 0 }; set_chat_open(chatopen); chatfield.set_enter_callback([&](std::string msg) { + // Enter sends and hands the keys back to the game, like the original (no second Enter needed) + chatfield.set_state(Textfield::NORMAL); + msg = trim(msg); if (msg.empty()) { @@ -162,7 +169,8 @@ namespace jrc int16_t next = up ? rowpos - 1 : rowpos + 1; - if (next >= 0 && next <= rowmax) + // (rowpos is the newest line shown, so the top of the scroll is a screenful in) + if (next >= std::min(chatrows, rowmax) && next <= rowmax) rowpos = next; } }; } @@ -255,6 +263,12 @@ namespace jrc case BT_CHATTARGETS: cycle_chat_target(); return Button::PRESSED; + case BT_SCROLLUP: + slider.send_scroll(1.0); + break; + case BT_SCROLLDOWN: + slider.send_scroll(-1.0); + break; } return Button::NORMAL; } @@ -267,6 +281,22 @@ namespace jrc .contains(cursorpos); } + void UIChatbar::sync_slider() + { + // The slider counts from 0 (top) to rows - visible rows (bottom); rowpos is the newest line shown, from a + // screenful in up to the last line. Handing it rowpos as-is put the thumb past the end of its track (over + // the gauges) and stopped scrolling down a screenful short of the bottom. + slider.setrows(static_cast(std::max(0, rowpos - chatrows)), chatrows, rowmax); + } + + void UIChatbar::send_scroll(double yoffset) + { + if (chatopen) + { + slider.send_scroll(yoffset); + } + } + bool UIChatbar::remove_cursor(bool clicked, Point cursorpos) { if (slider.remove_cursor(clicked)) @@ -318,7 +348,7 @@ namespace jrc ydelta += CHATROWHEIGHT; } chatbox.setheight(1 + chatrows * CHATROWHEIGHT); - slider.setrows(rowpos, chatrows, rowmax); + sync_slider(); slider.setvertical({ 0, CHATROWHEIGHT * chatrows - 14 }); return { Cursor::CLICKING, true }; } @@ -348,7 +378,7 @@ namespace jrc rowmax++; rowpos = rowmax; - slider.setrows(rowpos, chatrows, rowmax); + sync_slider(); Text::Color color; switch (type) @@ -362,6 +392,9 @@ namespace jrc case YELLOW: color = Text::YELLOW; break; + case STREAM: + color = Text::VIOLET; + break; default: color = Text::WHITE; break; @@ -685,6 +718,9 @@ namespace jrc { case CHT_ALL: GeneralChatPacket(message, true).dispatch(); +#ifdef MS_PLATFORM_WASM + EM_ASM({ if (Module.onSaid) Module.onSaid(UTF8ToString($0)); }, message.c_str()); +#endif break; case CHT_BUDDY: MultiChatPacket(MultiChatPacket::BUDDY, recipients, message).dispatch(); diff --git a/src/client/IO/UITypes/UIChatBar.h b/src/client/IO/UITypes/UIChatBar.h index 862dde9..fa58773 100644 --- a/src/client/IO/UITypes/UIChatBar.h +++ b/src/client/IO/UITypes/UIChatBar.h @@ -51,7 +51,9 @@ namespace jrc WHITE, RED, BLUE, - YELLOW + YELLOW, + // (Dordo Story: someone watching our live stream, saying something) + STREAM }; struct PartyMember @@ -73,6 +75,7 @@ namespace jrc void set_position(Point pos); bool is_in_range(Point cursorpos) const override; + void send_scroll(double yoffset) override; bool remove_cursor(bool clicked, Point cursorpos) override; CursorResult send_cursor(bool pressed, Point cursorpos) override; @@ -96,6 +99,9 @@ namespace jrc Button::State button_pressed(uint16_t buttonid) override; private: + // the slider, from rowpos / chatrows / rowmax + void sync_slider(); + void set_chat_open(bool open); int32_t resolve_party_member_id(const std::string& token) const; bool handle_party_command(const std::string& message); diff --git a/src/client/IO/UITypes/UIEquipInventory.cpp b/src/client/IO/UITypes/UIEquipInventory.cpp index 2be692f..b1a5a2d 100644 --- a/src/client/IO/UITypes/UIEquipInventory.cpp +++ b/src/client/IO/UITypes/UIEquipInventory.cpp @@ -47,7 +47,7 @@ namespace jrc buttons[tab] = std::make_unique( source["Tab"]["disabled"][tab], source["Tab"]["enabled"][tab]); buttons[BT_EQUIP]->set_state(Button::PRESSED); - buttons[BT_CLOSE] = std::make_unique(nl::nx::ui["Basic.img"]["BtClose"], dimension.x() - 18, 6); + buttons[BT_CLOSE] = std::make_unique(nl::nx::ui["Basic.img"]["BtClose"], dimension.x() - 18, 12); unavailable_tabs[0] = source["Tab"]["disabled"]["2"]; unavailable_tabs[1] = source["Tab"]["disabled"]["3"]; diff --git a/src/client/IO/UITypes/UIItemInventory.cpp b/src/client/IO/UITypes/UIItemInventory.cpp index 8b87f1f..1e08350 100644 --- a/src/client/IO/UITypes/UIItemInventory.cpp +++ b/src/client/IO/UITypes/UIItemInventory.cpp @@ -16,6 +16,8 @@ // along with this program. If not, see . // ////////////////////////////////////////////////////////////////////////////// #include "UIItemInventory.h" +#include "UIQuickSlot.h" +#include "UINotice.h" #include "../../Gameplay/Stage.h" #include "../UI.h" @@ -23,6 +25,7 @@ #include "../Components/TwoSpriteButton.h" #include "UIKeyConfig.h" +#include "../../Audio/Audio.h" #include "../../Data/ItemData.h" #include "../../Gameplay/Stage.h" #include "../../Net/Packets/InventoryPackets.h" @@ -48,11 +51,12 @@ namespace jrc nl::node taben = src["Tab"]["enabled"]; nl::node tabdis = src["Tab"]["disabled"]; - buttons[BT_TAB_EQUIP]= std::make_unique(tabdis["0"], taben["0"], Point(-1, -4)); - buttons[BT_TAB_USE] = std::make_unique(tabdis["1"], taben["1"], Point(-1, -4)); + // (the tabs' own origins place them 32 px apart, except Set-up's, which is 1 px short) + buttons[BT_TAB_EQUIP]= std::make_unique(tabdis["0"], taben["0"], Point(0, -4)); + buttons[BT_TAB_USE] = std::make_unique(tabdis["1"], taben["1"], Point(0, -4)); buttons[BT_TAB_ETC] = std::make_unique(tabdis["2"], taben["2"], Point(0, -4)); - buttons[BT_TAB_SETUP] = std::make_unique(tabdis["3"], taben["3"], Point(-1, -4)); - buttons[BT_TAB_CASH]= std::make_unique(tabdis["4"], taben["4"], Point(-1, -4)); + buttons[BT_TAB_SETUP] = std::make_unique(tabdis["3"], taben["3"], Point(1, -4)); + buttons[BT_TAB_CASH]= std::make_unique(tabdis["4"], taben["4"], Point(0, -4)); buttons[BT_DROPMESO]= std::make_unique(src["BtCoin"]); buttons[BT_POINTS]= std::make_unique(src["BtPoint0"]); @@ -89,6 +93,15 @@ namespace jrc } }; dimension = { 172, 335 }; + // the X in the corner, like the stats and equipment windows + buttons[BT_CLOSE] = std::make_unique(nl::nx::ui["Basic.img"]["BtClose"], dimension.x() - 18, 12); + // (points, expanding, item pots, upgrades, the magnifier and the bit case aren't built yet: greyed out) + buttons[BT_POINTS]->set_state(Button::DISABLED); + buttons[BT_EXPAND]->set_state(Button::DISABLED); + buttons[BT_ITEMPOT]->set_state(Button::DISABLED); + buttons[BT_UPGRADE]->set_state(Button::DISABLED); + buttons[BT_MAGNIFY]->set_state(Button::DISABLED); + buttons[BT_BITCASE]->set_state(Button::DISABLED); active = true; load_icons(); @@ -187,9 +200,25 @@ namespace jrc Button::State UIItemInventory::button_pressed(uint16_t buttonid) { + switch (buttonid) + { + case BT_POINTS: + case BT_EXPAND: + case BT_ITEMPOT: + case BT_UPGRADE: + case BT_MAGNIFY: + case BT_BITCASE: + return Button::DISABLED; + default: + break; + } + InventoryType::Id oldtab = tab; switch (buttonid) { + case BT_CLOSE: + deactivate(); + return Button::NORMAL; case BT_TAB_EQUIP: tab = InventoryType::EQUIP; break; @@ -205,6 +234,20 @@ namespace jrc case BT_TAB_CASH: tab = InventoryType::CASH; break; + case BT_DROPMESO: + { + // like the original: 10 to 50,000 at a time, and no more than you have + int64_t have = inventory.get_meso(); + if (have < 10) + { + break; + } + int32_t most = static_cast(std::min(have, 50000)); + UI::get().emplace("How many mesos do you want to drop?", [](int32_t amount) { + DropMesoPacket(amount).dispatch(); + }, 10, most, std::min(most, 10)); + return Button::NORMAL; + } case BT_GATHER: GatherItemsPacket(tab).dispatch(); break; @@ -250,8 +293,14 @@ namespace jrc item_id / 10000 != 207 ) { UseItemPacket(slot, item_id).dispatch(); + Sound::play_item_use(item_id); } break; + case InventoryType::SETUP: + // a chair: sit on it + if (item_id / 10000 == 301) + Stage::get().get_player().sit_chair(item_id); + break; default: break; } @@ -547,6 +596,10 @@ namespace jrc if (sourcetab != InventoryType::USE && sourcetab != InventoryType::SETUP) return; + Keyboard::Mapping slotted{ KeyType::ITEM, item_id }; + if (auto quickslot = UI::get().get_element(); quickslot && !remove && quickslot->bind_at(cursorposition, slotted)) + return; + if (auto keyconfig = UI::get().get_element()) { Keyboard::Mapping mapping{ KeyType::ITEM, item_id }; diff --git a/src/client/IO/UITypes/UIItemInventory.h b/src/client/IO/UITypes/UIItemInventory.h index c4eb4ab..3552a45 100644 --- a/src/client/IO/UITypes/UIItemInventory.h +++ b/src/client/IO/UITypes/UIItemInventory.h @@ -98,7 +98,8 @@ namespace jrc BT_ITEMPOT, BT_UPGRADE, BT_MAGNIFY, - BT_BITCASE + BT_BITCASE, + BT_CLOSE }; const Inventory& inventory; diff --git a/src/client/IO/UITypes/UIKeyConfig.cpp b/src/client/IO/UITypes/UIKeyConfig.cpp index d8e9fba..5f9e4e9 100644 --- a/src/client/IO/UITypes/UIKeyConfig.cpp +++ b/src/client/IO/UITypes/UIKeyConfig.cpp @@ -2,6 +2,7 @@ // This file is part of the Journey MMORPG client // ////////////////////////////////////////////////////////////////////////////// #include "UIKeyConfig.h" +#include "UIQuickSlot.h" #include "UINotice.h" @@ -591,6 +592,14 @@ namespace jrc dirty = false; } + void UIKeyConfig::sync_from_keyboard() + { + if (!dirty) + { + reset_from_keyboard(); + } + } + void UIKeyConfig::reset_from_keyboard() { staged_mappings = keyboard->get_maplekeys(); @@ -767,6 +776,11 @@ namespace jrc void UIKeyConfig::KeyIcon::drop_on_bindings(Point cursorposition, bool remove) const { + if (auto quickslot = UI::get().get_element(); quickslot && !remove && quickslot->bind_at(cursorposition, mapping)) + { + return; + } + if (auto keyconfig = UI::get().get_element()) { if (remove) diff --git a/src/client/IO/UITypes/UIKeyConfig.h b/src/client/IO/UITypes/UIKeyConfig.h index f6bb765..ce8ee8d 100644 --- a/src/client/IO/UITypes/UIKeyConfig.h +++ b/src/client/IO/UITypes/UIKeyConfig.h @@ -20,6 +20,9 @@ namespace jrc class UIKeyConfig : public UIDragElement { public: + // The keys were changed from outside (the quick slot): show them, unless there are unsaved changes here + void sync_from_keyboard(); + static constexpr Type TYPE = UIElement::KEYCONFIG; static constexpr bool FOCUSED = false; static constexpr bool TOGGLED = true; diff --git a/src/client/IO/UITypes/UILogin.cpp b/src/client/IO/UITypes/UILogin.cpp index 77e9cbb..3bc2f1d 100644 --- a/src/client/IO/UITypes/UILogin.cpp +++ b/src/client/IO/UITypes/UILogin.cpp @@ -26,6 +26,7 @@ #include "../../Console.h" #include "../../Graphics/Sprite.h" #include "../../Net/Packets/LoginPackets.h" +#include "../../Util/Misc.h" #include "nlnx/nx.hpp" @@ -149,8 +150,19 @@ namespace jrc password.set_cryptchar('*'); passwordbg = title["PW"]; + // The hosting page may already know who this is (its own log-on): fill in the account and log in by + // itself on the first update, once the screen is fully built. + std::string auto_account = getDordoString("account"); + std::string auto_password = getDordoString("password"); + autologin = !auto_account.empty() && !auto_password.empty(); + saveid = Setting::get().load(); - if (saveid) + if (autologin) + { + account.change_text(auto_account); + password.change_text(auto_password); + } + else if (saveid) { account.change_text(Setting::get().load()); password.set_state(Textfield::FOCUSED); @@ -191,6 +203,12 @@ namespace jrc account.update(position); password.update(position); + + if (autologin) + { + autologin = false; + login(); + } } void UILogin::login() diff --git a/src/client/IO/UITypes/UILogin.h b/src/client/IO/UITypes/UILogin.h index 0f3a556..96d8415 100644 --- a/src/client/IO/UITypes/UILogin.h +++ b/src/client/IO/UITypes/UILogin.h @@ -63,5 +63,6 @@ namespace jrc BoolPair checkbox; bool saveid; + bool autologin; }; } diff --git a/src/client/IO/UITypes/UIMiniMap.cpp b/src/client/IO/UITypes/UIMiniMap.cpp index 1367b18..21a26e6 100644 --- a/src/client/IO/UITypes/UIMiniMap.cpp +++ b/src/client/IO/UITypes/UIMiniMap.cpp @@ -17,6 +17,7 @@ ////////////////////////////////////////////////////////////////////////////// #include "UIMiniMap.h" +#include "../../Gameplay/Stage.h" #include "UIWorldMap.h" #include "../UI.h" @@ -99,8 +100,15 @@ namespace jrc toggle_buttons(); } + bool UIMiniMap::is_in_range(Point cursorpos) const + { + return !Stage::get().get_spirit().active() && UIElement::is_in_range(cursorpos); + } + void UIMiniMap::draw(float alpha) const { + if (Stage::get().get_spirit().active()) + return; // (a monster spirit has no map: Dordo Story) if (type == MIN) { for (const Sprite& sprite : min_sprites) @@ -174,18 +182,14 @@ namespace jrc mapid = current_mapid; map_node = NxHelper::Map::get_map_node_name(mapid); - nl::node town = map_node["info"]["town"]; nl::node mini_map = map_node["miniMap"]; has_map = static_cast(mini_map); + // (towns used to force it wide open; now they keep whatever the player chose, rolled up by default) if (!has_map) { type = MIN; } - else if (town && town.get_bool()) - { - type = MAX; - } else { type = user_type; @@ -507,7 +511,6 @@ namespace jrc nl::node min_src = minimap_node["Min"]; nl::node normal_src = minimap_node["MinMap"]; nl::node max_src = minimap_node["MaxMap"]; - nl::node middle_center = minimap_node["MaxMap"]["c"]; map_sprite = Texture(map_node["miniMap"]["canvas"]); Point map_dimensions = map_sprite.get_dimensions(); @@ -542,7 +545,7 @@ namespace jrc min_sprites.emplace_back(min_src["w"], DrawArgument(Point(0, 0))); min_sprites.emplace_back(min_src["e"], DrawArgument(Point(min_c_stretch + CENTER_START_X, 0))); - normal_sprites.emplace_back(middle_center, DrawArgument(Point(7, 10), Point(c_stretch + 114, m_stretch + 27))); + // (no fill behind the map: MaxMap/c is a translucent white wash; the map shows through the frame instead) if (has_map) { normal_sprites.emplace_back(map_node["miniMap"]["canvas"], DrawArgument(Point(map_draw_origin_x, map_draw_origin_y))); @@ -559,7 +562,6 @@ namespace jrc normal_dimensions = Point(ur_x_offset + 64, down_y_offset + 27); - max_sprites.emplace_back(middle_center, DrawArgument(Point(7, 50), Point(c_stretch + 114, m_stretch + 27))); if (has_map) { max_sprites.emplace_back(map_node["miniMap"]["canvas"], DrawArgument(Point(map_draw_origin_x, map_draw_origin_y + MAX_ADJ))); diff --git a/src/client/IO/UITypes/UIMiniMap.h b/src/client/IO/UITypes/UIMiniMap.h index b292bb3..1ef782a 100644 --- a/src/client/IO/UITypes/UIMiniMap.h +++ b/src/client/IO/UITypes/UIMiniMap.h @@ -38,6 +38,7 @@ namespace jrc explicit UIMiniMap(const CharStats& stats); void draw(float alpha) const override; + bool is_in_range(Point cursorpos) const override; void update() override; bool remove_window_cursor(bool clicked, Point cursorpos) override; diff --git a/src/client/IO/UITypes/UINpcTalk.cpp b/src/client/IO/UITypes/UINpcTalk.cpp index 5f0c0a2..0e4dd05 100644 --- a/src/client/IO/UITypes/UINpcTalk.cpp +++ b/src/client/IO/UITypes/UINpcTalk.cpp @@ -17,6 +17,10 @@ ////////////////////////////////////////////////////////////////////////////// #include "UINpcTalk.h" +#include "../../Audio/Audio.h" + +#include + #include "../Components/MapleButton.h" #include "../Components/NpcDialogLayout.h" #include "../Components/NpcMenu.h" @@ -43,9 +47,11 @@ namespace jrc namespace { constexpr int16_t TEXT_WIDTH = 320; - constexpr int16_t TEXT_VERTICAL_PADDING = NpcDialogLayout::PADDING; constexpr int16_t BUTTON_MARGIN = 20; constexpr int16_t BUTTON_GAP = 6; + // the blue button strip inside the dialog's bottom piece (UtilDlgEx/s: rows 17 to 39 of 44) + constexpr int16_t FOOTER_STRIP_TOP = 17; + constexpr int16_t FOOTER_STRIP_BOTTOM = 40; constexpr int16_t DIALOG_TEXT_X = 156; constexpr int16_t OPTION_VERTICAL_GAP = 2; constexpr int16_t HOVER_UNDERLINE_THICKNESS = 1; @@ -315,13 +321,22 @@ namespace jrc UIElement::draw(inter); - speaker.draw({ position + Point(80, 100), true }); - nametag.draw(position + Point(25, 100)); - name.draw(position + Point(80, 99)); + // The NPC stands in the middle of the dialog's left column with its name tag just under its feet, as in + // the original (feet pinned 100 px down put tall NPCs against the top edge and their tag on their feet). + int16_t column_top = top.height() + 4; + int16_t column_bottom = static_cast(top.height() + vtile * fill.height() + bottom.height() + - FOOTER_STRIP_BOTTOM - nametag.height() - 6); + int16_t sprite_h = speaker.get_dimensions().y(); + int16_t feet = static_cast((column_top + column_bottom + sprite_h) / 2 - sprite_h + + speaker.get_origin().y()); + feet = std::max(feet, static_cast(column_top + speaker.get_origin().y())); + speaker.draw({ position + Point(80, feet), true }); + nametag.draw(position + Point(25, feet + 2)); + name.draw(position + Point(80, feet + 1)); // Visible content bounds (relative to dialog position). - int16_t content_top = static_cast(top.height() + TEXT_VERTICAL_PADDING); - int16_t content_bottom = static_cast(top.height() + height - TEXT_VERTICAL_PADDING); + int16_t content_top = text_top; + int16_t content_bottom = static_cast(text_top + visible_height); int32_t text_y = get_dialogue_text_y() - scroll_offset; if (text_y + text.height() > content_top && text_y < content_bottom) @@ -822,6 +837,8 @@ namespace jrc vtile = layout.tiles; height = vtile * fill.height(); max_scroll = layout.max_scroll; + text_top = layout.text_top; + visible_height = layout.visible_height; for (auto& button : buttons) { @@ -829,8 +846,12 @@ namespace jrc button.second->set_state(Button::NORMAL); } auto place_button = [&](Buttons id, int16_t x) { + // The bottom piece is the end of the white text area, a grey rule, then the blue strip the buttons sit + // in (and the frame's edge): centre them in the strip, an even margin above and below like the + // original, instead of in the whole piece, which lifts them over the rule towards the text. int16_t footer_y = top.height() + height; - int16_t button_y = footer_y + std::max(0, (bottom.height() - buttons[id]->height()) / 2); + int16_t strip = std::min(FOOTER_STRIP_BOTTOM, bottom.height()) - FOOTER_STRIP_TOP; + int16_t button_y = footer_y + FOOTER_STRIP_TOP + std::max(0, (strip - buttons[id]->height()) / 2); buttons[id]->set_position({ x, button_y }); buttons[id]->set_active(true); }; @@ -931,6 +952,84 @@ namespace jrc NpcTalkMorePacket::close(type).dispatch(); } + bool UINpcTalk::send_answer_key(bool yes) + { + Buttons id = yes ? YES : NO; + if (!active || !buttons.count(id) || !buttons[id]->is_active()) + { + return false; + } + + Sound(Sound::BUTTONCLICK).play(); + buttons[id]->set_state(button_pressed(id)); + return true; + } + + bool UINpcTalk::send_selection_key(int32_t keycode) + { + if (!active || dialogue_mode != DialogueMode::SELECTION || selection_labels.empty()) + { + return false; + } + + int32_t count = static_cast(selection_labels.size()); + if (keycode == GLFW_KEY_UP || keycode == GLFW_KEY_DOWN) + { + if (selected < 0 || selected >= count) + { + selected = keycode == GLFW_KEY_UP ? count - 1 : 0; + } + else + { + selected = std::clamp(selected + (keycode == GLFW_KEY_UP ? -1 : 1), 0, count - 1); + } + hovered_selection = selected; + refresh_selection_styles(); + + // keep the picked option in view on a long list + int32_t top = get_options_start_y(); + for (int32_t i = 0; i < selected; ++i) + { + top += selection_labels[i].height() + OPTION_VERTICAL_GAP; + } + int32_t bottom = top + selection_labels[selected].height(); + if (top - scroll_offset < text_top) + { + scroll_offset = top - text_top; + } + else if (bottom - scroll_offset > text_top + visible_height) + { + scroll_offset = bottom - (text_top + visible_height); + } + scroll_offset = std::clamp(scroll_offset, 0, std::max(0, max_scroll)); + return true; + } + + if ((keycode == GLFW_KEY_ENTER || keycode == GLFW_KEY_KP_ENTER || keycode == GLFW_KEY_SPACE) + && selected >= 0 && selected < count) + { + Sound(Sound::BUTTONCLICK).play(); + button_pressed(OK); + return true; + } + + return false; + } + + bool UINpcTalk::send_confirm_key() + { + for (Buttons id : { NEXT, OK }) + { + if (active && buttons.count(id) && buttons[id]->is_active()) + { + Sound(Sound::BUTTONCLICK).play(); + buttons[id]->set_state(button_pressed(id)); + return true; + } + } + return false; + } + void UINpcTalk::send_scroll(double yoffset) { if (max_scroll <= 0) @@ -1042,7 +1141,7 @@ namespace jrc int16_t UINpcTalk::get_dialogue_text_y() const { - return top.height() + TEXT_VERTICAL_PADDING; + return text_top; } int32_t UINpcTalk::get_options_start_y() const @@ -1055,10 +1154,35 @@ namespace jrc return options_y; } + void UINpcTalk::tap_targets(std::vector>& out) const + { + UIElement::tap_targets(out); + + // each answer's row, where it shows (the same rows get_option_at reads) + const int16_t content_top = text_top; + const int16_t content_bottom = static_cast(text_top + visible_height); + int32_t options_y = get_options_start_y() - scroll_offset; + for (size_t i = 0; i < selection_labels.size(); ++i) + { + const int32_t option_height = selection_labels[i].height(); + int32_t top = std::max(options_y, content_top); + int32_t bottom = std::min(options_y + option_height, content_bottom); + if (bottom > top) + { + out.push_back(Rectangle( + static_cast(position.x() + DIALOG_TEXT_X), + static_cast(position.x() + DIALOG_TEXT_X + TEXT_WIDTH), + static_cast(position.y() + top), + static_cast(position.y() + bottom))); + } + options_y += option_height + OPTION_VERTICAL_GAP; + } + } + int32_t UINpcTalk::get_option_at(Point relative) const { - const int16_t content_top = top.height() + TEXT_VERTICAL_PADDING; - const int16_t content_bottom = top.height() + height - TEXT_VERTICAL_PADDING; + const int16_t content_top = text_top; + const int16_t content_bottom = static_cast(text_top + visible_height); if (relative.y() < content_top || relative.y() >= content_bottom || relative.x() < DIALOG_TEXT_X || relative.x() >= DIALOG_TEXT_X + TEXT_WIDTH) return -1; @@ -1112,10 +1236,40 @@ namespace jrc continue; } + // "#L#" opens option n: passed through whole, so its closing '#' can't be read as the start of a + // token ("#L1#How do I..." took "#How do I...#" for "#h#", the player's name) + if (token == 'L') + { + size_t digits = cursor + 2; + while (digits < source.size() && std::isdigit(static_cast(source[digits]))) + digits++; + if (digits > cursor + 2 && digits < source.size() && source[digits] == '#') + { + result.append(source, cursor, digits + 1 - cursor); + cursor = digits + 1; + continue; + } + } + + // "#c#": how many of that item the player has (a quest's "3 / 10") + if (token == 'c' || token == 'C') + { + int32_t id = 0; + size_t token_end = 0; + if (try_parse_delimited_number(source, cursor + 2, token_end, id)) + { + result += std::to_string(Stage::get().get_player().get_inventory().count_items(id)); + cursor = token_end + 1; + continue; + } + } + if (token == 'h' || token == 'H') { + // (only "#h#" or "#h #" is the player's name: "#How ..." is just text after a '#') size_t token_end = source.find('#', cursor + 2); - if (token_end != std::string::npos) + bool name_token = token_end == cursor + 2 || (token_end == cursor + 3 && source[cursor + 2] == ' '); + if (token_end != std::string::npos && name_token) { result += Stage::get().get_player().get_stats().get_name(); cursor = token_end + 1; diff --git a/src/client/IO/UITypes/UINpcTalk.h b/src/client/IO/UITypes/UINpcTalk.h index 7aceae1..3a87caf 100644 --- a/src/client/IO/UITypes/UINpcTalk.h +++ b/src/client/IO/UITypes/UINpcTalk.h @@ -33,6 +33,13 @@ namespace jrc class UINpcTalk : public UIWindow { public: + // Y and N answer a Yes/No (or Accept/Decline) question, like the original; false when none is showing + bool send_answer_key(bool yes); + // Enter and Space press Next, or OK on the last page; false when neither is showing + bool send_confirm_key(); + // In a list of options: Up / Down pick one, Enter / Space choose it; false when there's no list + bool send_selection_key(int32_t keycode); + static constexpr Type TYPE = NPCTALK; static constexpr bool FOCUSED = false; static constexpr bool TOGGLED = true; @@ -127,6 +134,9 @@ namespace jrc int16_t get_dialogue_text_y() const; int32_t get_options_start_y() const; int32_t get_option_at(Point relative) const; + public: + void tap_targets(std::vector>& out) const override; + private: enum Buttons { @@ -161,6 +171,9 @@ namespace jrc int32_t hovered_selection; int32_t scroll_offset; int32_t max_scroll; + // where the text area starts and how tall it is (from NpcDialogLayout: inside the white field) + int16_t text_top = 0; + int16_t visible_height = 0; std::unique_ptr quest; std::function menu_selection; }; diff --git a/src/client/IO/UITypes/UIParty.cpp b/src/client/IO/UITypes/UIParty.cpp index be60ef0..d138570 100644 --- a/src/client/IO/UITypes/UIParty.cpp +++ b/src/client/IO/UITypes/UIParty.cpp @@ -1,8 +1,27 @@ +////////////////////////////////////////////////////////////////////////////// +// This file is part of the Journey MMORPG client // +// Copyright © 2015-2016 Daniel Allendorf // +// // +// This program is free software: you can redistribute it and/or modify // +// it under the terms of the GNU Affero General Public License as // +// published by the Free Software Foundation, either version 3 of the // +// License, or (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU Affero General Public License for more details. // +// // +// You should have received a copy of the GNU Affero General Public License // +// along with this program. If not, see . // +////////////////////////////////////////////////////////////////////////////// #include "UIParty.h" #include "../Components/MapleButton.h" #include "../UI.h" +#include "../../Character/Job.h" +#include "../../Gameplay/Stage.h" #include "../../Net/Packets/GameplayPackets.h" #include "UIStatusBar.h" @@ -15,6 +34,36 @@ namespace jrc { namespace { + // The User List window (312 x 389): title box, tab strip (rows 22-43), red rule, white content + // (rows 47-332), and the blue button band (rows 336-384) + constexpr int16_t WIDTH = 312; + constexpr int16_t HEIGHT = 389; + constexpr int16_t TAB_Y = 27; + // the Party tab's pieces, top to bottom + constexpr Point ONLINE_HEADER = { 15, 52 }; + constexpr Point ONLINE_COLUMNS = { 16, 80 }; + constexpr Point ONLINE_ROWS = { 16, 98 }; + constexpr Point SEPARATOR = { 16, 210 }; + constexpr Point OFFLINE_HEADER = { 15, 216 }; + constexpr Point OFFLINE_COLUMNS = { 16, 244 }; + constexpr Point OFFLINE_ROWS = { 16, 262 }; + constexpr size_t OFFLINE_SHOWN = 3; + constexpr int16_t ROW_H = 18; + constexpr int16_t ROW_W = 279; + constexpr Point INVITE_INFO = { 18, 318 }; + // inside a row: the leader's star, then the NAME / JOB / LV columns of the header + constexpr int16_t STAR_X = 3; + constexpr int16_t NAME_X = 19; + constexpr int16_t JOB_X = 122; + constexpr int16_t LEVEL_X = 213; + constexpr int16_t TEXT_Y = 2; + // the button band: two rows + constexpr int16_t BUTTONS_Y = 341; + constexpr int16_t BUTTONS_X = 10; + constexpr int16_t BUTTON_STRIDE = 50; + constexpr int16_t SECOND_ROW_Y = 363; + constexpr Rectangle NAME_BOX = { 46, 172, 363, 379 }; + std::string trim(const std::string& value) { size_t first = value.find_first_not_of(' '); @@ -35,47 +84,59 @@ namespace jrc } } - std::string resolve_leader_name(int32_t leader_id, const std::vector& members) + bool is_online(const UIChatbar::PartyMember& member) { - for (const UIChatbar::PartyMember& member : members) - { - if (member.id == leader_id && !member.name.empty()) - { - return member.name; - } - } - - return "Unknown"; + return member.channel >= 0; } } UIParty::UIParty() - : UIDragElement(Point(300, 22)), background(300, 230, Geometry::BLACK, 0.80f), header(300, 22, Geometry::WHITE, 0.12f), divider(260, 1, Geometry::WHITE, 0.25f), title(Text::A12B, Text::LEFT, Text::WHITE, "Party"), party_info(Text::A11M, Text::LEFT, Text::WHITE, ""), invite_info(Text::A11M, Text::LEFT, Text::YELLOW, ""), invite_label(Text::A11M, Text::LEFT, Text::WHITE, "Invite:"), - help_info(Text::A11M, Text::LEFT, Text::LIGHTGREY, "Tip: /party list, /party leader "), party_id(-1), party_leader_id(-1), pending_party_invite_id(-1) + : UIDragElement(Point(WIDTH, 21)), + name_box(NAME_BOX.width(), NAME_BOX.height(), Geometry::WHITE, 1.0f), + name_box_edge(NAME_BOX.width() + 2, NAME_BOX.height() + 2, Geometry::BLACK, 0.45f), + picked_row(ROW_W, ROW_H, Geometry::BLACK, 0.12f), + title(Text::A12B, Text::LEFT, Text::BLACK, ""), + name_label(Text::A11M, Text::LEFT, Text::WHITE, "Name"), + invite_info(Text::A11M, Text::LEFT, Text::BLUE, ""), + empty_info(Text::A11M, Text::LEFT, Text::DARKGREY, ""), + party_id(-1), party_leader_id(-1), pending_party_invite_id(-1), picked_member(-1) { - dimension = Point(300, 230); - - nl::node basic = nl::nx::ui["Basic.img"]; - buttons[BT_CLOSE] = std::make_unique(basic["BtClose"], Point(276, 4)); - buttons[BT_CREATE] = std::make_unique(basic["BtOK4"], Point(20, 190)); - buttons[BT_LEAVE] = std::make_unique(basic["BtCancel4"], Point(90, 190)); - buttons[BT_ACCEPT] = std::make_unique(basic["BtOK4"], Point(160, 190)); - buttons[BT_DENY] = std::make_unique(basic["BtCancel4"], Point(230, 190)); - buttons[BT_INVITE] = std::make_unique(basic["BtOK4"], Point(240, 157)); - - button_labels[BT_CREATE] = Text(Text::A11M, Text::CENTER, Text::WHITE, "Create"); - button_labels[BT_LEAVE] = Text(Text::A11M, Text::CENTER, Text::WHITE, "Leave"); - button_labels[BT_ACCEPT] = Text(Text::A11M, Text::CENTER, Text::WHITE, "Accept"); - button_labels[BT_DENY] = Text(Text::A11M, Text::CENTER, Text::WHITE, "Deny"); - button_labels[BT_INVITE] = Text(Text::A11M, Text::CENTER, Text::WHITE, "Invite"); + dimension = Point(WIDTH, HEIGHT); + + nl::node userlist = nl::nx::ui["UIWindow.img"]["UserList"]; + nl::node party = userlist["Party"]; + backgrnd = userlist["backgrnd"]; + header_online = party["party0"]; + row = party["party1"]; + separator = party["party2"]; + header_offline = party["party4"]; + columns = party["party5"]; + leader_star = party["icon0"]; + + // Buddy, Party, Exped, Guild, Alliance, Blacklist along the strip; only Party is this window's + int16_t x = 10; + for (size_t i = 0; i < tabs.size(); ++i) + { + tabs[i] = userlist["Tab"][i == 1 ? "enabled" : "disabled"][std::to_string(i)]; + tab_x[i] = x; + x += tabs[i].get_dimensions().x() + 7; + } + + buttons[BT_CLOSE] = std::make_unique(nl::nx::ui["Basic.img"]["BtClose"], Point(WIDTH - 15, 14)); + buttons[BT_CREATE] = std::make_unique(party["BtCreate"], Point(BUTTONS_X, BUTTONS_Y)); + buttons[BT_INVITE] = std::make_unique(party["BtInvite"], Point(BUTTONS_X + BUTTON_STRIDE, BUTTONS_Y)); + buttons[BT_EXPEL] = std::make_unique(party["BtKick"], Point(BUTTONS_X + BUTTON_STRIDE * 2, BUTTONS_Y)); + buttons[BT_LEAVE] = std::make_unique(party["BtWithdraw"], Point(BUTTONS_X + BUTTON_STRIDE * 3, BUTTONS_Y)); + buttons[BT_LEADER] = std::make_unique(party["BtChangeBoss"], Point(BUTTONS_X + BUTTON_STRIDE * 4, BUTTONS_Y - 1)); + buttons[BT_ACCEPT] = std::make_unique(nl::nx::ui["Basic.img"]["BtOK4"], Point(186, SECOND_ROW_Y)); + buttons[BT_DENY] = std::make_unique(nl::nx::ui["Basic.img"]["BtCancel4"], Point(232, SECOND_ROW_Y)); invite_field = Textfield( Text::A11M, Text::LEFT, - Text::WHITE, - // Keep typed invite names clear of the "Invite:" caption. - Rectangle(53, 207, 160, 178), - 13 + Text::BLACK, + Rectangle(NAME_BOX.l() + 3, NAME_BOX.r() - 2, NAME_BOX.t() + 1, NAME_BOX.b()), + 12 ); invite_field.set_state(Textfield::NORMAL); invite_field.set_enter_callback( @@ -87,7 +148,9 @@ namespace jrc for (size_t i = 0; i < PARTY_SIZE; i++) { - member_lines[i] = Text(Text::A11M, Text::LEFT, Text::LIGHTGREY, ""); + names[i] = Text(Text::A11M, Text::LEFT, Text::BLACK, ""); + jobs[i] = Text(Text::A11M, Text::LEFT, Text::DARKGREY, ""); + levels[i] = Text(Text::A11M, Text::LEFT, Text::DARKGREY, ""); } if (auto statusbar = UI::get().get_element()) @@ -104,27 +167,67 @@ namespace jrc sync_text(); } + Point UIParty::row_position(size_t slot, bool online) const + { + Point first = online ? ONLINE_ROWS : OFFLINE_ROWS; + return first + Point(0, static_cast(slot * ROW_H)); + } + void UIParty::draw(float alpha) const { - background.draw(position); - header.draw(position); - divider.draw(position + Point(20, 24)); - divider.draw(position + Point(20, 146)); - invite_field.draw(position); - UIElement::draw_buttons(alpha); + backgrnd.draw(position); + for (size_t i = 0; i < tabs.size(); ++i) + { + tabs[i].draw(position + Point(tab_x[i], TAB_Y + (i == 1 ? 0 : 1))); + } - title.draw(position + Point(12, 6)); - party_info.draw(position + Point(20, 30)); + header_online.draw(position + ONLINE_HEADER); + columns.draw(position + ONLINE_COLUMNS); + separator.draw(position + SEPARATOR); + header_offline.draw(position + OFFLINE_HEADER); + columns.draw(position + OFFLINE_COLUMNS); - for (size_t i = 0; i < PARTY_SIZE; i++) + // members: online under the first header, offline under the second, in party order + size_t online_slot = 0; + size_t offline_slot = 0; + for (size_t i = 0; i < party_members.size() && i < PARTY_SIZE; ++i) { - member_lines[i].draw(position + Point(20, 48 + static_cast(i * 16))); + const UIChatbar::PartyMember& member = party_members[i]; + bool online = is_online(member); + size_t slot = online ? online_slot++ : offline_slot++; + if (!online && slot >= OFFLINE_SHOWN) + { + continue; + } + + Point at = position + row_position(slot, online); + row.draw(at); + if (static_cast(i) == picked_member) + { + picked_row.draw(at); + } + if (member.id == party_leader_id) + { + leader_star.draw(at + Point(STAR_X, 2)); + } + names[i].draw(at + Point(NAME_X, TEXT_Y)); + jobs[i].draw(at + Point(JOB_X, TEXT_Y)); + levels[i].draw(at + Point(LEVEL_X, TEXT_Y)); } - invite_info.draw(position + Point(20, 132)); - invite_label.draw(position + Point(20, 160)); - help_info.draw(position + Point(20, 214)); - draw_button_labels(); + if (party_members.empty()) + { + empty_info.draw(position + ONLINE_ROWS + Point(NAME_X, TEXT_Y)); + } + invite_info.draw(position + INVITE_INFO); + + // the invite row in the button band + name_label.draw(position + Point(BUTTONS_X + 2, SECOND_ROW_Y + 1)); + name_box_edge.draw(position + Point(NAME_BOX.l() - 1, NAME_BOX.t() - 1)); + name_box.draw(position + Point(NAME_BOX.l(), NAME_BOX.t())); + invite_field.draw(position); + + UIElement::draw_buttons(alpha); } void UIParty::update() @@ -133,6 +236,29 @@ namespace jrc invite_field.update(position); } + int32_t UIParty::member_at(Point cursorpos) const + { + size_t online_slot = 0; + size_t offline_slot = 0; + for (size_t i = 0; i < party_members.size() && i < PARTY_SIZE; ++i) + { + bool online = is_online(party_members[i]); + size_t slot = online ? online_slot++ : offline_slot++; + if (!online && slot >= OFFLINE_SHOWN) + { + continue; + } + + Point at = position + row_position(slot, online); + if (Rectangle(at, at + Point(ROW_W, ROW_H)).contains(cursorpos)) + { + return static_cast(i); + } + } + + return -1; + } + UIElement::CursorResult UIParty::send_window_cursor(bool clicked, Point cursorpos) { if (invite_field.get_state() != Textfield::DISABLED) @@ -144,6 +270,20 @@ namespace jrc } } + int32_t member = member_at(cursorpos); + if (member >= 0) + { + if (clicked) + { + // (click again to let go) + picked_member = picked_member == member ? -1 : member; + sync_buttons(); + return { Cursor::CLICKING, true }; + } + + return { Cursor::CANCLICK, true }; + } + return UIWindow::send_window_cursor(clicked, cursorpos); } @@ -185,6 +325,7 @@ namespace jrc party_id = in_party_id; party_leader_id = leader_id; party_members = members; + picked_member = -1; if (pending_party_invite_id == in_party_id) { @@ -199,6 +340,7 @@ namespace jrc party_id = -1; party_leader_id = -1; party_members.clear(); + picked_member = -1; sync_text(); } @@ -216,7 +358,6 @@ namespace jrc { member.hp = hp; member.max_hp = max_hp; - sync_text(); return; } } @@ -224,6 +365,16 @@ namespace jrc Button::State UIParty::button_pressed(uint16_t buttonid) { + // (a greyed-out button still gets clicks here: it does nothing) + auto pressed = buttons.find(buttonid); + if (pressed != buttons.end() && pressed->second->get_state() == Button::DISABLED) + { + return Button::DISABLED; + } + + const UIChatbar::PartyMember* picked = + picked_member >= 0 && picked_member < static_cast(party_members.size()) ? &party_members[picked_member] : nullptr; + switch (buttonid) { case BT_CLOSE: @@ -231,50 +382,62 @@ namespace jrc return Button::NORMAL; case BT_CREATE: CreatePartyPacket().dispatch(); - send_status_line("[Party] Sent create request."); break; case BT_LEAVE: LeavePartyPacket().dispatch(); - send_status_line("[Party] Sent leave request."); + break; + case BT_INVITE: + send_invite(); + break; + case BT_EXPEL: + if (picked) + { + ExpelFromPartyPacket(picked->id).dispatch(); + send_status_line("[Party] Asked to expel " + picked->name + "."); + } + else + { + send_status_line("[Party] Click a member first, then Expel."); + } + break; + case BT_LEADER: + if (picked) + { + ChangePartyLeaderPacket(picked->id).dispatch(); + } + else + { + send_status_line("[Party] Click a member first, then Party Leader."); + } break; case BT_ACCEPT: if (pending_party_invite_id > 0) { JoinPartyPacket(pending_party_invite_id).dispatch(); - send_status_line("[Party] Sent invitation accept request."); if (auto statusbar = UI::get().get_element()) { statusbar->clear_pending_party_invite(); } } - else - { - send_status_line("[Party] There is no pending invitation."); - } break; case BT_DENY: if (!pending_party_inviter.empty()) { DenyPartyInvitePacket(pending_party_inviter).dispatch(); - send_status_line("[Party] Declined invitation from " + pending_party_inviter + "."); + send_status_line("[Party] Declined the invitation from " + pending_party_inviter + "."); if (auto statusbar = UI::get().get_element()) { statusbar->clear_pending_party_invite(); } } - else - { - send_status_line("[Party] There is no pending invitation."); - } - break; - case BT_INVITE: - send_invite(); break; default: break; } - return Button::PRESSED; + // (whatever the press changed, the buttons show what's possible now) + sync_buttons(); + return pressed != buttons.end() ? pressed->second->get_state() : Button::NORMAL; } void UIParty::send_invite() @@ -282,78 +445,58 @@ namespace jrc std::string name = trim(invite_field.get_text()); if (name.empty()) { - send_status_line("[Party] Enter a character name to invite."); + send_status_line("[Party] Type a character's name in the box to invite them."); return; } InviteToPartyPacket(name).dispatch(); - send_status_line("[Party] Sent invite request to " + name + "."); + send_status_line("[Party] Invited " + name + "."); invite_field.change_text(""); } - void UIParty::sync_text() + void UIParty::sync_buttons() { - if (party_id > 0) - { - std::string leader_name = resolve_leader_name(party_leader_id, party_members); - party_info.change_text("Leader: " + leader_name + " Members: " + std::to_string(party_members.size())); - } - else - { - party_info.change_text("Not currently in a party"); - } - - if (pending_party_invite_id > 0) - { - invite_info.change_text("Pending invite: " + pending_party_inviter); - } - else - { - invite_info.change_text("Pending invite: none"); - } + int32_t me = Stage::get().get_player().get_oid(); + bool in_party = party_id > 0; + bool leading = in_party && party_leader_id == me; + bool picked_other = picked_member >= 0 && picked_member < static_cast(party_members.size()) + && party_members[picked_member].id != me; + + buttons[BT_CREATE]->set_state(in_party ? Button::DISABLED : Button::NORMAL); + buttons[BT_INVITE]->set_state(in_party && !leading ? Button::DISABLED : Button::NORMAL); + buttons[BT_LEAVE]->set_state(in_party ? Button::NORMAL : Button::DISABLED); + buttons[BT_EXPEL]->set_state(leading && picked_other ? Button::NORMAL : Button::DISABLED); + buttons[BT_LEADER]->set_state(leading && picked_other ? Button::NORMAL : Button::DISABLED); + + bool invited = pending_party_invite_id > 0; + buttons[BT_ACCEPT]->set_active(invited); + buttons[BT_DENY]->set_active(invited); + } + void UIParty::sync_text() + { + int32_t me = Stage::get().get_player().get_oid(); for (size_t i = 0; i < PARTY_SIZE; i++) { if (i >= party_members.size()) { - if (i == 0) - { - member_lines[i].change_color(Text::LIGHTGREY); - member_lines[i].change_text("No party members cached."); - } - else - { - member_lines[i].change_text(""); - } + names[i].change_text(""); + jobs[i].change_text(""); + levels[i].change_text(""); continue; } const UIChatbar::PartyMember& member = party_members[i]; - std::string leader_tag = member.id == party_leader_id ? " [Leader]" : ""; - std::string hp_tag; - if (member.max_hp > 0) - { - hp_tag = " HP " + std::to_string(member.hp) + "/" + std::to_string(member.max_hp); - } - - member_lines[i].change_color(member.channel >= 0 ? Text::WHITE : Text::LIGHTGREY); - member_lines[i].change_text(member.name + " Lv." + std::to_string(member.level) + leader_tag + hp_tag); + bool online = is_online(member); + names[i].change_text(member.name); + names[i].change_color(member.id == me ? Text::BLUE : (online ? Text::BLACK : Text::DARKGREY)); + jobs[i].change_text(Job(static_cast(member.job_id)).get_name()); + levels[i].change_text(std::to_string(member.level)); } - } - void UIParty::draw_button_labels() const - { - for (const auto& label : button_labels) - { - auto bit = buttons.find(label.first); - if (bit == buttons.end() || !bit->second || !bit->second->is_active()) - { - continue; - } + empty_info.change_text(party_id > 0 ? "" : "Not in a party yet."); + invite_info.change_text(pending_party_invite_id > 0 ? pending_party_inviter + " invited you to their party." : ""); - Rectangle bounds = bit->second->bounds(position); - Point center(static_cast((bounds.l() + bounds.r()) / 2), static_cast((bounds.t() + bounds.b()) / 2 + 2)); - label.second.draw(center); - } + sync_buttons(); } } diff --git a/src/client/IO/UITypes/UIParty.h b/src/client/IO/UITypes/UIParty.h index ec00b84..b87349a 100644 --- a/src/client/IO/UITypes/UIParty.h +++ b/src/client/IO/UITypes/UIParty.h @@ -4,6 +4,8 @@ #include "../Components/Textfield.h" #include "../../Graphics/Geometry.h" +#include "../../Graphics/Text.h" +#include "../../Graphics/Texture.h" #include "UIChatBar.h" @@ -14,6 +16,10 @@ namespace jrc { + // The party, the way the old User List showed it: the Party tab of "Maple User List & Guild", members online + // and offline under their headers (name, job, level; the leader starred), the classic Create / Invite / Expel / + // Leave / Party Leader buttons, a name box for invites, and Accept / Deny when someone has invited you. + // Click a member to pick them for Expel or Party Leader. class UIParty : public UIDragElement { public: @@ -42,37 +48,54 @@ namespace jrc private: void send_invite(); void sync_text(); - void draw_button_labels() const; + // which buttons make sense now (in a party or not, leader or not, someone picked or not) + void sync_buttons(); + // the member row under the cursor (index into party_members), or -1 + int32_t member_at(Point cursorpos) const; + // where a member's row is drawn, relative to the window (online rows first, then offline) + Point row_position(size_t slot, bool online) const; enum Buttons : uint16_t { BT_CLOSE, BT_CREATE, + BT_INVITE, + BT_EXPEL, BT_LEAVE, + BT_LEADER, BT_ACCEPT, - BT_DENY, - BT_INVITE + BT_DENY }; static constexpr size_t PARTY_SIZE = 6; - ColorBox background; - ColorBox header; - ColorBox divider; + Texture backgrnd; + Texture header_online; + Texture header_offline; + Texture columns; + Texture row; + Texture separator; + Texture leader_star; + std::array tabs; + std::array tab_x; + ColorBox name_box; + ColorBox name_box_edge; + ColorBox picked_row; Text title; - Text party_info; + Text name_label; Text invite_info; - Text invite_label; - Text help_info; - std::array member_lines; - std::map button_labels; + Text empty_info; + std::array names; + std::array jobs; + std::array levels; Textfield invite_field; int32_t party_id; int32_t party_leader_id; int32_t pending_party_invite_id; + int32_t picked_member; std::string pending_party_inviter; std::vector party_members; }; diff --git a/src/client/IO/UITypes/UIQuestLog.cpp b/src/client/IO/UITypes/UIQuestLog.cpp index 17d4bd8..d729d95 100644 --- a/src/client/IO/UITypes/UIQuestLog.cpp +++ b/src/client/IO/UITypes/UIQuestLog.cpp @@ -61,7 +61,7 @@ namespace jrc tab_fill[i] = basic["Tab3"]["fill" + state]; tab_right[i] = basic["Tab3"]["right" + state]; } - buttons[BT_CLOSE] = std::make_unique(basic["BtClose"], WIDTH - 18, 6); + buttons[BT_CLOSE] = std::make_unique(basic["BtClose"], WIDTH - 18, 12); buttons[BT_DETAIL_CLOSE] = std::make_unique(basic["BtMin"], WIDTH + DETAIL_WIDTH - 18, 6); buttons[BT_FORFEIT] = std::make_unique(quest["BtGiveup"], WIDTH + 243, 373); buttons[BT_HELPER] = std::make_unique(quest["BtAlert"], WIDTH + 151, 373); diff --git a/src/client/IO/UITypes/UIQuestTracker.cpp b/src/client/IO/UITypes/UIQuestTracker.cpp index 50dffd7..38ac41c 100644 --- a/src/client/IO/UITypes/UIQuestTracker.cpp +++ b/src/client/IO/UITypes/UIQuestTracker.cpp @@ -23,6 +23,7 @@ namespace jrc { auto art = nl::nx::ui["UIWindow.img"]["QuestAlarm"]; top = art["backgrndmax"]; + top_min = art["backgrndmin"]; center = art["backgrndcenter"]; bottom = art["backgrndbottom"]; header = {Text::A11B, Text::LEFT, Text::DARKGREY}; @@ -41,7 +42,10 @@ namespace jrc void UIQuestTracker::draw(float inter) const { - top.draw(position); + if (Stage::get().get_spirit().active()) + return; // (nor quests) + // (rolled up it's the shorter header art: the full one hung 5 px below the rolled-up window) + (minimized ? top_min : top).draw(position); header.draw(position + Point(24, 3)); if (!minimized) { @@ -77,6 +81,8 @@ namespace jrc bool UIQuestTracker::is_in_range(Point cursorpos) const { + if (Stage::get().get_spirit().active()) + return false; if (in_drag_area(cursorpos)) return true; // Objective text still lets gameplay clicks through. for (const auto& button : buttons) @@ -193,7 +199,7 @@ namespace jrc buttons[BT_MIN]->set_active(!minimized); buttons[BT_MAX]->set_active(minimized); for (size_t i = 0; i < MAX_TRACKED; ++i) buttons[BT_QUEST0 + i]->set_active(!minimized && i < tracked.size()); - dimension = {PANEL_WIDTH, static_cast(minimized ? 25 : body_height + 30)}; + dimension = {PANEL_WIDTH, static_cast(minimized ? top_min.get_dimensions().y() : body_height + 30)}; keep_on_screen(); } } diff --git a/src/client/IO/UITypes/UIQuestTracker.h b/src/client/IO/UITypes/UIQuestTracker.h index 3d03d0c..af9512b 100644 --- a/src/client/IO/UITypes/UIQuestTracker.h +++ b/src/client/IO/UITypes/UIQuestTracker.h @@ -42,20 +42,22 @@ namespace jrc void open_journal(int16_t qid); static constexpr int16_t PANEL_WIDTH = 223; - static constexpr int16_t TOP_MARGIN = 90; - static constexpr int16_t RIGHT_MARGIN = 8; + // (top right, just under the scrolling notice, level with the minimap at the top left) + static constexpr int16_t TOP_MARGIN = 20; + static constexpr int16_t RIGHT_MARGIN = 2; static constexpr size_t MAX_TRACKED = 5; const Inventory& inventory; const Questlog& questlog; int16_t screen_width; int16_t screen_height; - bool minimized = false; + bool minimized = true; // (rolled up until opened, or a quest is picked to track) int16_t body_height = 0; std::set excluded; std::vector preferred; std::vector tracked; Texture top; + Texture top_min; Texture center; Texture bottom; Text header; diff --git a/src/client/IO/UITypes/UIQuickSlot.cpp b/src/client/IO/UITypes/UIQuickSlot.cpp new file mode 100644 index 0000000..8661546 --- /dev/null +++ b/src/client/IO/UITypes/UIQuickSlot.cpp @@ -0,0 +1,407 @@ +#include "UIQuickSlot.h" +#include "UIKeyConfig.h" + +#include "../UI.h" +#include "../Components/MapleButton.h" + +#include "../../Constants.h" +#include "../../Data/ItemData.h" +#include "../../Data/SkillData.h" +#include "../../Graphics/GraphicsGL.h" +#include "../../Gameplay/Stage.h" +#include "../../Net/Packets/PlayerPackets.h" + +#include "nlnx/nx.hpp" + +#include + +#ifdef MS_PLATFORM_WASM +#include +#endif +#include +#include + +namespace jrc +{ + constexpr std::array UIQuickSlot::KEYS; + + namespace + { + // The status bar's anchor, which the quick slot's art is placed from (see UIStatusbar::POSITION) + constexpr int16_t ANCHOR_X = 512; + // where the panel's art sits from the anchor (its origin), and the slots inside it: 4 across, 2 down + constexpr Point PANEL_OFFSET = { 143, -143 }; + constexpr int16_t SLOT_X = 8; + constexpr int16_t SLOT_Y = 18; + constexpr int16_t SLOT_STRIDE = 33; + constexpr int16_t SLOT_W = 28; + constexpr int16_t SLOT_H = 26; + constexpr int16_t PANEL_W = 145; + constexpr int16_t PANEL_H = 93; + // the status bar's visible top edge, from the anchor: the panel's bottom band belongs behind the bar, so it + // isn't drawn (or clickable) below this line, where the bar's own small buttons are + constexpr int16_t BAR_TOP = -65; + // the folded tab (BtOpen), from the anchor + constexpr Point TAB_OFFSET = { 143, -76 }; + constexpr int16_t TAB_H = 15; + // where a 32 px icon goes from a slot's top-left corner + constexpr Point ICON_SHIFT = { -2, -3 }; + // how often the slots look at the keys and the inventory again (updates: 8 ms each) + constexpr uint16_t REFRESH_TICKS = 30; + + constexpr const char* KEY_NAMES[UIQuickSlot::NUM_SLOTS] = { + "Shift", "Ins", "Home", "PgUp", "Ctrl", "Del", "End", "PgDn" + }; + + // A skill or potion picked up off a slot: let go on the map takes it off the key, on another slot swaps + class QuickSlotDragType : public Icon::Type + { + public: + QuickSlotDragType(uint8_t in_keycode, Keyboard::Mapping in_mapping) + : keycode(in_keycode), mapping(in_mapping) {} + + void drop_on_stage() const override + { + if (auto quickslot = UI::get().get_element()) + { + quickslot->set_key(keycode, {}); + } + } + + void drop_on_equips(Equipslot::Id) const override {} + void drop_on_items(InventoryType::Id, Equipslot::Id, int16_t, bool) const override {} + + void drop_on_bindings(Point cursorpos, bool remove) const override + { + if (remove) + { + return; + } + + // onto another slot (the two swap: see bind_at), or onto a key in the key config + if (auto quickslot = UI::get().get_element(); quickslot && quickslot->bind_at(cursorpos, mapping)) + { + return; + } + if (auto keyconfig = UI::get().get_element()) + { + keyconfig->stage_mapping(cursorpos, mapping); + } + } + + private: + uint8_t keycode; + Keyboard::Mapping mapping; + }; + } + + UIQuickSlot::UIQuickSlot() : open(true), refresh_ticks(0) + { + nl::node src = nl::nx::ui["StatusBar2.img"]["mainBar"]["quickSlot"]; + panel = src["quickSlot"]; + + buttons[BT_CLOSE] = std::make_unique(src["BtClose"]); + buttons[BT_OPEN] = std::make_unique(src["BtOpen"]); + buttons[BT_OPEN]->set_active(false); + + for (size_t i = 0; i < NUM_SLOTS; ++i) + { + labels[i] = { Text::A11M, Text::LEFT, Text::DARKGREY, KEY_NAMES[i] }; + } + + update_screen(Constants::viewwidth(), Constants::viewheight()); + refresh(); + active = true; + } + + void UIQuickSlot::update_screen(int16_t, int16_t new_height) + { + position = { ANCHOR_X, static_cast(new_height - Constants::VIEWYOFFSET) }; + dimension = { 0, 0 }; + } + + int16_t UIQuickSlot::panel_top() const + { + return panel_position().y(); + } + + Point UIQuickSlot::panel_position() const + { + return position + PANEL_OFFSET; + } + + Point UIQuickSlot::slot_position(size_t slot) const + { + return panel_position() + Point( + static_cast(SLOT_X + SLOT_STRIDE * (slot % 4)), + static_cast(SLOT_Y + SLOT_STRIDE * (slot / 4)) + ); + } + + int8_t UIQuickSlot::slot_at(Point cursorpos) const + { + if (!open) + { + return -1; + } + + for (size_t i = 0; i < NUM_SLOTS; ++i) + { + Point topleft = slot_position(i); + Rectangle area(topleft, topleft + Point(SLOT_W, SLOT_H)); + if (area.contains(cursorpos)) + { + return static_cast(i); + } + } + + return -1; + } + + bool UIQuickSlot::is_in_range(Point cursorpos) const + { + if (Stage::get().get_spirit().active()) + return false; + if (open) + { + Point topleft = panel_position(); + int16_t bottom = std::min(topleft.y() + PANEL_H, position.y() + BAR_TOP); + return Rectangle(topleft, Point(topleft.x() + PANEL_W, bottom)).contains(cursorpos); + } + + Point tab = position + TAB_OFFSET; + return Rectangle(tab, tab + Point(PANEL_W, TAB_H)).contains(cursorpos); + } + + void UIQuickSlot::draw(float alpha) const + { + if (Stage::get().get_spirit().active()) + return; // (nor a character's quick slots) + if (open) + { + Point topleft = panel_position(); + panel.draw_clipped(position, { topleft.y(), static_cast(position.y() + BAR_TOP) }); + + for (size_t i = 0; i < NUM_SLOTS; ++i) + { + Point slot = slot_position(i); + if (icons[i]) + { + // (an icon is drawn from its top-left corner, like the inventory's: 32 px square, centred over + // the 28 x 26 slot) + icons[i]->draw(slot + ICON_SHIFT); + } + if (glow[i] > 0.0f) + { + // a warm wash over the slot and a bright gold rim round it + float g = glow[i]; + GraphicsGL& gl = GraphicsGL::get(); + gl.drawrectangle(slot.x(), slot.y(), SLOT_W, SLOT_H, 1.0f, 0.85f, 0.3f, 0.35f * g); + gl.drawrectangle(slot.x() - 1, slot.y() - 1, SLOT_W + 2, 1, 1.0f, 0.9f, 0.4f, g); + gl.drawrectangle(slot.x() - 1, slot.y() + SLOT_H, SLOT_W + 2, 1, 1.0f, 0.9f, 0.4f, g); + gl.drawrectangle(slot.x() - 1, slot.y(), 1, SLOT_H, 1.0f, 0.9f, 0.4f, g); + gl.drawrectangle(slot.x() + SLOT_W, slot.y(), 1, SLOT_H, 1.0f, 0.9f, 0.4f, g); + } + labels[i].draw(slot + Point(1, -1)); + } + } + + UIElement::draw(alpha); + } + + void UIQuickSlot::update() + { + UIElement::update(); + + // (held: fully lit; let go: fades over ~0.15 s, so even a quick tap of a button is seen) + for (size_t i = 0; i < NUM_SLOTS; ++i) + { + if (UI::get().is_held(Keyboard::glfw_code(KEYS[i]))) + glow[i] = 1.0f; + else if (glow[i] > 0.0f) + glow[i] = std::max(0.0f, glow[i] - 0.055f); + } + + if (++refresh_ticks >= REFRESH_TICKS) + { + refresh_ticks = 0; + refresh(); + } + } + + void UIQuickSlot::refresh() + { + const Keyboard& keyboard = UI::get().get_keyboard(); + const Inventory& inventory = Stage::get().get_player().get_inventory(); + + for (size_t i = 0; i < NUM_SLOTS; ++i) + { + Keyboard::Mapping mapping = keyboard.get_maple_mapping(KEYS[i]); + bool changed = mapping != shown[i]; + shown[i] = mapping; + + if (mapping.type == KeyType::ITEM) + { + // a potion's count goes up and down: keep it current + int16_t count = static_cast(std::min(inventory.count_items(mapping.action), 32767)); + const Texture& icon = ItemData::get(mapping.action).get_icon(false); + if (changed || !icons[i]) + { + icons[i] = std::make_unique( + std::make_unique(KEYS[i], mapping), + icon, + count + ); + } + else + { + icons[i]->set_count(count); + } + tell_page(i, &icon, count); + } + else if (!changed) + { + continue; + } + else if (mapping.type == KeyType::SKILL) + { + icons[i] = std::make_unique( + std::make_unique(KEYS[i], mapping), + SkillData::get(mapping.action).get_icon(SkillData::NORMAL), + -1 + ); + tell_page(i, &SkillData::get(mapping.action).get_icon(SkillData::NORMAL), -1); + } + else if (nl::node art = nl::nx::ui["UIWindow.img"]["KeyConfig"]["icon"][std::to_string(mapping.action)]; + mapping.type != KeyType::NONE && art) + { + // an action, a menu or a face (Ctrl is Attack by default): shown with the key config's icon, so + // nobody drops a skill on it without seeing what it was + icons[i] = std::make_unique( + std::make_unique(KEYS[i], mapping), + Texture(art), + -1 + ); + Texture shown_art(art); + tell_page(i, &shown_art, -1); + } + else + { + icons[i].reset(); + tell_page(i, nullptr, -1); + } + } + } + + void UIQuickSlot::tell_page(size_t slot, const Texture* icon, int16_t count) + { +#ifdef MS_PLATFORM_WASM + // Phones show the quick slot as the page's own bar beside the game: each slot's picture (BGRA, from the + // game's files, kept only in the page's memory) and its count, sent when either changes. + const nl::bitmap* bmp = icon ? &icon->get_bitmap() : nullptr; + size_t id = bmp ? bmp->id() : 0; + if (id == told_icon[slot] && count == told_count[slot]) + return; + told_icon[slot] = id; + told_count[slot] = count; + const void* pixels = id ? bmp->data() : nullptr; + if (!pixels) + { + EM_ASM({ if (Module.onQuickSlot) Module.onQuickSlot($0, null, 0, 0, $1); }, static_cast(slot), count); + return; + } + int w = bmp->width(), h = bmp->height(); + EM_ASM({ if (Module.onQuickSlot) Module.onQuickSlot($0, HEAPU8.slice($1, $1 + $2 * $3 * 4), $2, $3, $4); }, + static_cast(slot), pixels, w, h, count); +#endif + } + + UIElement::CursorResult UIQuickSlot::send_cursor(bool pressed, Point cursorpos) + { + int8_t slot = slot_at(cursorpos); + if (slot >= 0 && icons[slot]) + { + if (pressed) + { + Point topleft = slot_position(slot) + ICON_SHIFT; + icons[slot]->start_drag(cursorpos - topleft); + UI::get().drag_icon(icons[slot].get()); + return { Cursor::GRABBING, true }; + } + + return { Cursor::CANGRAB, true }; + } + + return UIElement::send_cursor(pressed, cursorpos); + } + + void UIQuickSlot::send_icon(const Icon& icon, Point cursorpos) + { + // the icon's own kind knows what it is (a skill, a potion, a key from the key config): it calls bind_at + icon.drop_on_bindings(cursorpos, false); + } + + bool UIQuickSlot::bind_at(Point cursorpos, Keyboard::Mapping mapping) + { + int8_t slot = slot_at(cursorpos); + if (slot < 0) + { + return false; + } + + // the same skill or potion already on another slot moves here (it lives on one key at a time) + Keyboard& keyboard = UI::get().get_keyboard(); + for (size_t i = 0; i < NUM_SLOTS; ++i) + { + if (static_cast(i) != slot && keyboard.get_maple_mapping(KEYS[i]) == mapping) + { + Keyboard::Mapping displaced = keyboard.get_maple_mapping(KEYS[slot]); + set_key(KEYS[i], displaced); + } + } + + set_key(KEYS[slot], mapping); + return true; + } + + Keyboard::Mapping UIQuickSlot::set_key(uint8_t keycode, Keyboard::Mapping mapping) + { + Keyboard& keyboard = UI::get().get_keyboard(); + Keyboard::Mapping previous = keyboard.get_maple_mapping(keycode); + if (previous == mapping) + { + return previous; + } + + std::vector> update = { + { keycode, static_cast(mapping.type), mapping.action } + }; + ChangeKeyMapPacket(update).dispatch(); + + if (mapping.type == KeyType::NONE) + { + keyboard.remove(keycode); + } + else + { + keyboard.assign(keycode, static_cast(mapping.type), mapping.action); + } + + // the key config window keeps its own copy of the keys while it's around + if (auto keyconfig = UI::get().get_element()) + { + keyconfig->sync_from_keyboard(); + } + + refresh(); + return previous; + } + + Button::State UIQuickSlot::button_pressed(uint16_t buttonid) + { + open = buttonid == BT_OPEN; + buttons[BT_OPEN]->set_active(!open); + buttons[BT_CLOSE]->set_active(open); + return Button::NORMAL; + } +} diff --git a/src/client/IO/UITypes/UIQuickSlot.h b/src/client/IO/UITypes/UIQuickSlot.h new file mode 100644 index 0000000..8220270 --- /dev/null +++ b/src/client/IO/UITypes/UIQuickSlot.h @@ -0,0 +1,81 @@ +#pragma once +#include "../UIElement.h" + +#include "../Keyboard.h" +#include "../Components/Icon.h" + +#include "../../Graphics/Text.h" +#include "../../Graphics/Texture.h" + +#include +#include + +namespace jrc +{ + // The quick slot beside the status bar: the eight keys Shift, Ins, Home, PgUp / Ctrl, Del, End, PgDn and the + // skill or potion on each, like the original. Drop a skill (from the skill book) or a potion (from the + // inventory) on a slot to put it on that key; drag one off to take it off, or onto another slot to swap them. + // The tab folds it away. Changes go to the server like the key config's, so they follow the character. + class UIQuickSlot : public UIElement + { + public: + static constexpr Type TYPE = QUICKSLOT; + static constexpr bool FOCUSED = false; + static constexpr bool TOGGLED = false; + + UIQuickSlot(); + + void draw(float alpha) const override; + void update() override; + void update_screen(int16_t new_width, int16_t new_height) override; + bool is_in_range(Point cursorpos) const override; + CursorResult send_cursor(bool pressed, Point cursorpos) override; + void send_icon(const Icon& icon, Point cursorpos) override; + + // A skill or item let go over the quick slot: put it on the key under the cursor. False when the cursor + // isn't over a slot (the caller can try somewhere else). + bool bind_at(Point cursorpos, Keyboard::Mapping mapping); + // Put a mapping on one of the eight keys (an empty one clears it); returns what was there + Keyboard::Mapping set_key(uint8_t keycode, Keyboard::Mapping mapping); + + static constexpr size_t NUM_SLOTS = 8; + // (open: the panel's top edge, so the "gained an item" log can sit above it instead of under it) + bool is_open() const { return open; } + int16_t panel_top() const; + // the keys, in slot order (MapleStory key codes) + static constexpr std::array KEYS = { 42, 82, 71, 73, 29, 83, 79, 81 }; + + protected: + Button::State button_pressed(uint16_t buttonid) override; + + private: + // which slot is under the cursor, or -1 + int8_t slot_at(Point cursorpos) const; + // a slot's top-left corner, on screen + Point slot_position(size_t slot) const; + // the panel's top-left corner, on screen (its art is placed from the status bar's anchor) + Point panel_position() const; + // the icons, from what the keys hold right now + void refresh(); + + enum Buttons : uint16_t + { + BT_OPEN, + BT_CLOSE + }; + + Texture panel; + bool open; + uint16_t refresh_ticks; + // (phones) what the page's bar was last told each slot shows: its icon, or none, and the count + std::array told_icon = {}; + std::array told_count = {}; + void tell_page(size_t slot, const Texture* icon, int16_t count); + + std::array shown; + std::array, NUM_SLOTS> icons; + std::array labels; + // how lit each slot is (1 while its key is held, fading out after), so a press shows even on an empty slot + std::array glow = {}; + }; +} diff --git a/src/client/IO/UITypes/UISkillBook.cpp b/src/client/IO/UITypes/UISkillBook.cpp index 17cb353..fa78c1c 100644 --- a/src/client/IO/UITypes/UISkillBook.cpp +++ b/src/client/IO/UITypes/UISkillBook.cpp @@ -16,6 +16,7 @@ // along with this program. If not, see . // ////////////////////////////////////////////////////////////////////////////// #include "UISkillBook.h" +#include "UIQuickSlot.h" #include "../Components/MapleButton.h" #include "../Components/TwoSpriteButton.h" @@ -47,6 +48,10 @@ namespace jrc void drop_on_items(InventoryType::Id, Equipslot::Id, int16_t, bool) const override {} void drop_on_bindings(Point cursorposition, bool remove) const override { + Keyboard::Mapping slotted{ KeyType::SKILL, skill_id }; + if (auto quickslot = UI::get().get_element(); quickslot && !remove && quickslot->bind_at(cursorposition, slotted)) + return; + if (auto keyconfig = UI::get().get_element()) { Keyboard::Mapping mapping{ KeyType::SKILL, skill_id }; @@ -233,6 +238,8 @@ namespace jrc change_sp(stats.get_stat(Maplestat::SP)); dimension = { 174, 299 }; + // the X in the corner, like the stats and equipment windows + buttons[BT_CLOSE] = std::make_unique(nl::nx::ui["Basic.img"]["BtClose"], dimension.x() - 18, 12); } void UISkillbook::draw(float alpha) const @@ -277,6 +284,9 @@ namespace jrc { switch (id) { + case BT_CLOSE: + deactivate(); + return Button::NORMAL; case BT_TAB0: case BT_TAB1: case BT_TAB2: diff --git a/src/client/IO/UITypes/UISkillBook.h b/src/client/IO/UITypes/UISkillBook.h index bdb38cc..a8b0ba1 100644 --- a/src/client/IO/UITypes/UISkillBook.h +++ b/src/client/IO/UITypes/UISkillBook.h @@ -114,7 +114,8 @@ namespace jrc BT_SPUP0, BT_SPUP1, BT_SPUP2, - BT_SPUP3 + BT_SPUP3, + BT_CLOSE }; static constexpr int16_t ROWS = 4; diff --git a/src/client/IO/UITypes/UIStatsInfo.cpp b/src/client/IO/UITypes/UIStatsInfo.cpp index 114f649..52a6743 100644 --- a/src/client/IO/UITypes/UIStatsInfo.cpp +++ b/src/client/IO/UITypes/UIStatsInfo.cpp @@ -60,7 +60,7 @@ namespace jrc buttons[BT_DETAILOPEN] = std::make_unique(src["BtDetailOpen"]); buttons[BT_DETAILCLOSE] = std::make_unique(src["BtDetailClose"]); buttons[BT_DETAILCLOSE]->set_active(false); - buttons[BT_CLOSE] = std::make_unique(nl::nx::ui["Basic.img"]["BtClose"], 194, 6); + buttons[BT_CLOSE] = std::make_unique(nl::nx::ui["Basic.img"]["BtClose"], 194, 12); update_ap(); diff --git a/src/client/IO/UITypes/UIStatusBar.cpp b/src/client/IO/UITypes/UIStatusBar.cpp index b394dd6..c3aa533 100644 --- a/src/client/IO/UITypes/UIStatusBar.cpp +++ b/src/client/IO/UITypes/UIStatusBar.cpp @@ -16,8 +16,17 @@ // along with this program. If not, see . // ////////////////////////////////////////////////////////////////////////////// #include "UIStatusBar.h" +#include +#include + +#ifdef MS_PLATFORM_WASM +#include +#endif +#include "UINotice.h" +#include "../../Graphics/GraphicsGL.h" #include "../UI.h" +#include "../../Gameplay/Stage.h" #include "../Components/MapleButton.h" #include "../../Character/ExpTable.h" @@ -72,8 +81,13 @@ namespace jrc buttons[BT_CASHSHOP] = std::make_unique(mainbar["BtCashShop"]); buttons[BT_TRADE] = std::make_unique(mainbar["BtMTS"]); + // The post-Chaos bar lays out Cash Shop, Menu and System in one row; its MTS art is a leftover that sits on + // top of them (and nothing here handles it), so it stays hidden. + buttons[BT_TRADE]->set_active(false); buttons[BT_MENU] = std::make_unique(mainbar["BtMenu"]); + // (Menu is Dordo Story's STREAM NOW, drawn over in draw(); System does nothing yet: greyed out) buttons[BT_OPTIONS] = std::make_unique(mainbar["BtSystem"]); + buttons[BT_OPTIONS]->set_state(Button::DISABLED); buttons[BT_CHARACTER] = std::make_unique(mainbar["BtCharacter"]); buttons[BT_STATS] = std::make_unique(mainbar["BtStat"]); @@ -81,6 +95,10 @@ namespace jrc buttons[BT_INVENTORY] = std::make_unique(mainbar["BtInven"]); buttons[BT_EQUIPS] = std::make_unique(mainbar["BtEquip"]); buttons[BT_SKILL] = std::make_unique(mainbar["BtSkill"]); + // (Whisper, Call GM and the character sheet aren't built yet: greyed out) + buttons[BT_WHISPER]->set_state(Button::DISABLED); + buttons[BT_CALLGM]->set_state(Button::DISABLED); + buttons[BT_CHARACTER]->set_state(Button::DISABLED); update_layout_position(); } @@ -89,6 +107,94 @@ namespace jrc { UIElement::draw(alpha); + // STREAM NOW on the Menu button: its own frame stays, the inside becomes a rounded plate with a record dot and + // "STREAM" (red, a white dot and "LIVE" while we're streaming; a little lighter under the cursor) + if (auto menu = buttons.find(BT_MENU); menu != buttons.end()) + { + // (greyed like the rest of a monster spirit's bar) + bool greyed = menu->second->get_state() == Button::DISABLED; + Rectangle r = menu->second->bounds(position); + bool live = false; +#ifdef MS_PLATFORM_WASM + live = EM_ASM_INT({ return Module.dordoLive ? 1 : 0; }) != 0; +#endif + bool lit = menu->second->get_state() == Button::MOUSEOVER || menu->second->get_state() == Button::PRESSED; + float glow = lit ? 0.08f : 0.0f; + // (inside the button's rim: 75 x 35 art, rim ~3 px; down to its bottom edge, so none of MENU shows) + int16_t x = r.l() + 4, y = r.t() + 4, w = r.width() - 8, h = r.height() - 6; + auto rounded = [](int16_t x, int16_t y, int16_t w, int16_t h, float cr, float cg, float cb) { + GraphicsGL::get().drawrectangle(x + 2, y, w - 4, 1, cr, cg, cb, 1.0f); + GraphicsGL::get().drawrectangle(x + 1, y + 1, w - 2, 1, cr, cg, cb, 1.0f); + GraphicsGL::get().drawrectangle(x, y + 2, w, h - 4, cr, cg, cb, 1.0f); + GraphicsGL::get().drawrectangle(x + 1, y + h - 2, w - 2, 1, cr, cg, cb, 1.0f); + GraphicsGL::get().drawrectangle(x + 2, y + h - 1, w - 4, 1, cr, cg, cb, 1.0f); + }; + if (greyed) + { + rounded(x, y, w, h, 0.25f, 0.25f, 0.27f); + rounded(x + 1, y + 1, w - 2, h - 2, 0.50f, 0.50f, 0.53f); + rounded(x + 2, y + 2, w - 4, (h - 4) / 2, 0.60f, 0.60f, 0.63f); + } + else if (live) + { + rounded(x, y, w, h, 0.45f, 0.06f, 0.08f); + rounded(x + 1, y + 1, w - 2, h - 2, 0.86f + glow, 0.18f + glow, 0.20f + glow); + rounded(x + 2, y + 2, w - 4, (h - 4) / 2, 0.96f, 0.42f + glow, 0.42f + glow); + } + else + { + rounded(x, y, w, h, 0.20f, 0.12f, 0.30f); + rounded(x + 1, y + 1, w - 2, h - 2, 0.42f + glow, 0.27f + glow, 0.66f + glow); + rounded(x + 2, y + 2, w - 4, (h - 4) / 2, 0.58f + glow, 0.44f + glow, 0.80f + glow); + } + // the dot: red on purple; white (blinking) on red + int16_t cx = x + 10, cy = y + h / 2, rad = 4; + bool dot = !live || (std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count() / 600) % 2 == 0; + if (dot) + { + for (int16_t dy = -rad; dy <= rad; dy++) + { + int16_t half = static_cast(std::lround(std::sqrt(static_cast(rad * rad - dy * dy)))); + if (greyed) + GraphicsGL::get().drawrectangle(cx - half, cy + dy, half * 2 + 1, 1, 0.35f, 0.35f, 0.37f, 1.0f); + else if (live) + GraphicsGL::get().drawrectangle(cx - half, cy + dy, half * 2 + 1, 1, 1.0f, 1.0f, 1.0f, 1.0f); + else + GraphicsGL::get().drawrectangle(cx - half, cy + dy, half * 2 + 1, 1, 0.95f, 0.16f, 0.24f, 1.0f); + } + } + const Text& label = live ? streamlive : streamnow; + Point at(static_cast(x + 10 + (w - 10) / 2), static_cast(cy - 6)); + (live ? streamliveshadow : streamshadow).draw(at + Point(1, 1)); + label.draw(at); + } + + // A monster spirit: level "?", "Monster Spirit", the monster it holds ("???" for none) and that monster's HP + // (grey 0/0 and an empty gauge holding nothing); no MP, no EXP. + const Spirit& spirit = Stage::get().get_spirit(); + if (spirit.active()) + { + hpbar.draw(position + Point(-261, -31)); + int32_t maxhp = spirit.get_maxhp(); + if (maxhp > 0) + { + statset.draw( + "[" + std::to_string(spirit.get_hp()) + "/" + std::to_string(maxhp) + "]", + position + Point(-124, -29) + ); + } + else + { + statset.draw("[0/0]", DrawArgument(position + Point(-124, -29), Color(0.55f, 0.55f, 0.55f, 1.0f))); + } + spiritlevel.draw(position + Point(-478, -33)); + joblabel.draw(position + Point(-435, -21)); + namelabel.draw(position + Point(-435, -36)); + chatbar.draw(alpha); + return; + } + expbar.draw(position + Point(-261, -15)); hpbar.draw(position + Point(-261, -31)); mpbar.draw(position + Point(-90, -31)); @@ -131,12 +237,31 @@ namespace jrc chatbar.update(); - expbar.update(getexppercent()); - hpbar.update(gethppercent()); - mpbar.update(getmppercent()); + const Spirit& spirit = Stage::get().get_spirit(); + if (spirit.active()) + { + int32_t maxhp = spirit.get_maxhp(); + hpbar.update(maxhp > 0 ? static_cast(spirit.get_hp()) / maxhp : 0.0f); + namelabel.change_text("Monster Spirit"); + joblabel.change_text(spirit.held_name().empty() ? "???" : spirit.held_name()); + // (nothing on the bar is for a spirit) + for (auto& button : buttons) + { + if (button.second && button.second->get_state() != Button::DISABLED) + { + button.second->set_state(Button::DISABLED); + } + } + } + else + { + expbar.update(getexppercent()); + hpbar.update(gethppercent()); + mpbar.update(getmppercent()); - namelabel.change_text(stats.get_name()); - joblabel.change_text(stats.get_jobname()); + namelabel.change_text(stats.get_name()); + joblabel.change_text(stats.get_jobname()); + } for (auto iter : message_cooldowns) { @@ -155,11 +280,50 @@ namespace jrc Button::State UIStatusbar::button_pressed(uint16_t id) { + if (Stage::get().get_spirit().active()) + { + return Button::DISABLED; + } + switch (id) + { + case BT_WHISPER: + case BT_CALLGM: + case BT_CHARACTER: + return Button::DISABLED; + default: + break; + } + switch (id) { case BT_CASHSHOP: UI::get().send_menu(KeyAction::CASHSHOP); return Button::NORMAL; + case BT_MENU: + { + // STREAM NOW: the game asks first, then the page goes live (or, live already, offers to stop) + if (Stage::get().get_spirit().active()) + return Button::NORMAL; + bool live = false; +#ifdef MS_PLATFORM_WASM + live = EM_ASM_INT({ return Module.dordoLive ? 1 : 0; }) != 0; +#endif + UI::get().emplace( + live ? "Stop your live stream?" : "Begin live streaming? Anyone with the link can watch you play.", + [live](bool yes) { + if (!yes) + return; +#ifdef MS_PLATFORM_WASM + if (live) + EM_ASM({ if (Module.onStreamStop) Module.onStreamStop(); }); + else + EM_ASM({ if (Module.onStreamStart) Module.onStreamStart(); }); +#endif + }); + return Button::NORMAL; + } + case BT_OPTIONS: + return Button::DISABLED; case BT_STATS: UI::get().send_menu(KeyAction::CHARSTATS); return Button::NORMAL; @@ -190,6 +354,12 @@ namespace jrc return bounds.contains(cursorpos) || chatbar.is_in_range(cursorpos); } + void UIStatusbar::send_scroll(double yoffset) + { + // (the bar itself doesn't scroll: the wheel over it is for the chat) + chatbar.send_scroll(yoffset); + } + bool UIStatusbar::remove_cursor(bool clicked, Point cursorpos) { if (chatbar.remove_cursor(clicked, cursorpos)) diff --git a/src/client/IO/UITypes/UIStatusBar.h b/src/client/IO/UITypes/UIStatusBar.h index c42cd01..95f3dbb 100644 --- a/src/client/IO/UITypes/UIStatusBar.h +++ b/src/client/IO/UITypes/UIStatusBar.h @@ -48,6 +48,8 @@ namespace jrc void update() override; bool is_in_range(Point cursorpos) const override; + + void send_scroll(double yoffset) override; bool remove_cursor(bool clicked, Point cursorpos) override; CursorResult send_cursor(bool pressed, Point cursorpos) override; @@ -109,6 +111,13 @@ namespace jrc Charset levelset; Text namelabel; Text joblabel; + // (a monster spirit's level: "?") + Text spiritlevel = { Text::A13B, Text::LEFT, Text::WHITE, "?" }; + // (Dordo Story's STREAM NOW button, over the Menu button) + Text streamnow = { Text::A11B, Text::CENTER, Text::WHITE, "STREAM" }; + Text streamlive = { Text::A11B, Text::CENTER, Text::WHITE, "LIVE" }; + Text streamshadow = { Text::A11B, Text::CENTER, Text::BLACK, "STREAM" }; + Text streamliveshadow = { Text::A11B, Text::CENTER, Text::BLACK, "LIVE" }; Animation hpanimation; Animation mpanimation; }; diff --git a/src/client/IO/UITypes/UIStatusMessenger.cpp b/src/client/IO/UITypes/UIStatusMessenger.cpp index c3d0018..a2187b6 100644 --- a/src/client/IO/UITypes/UIStatusMessenger.cpp +++ b/src/client/IO/UITypes/UIStatusMessenger.cpp @@ -1,4 +1,10 @@ #include "UIStatusMessenger.h" +#include "../../Audio/Audio.h" +#include "../Components/QuestText.h" +#include "../../Data/QuestData.h" +#include "../../Gameplay/Stage.h" +#include "UIQuickSlot.h" +#include "../UI.h" #include "../UI.h" #include "../Components/MapleButton.h" @@ -66,7 +72,26 @@ namespace jrc void UIStatusMessenger::draw(float inter) const { + // quest hints, gently: centred near the top, fading in and out + int16_t hy = 74; + for (const QuestHint& hint : hints) + { + float a = hint.ticks < 40 ? hint.ticks / 40.0f : hint.ticks > 320 ? std::max(0.0f, (440 - hint.ticks) / 120.0f) : 1.0f; + int16_t cx = static_cast(screen_width / 2); + hint.shadow.draw(DrawArgument(Point(cx + 1, hy + 1), a * 0.8f)); + hint.text.draw(DrawArgument(Point(cx, hy), a)); + hy += 18; + } + Point infopos = status_anchor; + // (the quick slot open covers the bottom right: the log starts just above it, and climbs from there) + if (auto quickslot = UI::get().get_element()) + { + if (quickslot->is_active() && quickslot->is_open()) + { + infopos.set_y(std::min(infopos.y(), static_cast(quickslot->panel_top() - 22))); + } + } for (const StatusInfo& info : statusinfos) { info.draw(infopos, inter); @@ -79,8 +104,108 @@ namespace jrc } } + void UIStatusMessenger::show_hint(const std::string& text) + { + hints.push_back({ Text(Text::A12B, Text::CENTER, Text::YELLOW, text), + Text(Text::A12B, Text::CENTER, Text::BLACK, text), 0 }); + if (hints.size() > 4) + hints.pop_front(); + } + + void UIStatusMessenger::watch_quests() + { + if (Stage::get().get_spirit().active()) + return; + const Player& player = Stage::get().get_player(); + const Questlog& quests = player.get_quests(); + const Inventory& inventory = player.get_inventory(); + + std::set active; + for (const auto& entry : quests.get_started()) + { + int16_t qid = entry.first; + active.insert(qid); + const QuestData& data = QuestData::get(qid); + if (!data.is_valid()) + continue; + // (the first look at a quest only takes note: no hints for what was already there) + bool first = quests_seen.insert(qid).second; + bool all_met = true, any = false; + + const auto& items = data.get_requirements(false).items; + for (size_t i = 0; i < items.size(); ++i) + { + if (items[i].count <= 0) + continue; + any = true; + int32_t have = static_cast(inventory.count_items(items[i].id)); + auto key = std::make_pair(qid, static_cast(i)); + auto was = quest_counts.find(key); + if (!first && was != quest_counts.end() && have > was->second && was->second < items[i].count) + show_hint(QuestText::item_name(items[i].id) + " " + std::to_string(std::min(have, items[i].count)) + + " / " + std::to_string(items[i].count)); + quest_counts[key] = have; + all_met = all_met && have >= items[i].count; + } + + const auto& mobs = data.get_mob_requirements(); + for (size_t i = 0; i < mobs.size(); ++i) + { + if (mobs[i].count <= 0) + continue; + any = true; + int32_t done = quests.get_mob_progress(qid, i); + auto key = std::make_pair(qid, static_cast(1000 + i)); + auto was = quest_counts.find(key); + if (!first && was != quest_counts.end() && done > was->second && was->second < mobs[i].count) + show_hint(QuestText::mob_name(mobs[i].id) + " " + std::to_string(std::min(done, mobs[i].count)) + + " / " + std::to_string(mobs[i].count)); + quest_counts[key] = done; + all_met = all_met && done >= mobs[i].count; + } + + // everything it needs: the chime (once), as the quest's NPC gets the book to hand it in + if (any && all_met) + { + if (quests_ready.insert(qid).second && !first) + { + static const Sound alert(nl::nx::sound["Game.img"]["QuestAlert"]); + alert.play(); + show_hint(data.get_name() + " - ready to hand in!"); + } + } + else + { + quests_ready.erase(qid); + } + } + + // (finished or given up: forgotten, so taking it again starts fresh) + for (auto it = quests_seen.begin(); it != quests_seen.end();) + { + if (active.count(*it)) + { + ++it; + continue; + } + quests_ready.erase(*it); + for (auto c = quest_counts.begin(); c != quest_counts.end();) + c = c->first.first == *it ? quest_counts.erase(c) : std::next(c); + it = quests_seen.erase(it); + } + } + void UIStatusMessenger::update() { + if (++quest_watch_ticks >= 30) + { + quest_watch_ticks = 0; + watch_quests(); + } + // (a hint lives ~3.5 s: 440 steps) + for (auto it = hints.begin(); it != hints.end();) + it = ++it->ticks > 440 ? hints.erase(it) : std::next(it); + for (auto iter = statusinfos.begin(); iter != statusinfos.end();) { if (iter->update()) diff --git a/src/client/IO/UITypes/UIStatusMessenger.h b/src/client/IO/UITypes/UIStatusMessenger.h index 7a01662..5975edc 100644 --- a/src/client/IO/UITypes/UIStatusMessenger.h +++ b/src/client/IO/UITypes/UIStatusMessenger.h @@ -1,4 +1,6 @@ #pragma once +#include +#include #include "../UIWindow.h" #include "../../Graphics/Geometry.h" @@ -55,6 +57,22 @@ namespace jrc void position_changed() override; private: + // (Dordo Story) quests' progress, watched: a soft hint at the top of the screen when a started quest's item + // or monster count goes up ("Old Wooden Board 3 / 10"), and a chime when one has everything it needs + struct QuestHint + { + Text text; + Text shadow; + int16_t ticks; + }; + std::list hints; + std::map, int32_t> quest_counts; + std::set quests_seen; + std::set quests_ready; + uint16_t quest_watch_ticks = 0; + void watch_quests(); + void show_hint(const std::string& text); + void update_layout(); void draw_party_invite(float alpha) const; void draw_button_labels() const; diff --git a/src/client/IO/UITypes/UIStream.cpp b/src/client/IO/UITypes/UIStream.cpp new file mode 100644 index 0000000..fd3291f --- /dev/null +++ b/src/client/IO/UITypes/UIStream.cpp @@ -0,0 +1,178 @@ +////////////////////////////////////////////////////////////////////////////// +// This file is part of the Journey MMORPG client (Dordo Story's changes) // +// // +// This program is free software: you can redistribute it and/or modify // +// it under the terms of the GNU Affero General Public License as // +// published by the Free Software Foundation, either version 3 of the // +// License, or (at your option) any later version. // +////////////////////////////////////////////////////////////////////////////// +#include "UIStream.h" +#include "UINotice.h" + +#include "../UI.h" +#include "../Components/AreaButton.h" +#include "../../Constants.h" +#include "../../Graphics/GraphicsGL.h" + +#include +#include + +#ifdef MS_PLATFORM_WASM +#include +#endif + +namespace jrc +{ + namespace + { + // (the frame's colours: the game's blue-grey windows, with a pale body) + void plate(int16_t x, int16_t y, int16_t w, int16_t h, float r, float g, float b, float a = 1.0f) + { + GraphicsGL::get().drawrectangle(x, y, w, h, r, g, b, a); + } + + void button_plate(Rectangle r, bool lit, float cr, float cg, float cb) + { + float glow = lit ? 0.08f : 0.0f; + plate(r.l(), r.t(), r.width(), r.height(), cr * 0.45f, cg * 0.45f, cb * 0.45f); + plate(r.l() + 1, r.t() + 1, r.width() - 2, r.height() - 2, cr + glow, cg + glow, cb + glow); + plate(r.l() + 1, r.t() + 1, r.width() - 2, (r.height() - 2) / 2, 1.0f, 1.0f, 1.0f, 0.18f); + } + } + + UIStream::UIStream() : UIDragElement(Point(WIDTH - 22, HEAD)) + { + title = Text(Text::A12B, Text::LEFT, Text::WHITE, "LIVE"); + count = Text(Text::A11M, Text::LEFT, Text::WHITE, "0 watching"); + url = Text(Text::A11M, Text::LEFT, Text::DARKGREY, "", WIDTH - QR - 28); + copy_label = Text(Text::A11B, Text::CENTER, Text::WHITE, "Copy link"); + stop_label = Text(Text::A11B, Text::CENTER, Text::WHITE, "Stop stream"); + fold_label = Text(Text::A12B, Text::CENTER, Text::WHITE, "-"); + + int16_t right = 8 + QR + 8; + int16_t bw = WIDTH - right - 8; + buttons[BT_FOLD] = std::make_unique(Point(WIDTH - 20, 3), Point(16, 14)); + buttons[BT_COPY] = std::make_unique(Point(right, HEAD + 8 + QR - 46), Point(bw, 20)); + buttons[BT_STOP] = std::make_unique(Point(right, HEAD + 8 + QR - 22), Point(bw, 20)); + + // (first time: the top left, under the minimap's usual place) + if (position.x() == 0 && position.y() == 0) + position = { 4, 200 }; + fold(false); + active = true; + } + + void UIStream::fold(bool on) + { + folded = on; + dimension = { WIDTH, static_cast(folded ? HEAD : HEAD + BODY) }; + buttons[BT_COPY]->set_active(!folded); + buttons[BT_STOP]->set_active(!folded); + fold_label.change_text(folded ? "+" : "-"); + } + + void UIStream::set_info(const std::string& l, int32_t watching) + { + if (l != link) + { + link = l; + std::string shown = link; + for (const char* scheme : { "https://", "http://" }) + if (shown.rfind(scheme, 0) == 0) + shown = shown.substr(std::string(scheme).size()); + url.change_text(shown); + } + count.change_text(std::to_string(watching) + (watching == 1 ? " watching" : " watching")); + } + + void UIStream::draw(float inter) const + { + int16_t x = position.x(), y = position.y(); + int16_t h = dimension.y(); + + // frame: a dark rim, the blue-grey title bar, the pale body + plate(x - 1, y - 1, WIDTH + 2, h + 2, 0.10f, 0.12f, 0.18f); + plate(x, y, WIDTH, HEAD, 0.30f, 0.38f, 0.55f); + plate(x, y, WIDTH, HEAD / 2, 0.42f, 0.50f, 0.68f); + + // the title: a blinking red dot, LIVE, how many are watching + bool dot = (std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count() / 600) % 2 == 0; + int16_t cx = x + 10, cy = y + HEAD / 2, rad = 4; + for (int16_t dy = -rad; dy <= rad; dy++) + { + int16_t half = static_cast(std::lround(std::sqrt(static_cast(rad * rad - dy * dy)))); + if (dot) + plate(cx - half, cy + dy, half * 2 + 1, 1, 1.0f, 0.20f, 0.28f); + else + plate(cx - half, cy + dy, half * 2 + 1, 1, 0.45f, 0.10f, 0.14f); + } + // (text draws a few pixels below where it's put: these sit in the middle of the bar, level with the dot) + title.draw(Point(x + 18, y - 2)); + count.draw(Point(x + 52, y - 1)); + + Rectangle foldr = buttons.at(BT_FOLD)->bounds(position); + button_plate(foldr, buttons.at(BT_FOLD)->get_state() == Button::MOUSEOVER, 0.36f, 0.44f, 0.62f); + // (a bar to fold it down; a plus to open it again) + int16_t mx = foldr.l() + foldr.width() / 2, my = foldr.t() + foldr.height() / 2; + plate(mx - 4, my - 1, 9, 2, 1.0f, 1.0f, 1.0f); + if (folded) + plate(mx - 1, my - 4, 2, 9, 1.0f, 1.0f, 1.0f); + + if (folded) + return; + + plate(x, y + HEAD, WIDTH, BODY, 0.98f, 0.95f, 0.88f); + + // the QR (white behind it, for any camera) + int16_t qx = x + 8, qy = y + HEAD + 8; + plate(qx - 1, qy - 1, QR + 2, QR + 2, 0.60f, 0.60f, 0.62f); + plate(qx, qy, QR, QR, 1.0f, 1.0f, 1.0f); + GraphicsGL::get().draw_tv(GraphicsGL::TV_QR, Rectangle(qx, qx + QR, qy, qy + QR), 1.0f); + + // the link, then Copy and Stop + url.draw(Point(x + 8 + QR + 8, qy)); + Rectangle copyr = buttons.at(BT_COPY)->bounds(position); + button_plate(copyr, buttons.at(BT_COPY)->get_state() == Button::MOUSEOVER, 0.55f, 0.32f, 0.85f); + copy_label.draw(Point(static_cast(copyr.l() + copyr.width() / 2), static_cast(copyr.t() + 3))); + Rectangle stopr = buttons.at(BT_STOP)->bounds(position); + button_plate(stopr, buttons.at(BT_STOP)->get_state() == Button::MOUSEOVER, 0.86f, 0.22f, 0.26f); + stop_label.draw(Point(static_cast(stopr.l() + stopr.width() / 2), static_cast(stopr.t() + 3))); + } + + bool UIStream::is_in_range(Point cursorpos) const + { + return Rectangle(position, position + dimension).contains(cursorpos); + } + + UIElement::Type UIStream::get_type() const + { + return TYPE; + } + + Button::State UIStream::button_pressed(uint16_t buttonid) + { + switch (buttonid) + { + case BT_FOLD: + fold(!folded); + break; + case BT_COPY: +#ifdef MS_PLATFORM_WASM + EM_ASM({ if (Module.onStreamCopy) Module.onStreamCopy(); }); +#endif + break; + case BT_STOP: + UI::get().emplace("Stop your live stream?", [](bool yes) { +#ifdef MS_PLATFORM_WASM + if (yes) + EM_ASM({ if (Module.onStreamStop) Module.onStreamStop(); }); +#endif + }); + break; + default: + break; + } + return Button::NORMAL; + } +} diff --git a/src/client/IO/UITypes/UIStream.h b/src/client/IO/UITypes/UIStream.h new file mode 100644 index 0000000..f84c2e7 --- /dev/null +++ b/src/client/IO/UITypes/UIStream.h @@ -0,0 +1,58 @@ +////////////////////////////////////////////////////////////////////////////// +// This file is part of the Journey MMORPG client (Dordo Story's changes) // +// // +// This program is free software: you can redistribute it and/or modify // +// it under the terms of the GNU Affero General Public License as // +// published by the Free Software Foundation, either version 3 of the // +// License, or (at your option) any later version. // +////////////////////////////////////////////////////////////////////////////// +#pragma once +#include "../UIDragElement.h" +#include "../../Graphics/Text.h" + +#include + +namespace jrc +{ + // Dordo Story's live stream window, up while we're streaming (the page streams; STREAM NOW starts it): a QR code + // for the link (painted by the page into its corner of the atlas), the link, Copy and Stop, and how many are + // watching. Dragged by its title bar like any window (and remembered), and folded down to just that bar. + class UIStream : public UIDragElement + { + public: + static constexpr Type TYPE = STREAM; + static constexpr bool FOCUSED = false; + static constexpr bool TOGGLED = false; + + UIStream(); + + void draw(float inter) const override; + bool is_in_range(Point cursorpos) const override; + UIElement::Type get_type() const override; + + // the link to watch at and how many are watching + void set_info(const std::string& link, int32_t watching); + + protected: + Button::State button_pressed(uint16_t buttonid) override; + + private: + enum Buttons : uint16_t { BT_FOLD, BT_COPY, BT_STOP }; + + static constexpr int16_t WIDTH = 208; + static constexpr int16_t HEAD = 20; + static constexpr int16_t QR = 104; + static constexpr int16_t BODY = QR + 16; + + void fold(bool on); + + bool folded = false; + std::string link; + Text title; + Text count; + Text url; + Text copy_label; + Text stop_label; + Text fold_label; + }; +} diff --git a/src/client/IO/UITypes/UIWorldMap.cpp b/src/client/IO/UITypes/UIWorldMap.cpp index 68bfa56..e0b1a07 100644 --- a/src/client/IO/UITypes/UIWorldMap.cpp +++ b/src/client/IO/UITypes/UIWorldMap.cpp @@ -62,6 +62,9 @@ namespace jrc buttons[BT_SEARCH] = std::make_unique(world_map["BtSearch"]); buttons[BT_AUTOFLY] = std::make_unique(world_map["BtAutoFly_1"]); buttons[BT_NAVIREG] = std::make_unique(world_map["BtNaviRegister"]); + // (auto-fly and the navigator aren't built yet: greyed out) + buttons[BT_AUTOFLY]->set_state(Button::DISABLED); + buttons[BT_NAVIREG]->set_state(Button::DISABLED); buttons[BT_SEARCH_CLOSE] = std::make_unique(close, close_pos + Point(bg_search_dimensions.x(), 0)); buttons[BT_ALLSEARCH] = std::make_unique(world_map_search["BtAllsearch"], background_dimensions); @@ -249,6 +252,15 @@ namespace jrc Button::State UIWorldMap::button_pressed(uint16_t buttonid) { + switch (buttonid) + { + case BT_AUTOFLY: + case BT_NAVIREG: + return Button::DISABLED; + default: + break; + } + if (buttonid >= BT_LINK0) { auto iter = link_maps.find(buttonid); diff --git a/src/client/IO/UITypes/UIWorldSelect.cpp b/src/client/IO/UITypes/UIWorldSelect.cpp index 92bbba9..4766bc3 100644 --- a/src/client/IO/UITypes/UIWorldSelect.cpp +++ b/src/client/IO/UITypes/UIWorldSelect.cpp @@ -16,6 +16,7 @@ // along with this program. If not, see . // ////////////////////////////////////////////////////////////////////////////// #include "UIWorldSelect.h" +#include "../../Graphics/GraphicsGL.h" #include "../../Configuration.h" #include "../../Graphics/Sprite.h" @@ -52,6 +53,7 @@ namespace jrc return; const World& world = worlds.front(); + has_world = true; buttons[BT_WORLD0] = std::make_unique(worldsrc["button:15"], Point(650, 20)); buttons[BT_WORLD0]->set_state(Button::PRESSED); @@ -77,6 +79,25 @@ namespace jrc void UIWorldSelect::draw(float alpha) const { UIElement::draw(alpha); + + if (!has_world) + return; + + // Chimken over the world's button (96 x 26 at 660, 434) and the channel panel's banner (114 x 40 at 221, 194): + // a plate in the button's colours, the chicken and the name + auto plate = [](int16_t x, int16_t y, int16_t w, int16_t h) { + GraphicsGL::get().drawrectangle(x, y, w, h, 0.47f, 0.29f, 0.12f, 1.0f); + GraphicsGL::get().drawrectangle(x + 1, y + 1, w - 2, h - 2, 1.0f, 0.86f, 0.52f, 1.0f); + GraphicsGL::get().drawrectangle(x + 2, y + h / 2, w - 4, h / 2 - 2, 0.98f, 0.74f, 0.33f, 1.0f); + }; + plate(660, 434, 96, 26); + GraphicsGL::get().draw_tv(GraphicsGL::TV_WORLD, Rectangle(663, 685, 436, 458), 1.0f); + button_name.draw(Point(689, 438)); + + plate(221, 194, 114, 40); + GraphicsGL::get().draw_tv(GraphicsGL::TV_WORLD, Rectangle(223, 255, 198, 230), 1.0f); + banner_shadow.draw(Point(259, 203)); + banner_name.draw(Point(258, 202)); } uint8_t UIWorldSelect::get_world_id() const diff --git a/src/client/IO/UITypes/UIWorldSelect.h b/src/client/IO/UITypes/UIWorldSelect.h index ba2d13e..b81404d 100644 --- a/src/client/IO/UITypes/UIWorldSelect.h +++ b/src/client/IO/UITypes/UIWorldSelect.h @@ -16,6 +16,7 @@ // along with this program. If not, see . // ////////////////////////////////////////////////////////////////////////////// #pragma once +#include "../../Graphics/Text.h" #include "../UIElement.h" #include "../../Net/Login.h" @@ -48,6 +49,11 @@ namespace jrc }; uint8_t worldid; + // (Dordo Story's world, Chimken, drawn over world 15's button and banner) + bool has_world = false; + Text button_name = Text(Text::A12B, Text::LEFT, Text::BROWN, "Chimken"); + Text banner_name = Text(Text::A18M, Text::LEFT, Text::YELLOW, "Chimken"); + Text banner_shadow = Text(Text::A18M, Text::LEFT, Text::BROWN, "Chimken"); uint8_t channelid; }; } diff --git a/src/client/IO/Window.cpp b/src/client/IO/Window.cpp index 091d63f..473bab6 100644 --- a/src/client/IO/Window.cpp +++ b/src/client/IO/Window.cpp @@ -30,6 +30,10 @@ #include +#include +#include +#include + namespace jrc { namespace @@ -73,6 +77,9 @@ namespace jrc glwnd = nullptr; opacity = 1.0f; opcstep = 0.0f; + fadestep = 0.0f; + holding = false; + hold_ticks = 0; f11_down = false; } @@ -87,9 +94,36 @@ namespace jrc .print("glfw error: " + std::string(description) + " (" + std::to_string(no) + ")"); } + // Input waits for the game's own step. The browser hands keys, clicks and moves over the moment they happen, + // outside the main loop, and handling one can need a piece of a game file that isn't downloaded yet (a potion's + // use sound from Sound.nx, say): waiting for it there crashed the game. So each callback only notes what + // happened, and Window::check_events, at the start of the next step, does it. + std::vector>& pending_input() + { + static std::vector> pending; + return pending; + } + void key_callback(GLFWwindow*, int key, int, int action, int) { - UI::get().send_key(key, action != GLFW_RELEASE); + bool pressed = action != GLFW_RELEASE; + pending_input().push_back([key, pressed]() { UI::get().send_key(key, pressed); }); + } + + // A cursor position from GLFW, in the game's 800 x 600. GLFW reports it in its own window's size, and while + // anything on the page is fullscreen it takes that size to be the whole screen (a phone: ~390 wide), which + // left the game cursor stuck short of the right side. + Point to_game(GLFWwindow* window, double xpos, double ypos) + { + int width = 0; + int height = 0; + glfwGetWindowSize(window, &width, &height); + if (width > 0 && height > 0) + { + xpos = xpos * Constants::VIEWWIDTH / width; + ypos = ypos * Constants::VIEWHEIGHT / height; + } + return { static_cast(xpos), static_cast(ypos) }; } void mousekey_callback(GLFWwindow* window, int button, int action, int) @@ -104,21 +138,21 @@ namespace jrc double xpos = 0.0; double ypos = 0.0; glfwGetCursorPos(window, &xpos, &ypos); - Point position( - static_cast(xpos), - static_cast(ypos) - ); - - UI::get().send_cursor(true); - if (is_doubleclick(position)) - { - UI::get().cancel_drag(); - UI::get().doubleclick(); - } + Point position = to_game(window, xpos, ypos); + bool twice = is_doubleclick(position); + + pending_input().push_back([twice]() { + UI::get().send_cursor(true); + if (twice) + { + UI::get().cancel_drag(); + UI::get().doubleclick(); + } + }); break; } case GLFW_RELEASE: - UI::get().send_cursor(false); + pending_input().push_back([]() { UI::get().send_cursor(false); }); break; default: break; @@ -128,7 +162,7 @@ namespace jrc switch (action) { case GLFW_PRESS: - UI::get().rightclick(); + pending_input().push_back([]() { UI::get().rightclick(); }); break; default: break; @@ -139,27 +173,25 @@ namespace jrc } } - void cursor_callback(GLFWwindow*, double xpos, double ypos) + void cursor_callback(GLFWwindow* window, double xpos, double ypos) { - auto x = static_cast(xpos); - auto y = static_cast(ypos); - Point pos = Point(x, y); - UI::get().send_cursor(pos); + Point pos = to_game(window, xpos, ypos); + pending_input().push_back([pos]() { UI::get().send_cursor(pos); }); } void scroll_callback(GLFWwindow*, double, double yoffset) { - UI::get().send_scroll(yoffset); + pending_input().push_back([yoffset]() { UI::get().send_scroll(yoffset); }); } void focus_callback(GLFWwindow*, int focused) { - UI::get().send_focus(focused); + pending_input().push_back([focused]() { UI::get().send_focus(focused); }); } void close_callback(GLFWwindow* window) { - UI::get().send_close(); + pending_input().push_back([]() { UI::get().send_close(); }); glfwSetWindowShouldClose(window, GL_FALSE); } @@ -336,6 +368,25 @@ namespace jrc void Window::updateopc() { + if (holding) + { + int64_t now = std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count(); + if (fadeready() || ++hold_ticks >= HOLD_MAX_TICKS || now - hold_since >= HOLD_MAX_MS) + { + holding = false; + fadeready = nullptr; + opcstep = fadestep; + if (fadein) + { + auto proc = std::move(fadein); + fadein = nullptr; + proc(); + } + } + return; + } + if (opcstep != 0.0f) { opacity += opcstep; @@ -351,6 +402,22 @@ namespace jrc opcstep = -opcstep; fadeprocedure(); + + if (fadeready) + { + // stay black until what comes next is ready + holding = true; + hold_ticks = 0; + hold_since = std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count(); + opcstep = 0.0f; + } + else if (fadein) + { + auto proc = std::move(fadein); + fadein = nullptr; + proc(); + } } } } @@ -393,6 +460,14 @@ namespace jrc f11_down = (f11state == GLFW_PRESS); #endif glfwPollEvents(); + + // (what came in since the last step, in order; anything it sets off can wait for game files safely here) + std::vector> input; + input.swap(pending_input()); + for (auto& happened : input) + { + happened(); + } } void Window::begin() const @@ -406,10 +481,14 @@ namespace jrc glfwSwapBuffers(glwnd); } - void Window::fadeout(float step, std::function fadeproc) + void Window::fadeout(float step, std::function fadeproc, std::function ready, std::function fadeinproc) { opcstep = -step; + fadestep = step; fadeprocedure = std::move(fadeproc); + fadeready = std::move(ready); + fadein = std::move(fadeinproc); + holding = false; } void Window::setclipboard(const std::string& text) const diff --git a/src/client/IO/Window.h b/src/client/IO/Window.h index b39b935..3b47e44 100644 --- a/src/client/IO/Window.h +++ b/src/client/IO/Window.h @@ -40,7 +40,11 @@ namespace jrc void update(); void begin() const; void end() const; - void fadeout(float step, std::function fadeprocedure); + // Fades to black, runs fadeprocedure there, and fades back in. With ready given, it stays black (without + // blocking: the game keeps running) until ready() says yes, or HOLD_MAX_TICKS have gone by; fadein runs + // as the picture starts coming back. + void fadeout(float step, std::function fadeprocedure, + std::function ready = {}, std::function fadein = {}); void check_events(); void setclipboard(const std::string& text) const; @@ -55,6 +59,15 @@ namespace jrc bool f11_down; float opacity; float opcstep; + float fadestep; std::function fadeprocedure; + std::function fadeready; + std::function fadein; + bool holding; + uint32_t hold_ticks; + int64_t hold_since = 0; + // (20 seconds of 8 ms updates: a file that never arrives can't leave anyone in the dark) + static constexpr uint32_t HOLD_MAX_TICKS = 2500; + static constexpr int64_t HOLD_MAX_MS = 20000; // (real time: also ends it when the game is crawling) }; } diff --git a/src/client/Journey.cpp b/src/client/Journey.cpp index f994773..05874bd 100644 --- a/src/client/Journey.cpp +++ b/src/client/Journey.cpp @@ -15,6 +15,9 @@ // You should have received a copy of the GNU Affero General Public License // // along with this program. If not, see . // ////////////////////////////////////////////////////////////////////////////// +#ifdef MS_PLATFORM_WASM +#include +#endif #include "Configuration.h" #ifdef MS_PLATFORM_WASM #include @@ -138,18 +141,33 @@ namespace jrc { if (!running()) { + // tell the hosting page why the game stopped (the line to the server dropped, or the player quit), + // so it can say so and offer to come back, instead of leaving a frozen picture + int connected = Session::get().is_connected() ? 1 : 0; + EM_ASM({ if (Module.onGameStopped) Module.onGameStopped($0 === 0); }, connected); emscripten_cancel_main_loop(); Sound::close(); return; } + // (between frames, nothing holds a pointer into a file chunk: the one safe moment to let chunks go) + LazyFS::trim_caches(); + int64_t elapsed = Timer::get().stop(); - for (accumulator += elapsed; accumulator >= timestep; accumulator -= timestep) + // (catching up at most ~64 ms of game time a frame: after a long stall, a map load say, the game skips + // the rest instead of running hundreds of steps at once and falling further behind each frame) + accumulator += elapsed; + if (accumulator > timestep * 8) + accumulator = timestep * 8; + for (; accumulator >= timestep; accumulator -= timestep) update(); float alpha = static_cast(accumulator) / timestep; draw(alpha); + // (the frame is on the canvas right now, and only until the browser shows it: the page's live stream copies + // it here. Copied on its own timer, it caught the canvas already cleared now and then, and streamed black) + EM_ASM({ if (Module.onFrameDrawn) Module.onFrameDrawn(); }); bool show_fps = true; // Hardcoded or from config if (show_fps) diff --git a/src/client/LazyFS/LazyFileLoader.cpp b/src/client/LazyFS/LazyFileLoader.cpp index 4679229..7aafbf2 100644 --- a/src/client/LazyFS/LazyFileLoader.cpp +++ b/src/client/LazyFS/LazyFileLoader.cpp @@ -1,17 +1,152 @@ #include +#include +#include +#include #include #include #include namespace LazyFS { + namespace + { + bool probing = false; + + // every open file's loader, for trim_caches + std::vector& all_loaders() + { + static std::vector loaders; + return loaders; + } + bool probe_missed = false; + + // (one clock for every file, so the shared budget can tell which chunk anywhere was used longest ago) + uint64_t access_clock = 0; + + // What a dry run reads in place of a chunk that isn't here yet (never kept in a cache) + LazyFileLoader::Chunk& zero_chunk() + { + static LazyFileLoader::Chunk chunk{ static_cast(-1), std::vector(LazyFileBackend::CHUNK_SIZE), 0 }; + return chunk; + } + } + + bool probe(const std::function& touch) + { + bool outer = probing; + bool missed_before = probe_missed; + probing = true; + probe_missed = false; + bool ready = false; + try + { + touch(); + ready = !probe_missed; + } + catch (...) + { + // (zeros read in a dry run can trip parsing: that just means "not yet") + } + probing = outer; + probe_missed = outer && (missed_before || !ready); + return ready; + } + + void warm_file(const std::string& path) + { + EM_ASM({ Module.LazyFS.warmFile(UTF8ToString($0)); }, path.c_str()); + } + + bool LazyFileLoader::take_from_page(size_t chunk_index, std::vector& out) + { + int got = EM_ASM_INT({ + var chunk = Module.LazyFS.peekChunk(UTF8ToString($0), $1); + if (!chunk || chunk.length !== $3) return 0; + HEAPU8.set(chunk, $2); + return 1; + }, path_.c_str(), static_cast(chunk_index), out.data(), static_cast(out.size())); + return got == 1; + } + + void LazyFileLoader::touch_range(size_t offset, size_t size) + { + if (!backend_ || !backend_->is_open() || size == 0) + return; + for (size_t index = offset / CHUNK_SIZE; index <= (offset + size - 1) / CHUNK_SIZE; ++index) + { + get_or_load_chunk(index); + } + } LazyFileLoader::LazyFileLoader(const std::string& path) : path_(path) { - cache_.reserve(CACHE_SIZE); + cache_.reserve(HARD_CACHE_SIZE); + all_loaders().push_back(this); + } + + LazyFileLoader::~LazyFileLoader() + { + auto& loaders = all_loaders(); + loaders.erase(std::remove(loaders.begin(), loaders.end(), this), loaders.end()); } - LazyFileLoader::~LazyFileLoader() = default; + // drop cache_[at] (the last one moves into its place) + void LazyFileLoader::forget(size_t at) + { + if (cache_[at].get() == last_) + last_ = nullptr; + where_[cache_[at]->index] = 0; + if (at + 1 != cache_.size()) + { + cache_[at] = std::move(cache_.back()); + where_[cache_[at]->index] = static_cast(at + 1); + } + cache_.pop_back(); + } + + void LazyFileLoader::trim() + { + while (cache_.size() > CACHE_SIZE) + { + size_t lru = 0; + for (size_t i = 1; i < cache_.size(); ++i) + { + if (cache_[i]->last_access < cache_[lru]->last_access) + lru = i; + } + forget(lru); + } + } + + void trim_caches() + { + size_t total = 0; + for (LazyFileLoader* loader : all_loaders()) + { + total += loader->cache_.size(); + } + // (the chunks used longest ago, whichever file they're in, until all of them fit the shared budget) + while (total > LazyFileLoader::SHARED_CACHE_SIZE) + { + LazyFileLoader* from = nullptr; + size_t at = 0; + for (LazyFileLoader* loader : all_loaders()) + { + for (size_t i = 0; i < loader->cache_.size(); ++i) + { + if (!from || loader->cache_[i]->last_access < from->cache_[at]->last_access) + { + from = loader; + at = i; + } + } + } + if (!from) + break; + from->forget(at); + total--; + } + } bool LazyFileLoader::open() { @@ -110,22 +245,26 @@ namespace LazyFS LazyFileLoader::Chunk* LazyFileLoader::get_or_load_chunk(size_t chunk_index) { - access_counter_++; + access_clock++; - // Check cache - for (auto& chunk : cache_) + // (the same chunk as last time, most often: nodes next to each other) + if (last_ && last_->index == chunk_index) { - if (chunk->index == chunk_index) - { - chunk->last_access = access_counter_; - return chunk.get(); - } + last_->last_access = access_clock; + return last_; + } + if (chunk_index < where_.size() && where_[chunk_index]) + { + Chunk* chunk = cache_[where_[chunk_index] - 1].get(); + chunk->last_access = access_clock; + last_ = chunk; + return chunk; } // Not in cache, load it auto new_chunk = std::make_unique(); new_chunk->index = chunk_index; - new_chunk->last_access = access_counter_; + new_chunk->last_access = access_clock; // Determine size to read size_t file_sum_size = backend_->size(); @@ -135,6 +274,19 @@ namespace LazyFS new_chunk->data.resize(bytes_to_read); + if (take_from_page(chunk_index, new_chunk->data)) + { + return remember(std::move(new_chunk)); + } + + if (probing) + { + // A dry run never waits: ask for the chunk in the background and read zeros for now + EM_ASM({ Module.LazyFS.warmChunk(UTF8ToString($0), $1); }, path_.c_str(), static_cast(chunk_index)); + probe_missed = true; + return &zero_chunk(); + } + if (!backend_->seek(start_pos)) { std::cerr << "[LazyFS] Seek failed for chunk " << chunk_index << std::endl; @@ -150,23 +302,29 @@ namespace LazyFS // std::cout << "[LazyFS] Loaded chunk " << chunk_index << " (" << read << " bytes)" << std::endl; - // Add to cache (evict if needed) - if (cache_.size() >= CACHE_SIZE) + return remember(std::move(new_chunk)); + } + + LazyFileLoader::Chunk* LazyFileLoader::remember(std::unique_ptr new_chunk) + { + // Add to cache (only past the hard ceiling does one go now: see trim) + if (cache_.size() >= HARD_CACHE_SIZE) { - // Find LRU - auto lru_it = cache_.begin(); - for (auto it = cache_.begin(); it != cache_.end(); ++it) + size_t lru = 0; + for (size_t i = 1; i < cache_.size(); ++i) { - if ((*it)->last_access < (*lru_it)->last_access) - { - lru_it = it; - } + if (cache_[i]->last_access < cache_[lru]->last_access) + lru = i; } - cache_.erase(lru_it); + forget(lru); } + if (new_chunk->index >= where_.size()) + where_.resize(new_chunk->index + 1, 0); cache_.push_back(std::move(new_chunk)); - return cache_.back().get(); + where_[cache_.back()->index] = static_cast(cache_.size()); + last_ = cache_.back().get(); + return last_; } } // namespace LazyFS diff --git a/src/client/LazyFS/LazyFileLoader.h b/src/client/LazyFS/LazyFileLoader.h index 4299b3a..eba7e0f 100644 --- a/src/client/LazyFS/LazyFileLoader.h +++ b/src/client/LazyFS/LazyFileLoader.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include @@ -16,6 +17,13 @@ namespace LazyFS class LazyFileLoader { public: + struct Chunk + { + size_t index; + std::vector data; + uint64_t last_access; + }; + LazyFileLoader(const std::string& path); ~LazyFileLoader(); @@ -52,6 +60,11 @@ namespace LazyFS */ const void* get_contiguous_data(size_t offset, size_t size); + /** + * Make sure every chunk in [offset, offset + size) is loaded, without copying anything out. + */ + void touch_range(size_t offset, size_t size); + /** * Static helper to load file (creates a Loader instance) * @param path Path to file @@ -66,26 +79,59 @@ namespace LazyFS static void free_file(void* handle); private: - // Maximum chunks to keep in memory (160 * 64KB = ~10MB per file) - static constexpr size_t CACHE_SIZE = 160; + // Chunks kept here per file (2 MB each). The page's own cache holds many more and hands them over without + // waiting, so this only needs to cover what is being drawn right now; 17 files x 160 used to be able to + // outgrow the 4 GB WebAssembly memory over a long session. Trimmed back to CACHE_SIZE only between frames + // (trim_caches), so a pointer taken into a chunk can't go stale in the middle of one; HARD_CACHE_SIZE is + // the ceiling within a frame (a whole map loading at once), where the oldest go as before. + static constexpr size_t CACHE_SIZE = 32; + static constexpr size_t HARD_CACHE_SIZE = 160; + // (Dordo Story: between frames the files share one budget instead, kept by whichever chunks were used + // last, so a big map's art or a crowd of monsters can keep more than 32 of one file without copying the + // same 2 MB back in from the page every frame; the total stays below what 17 x 32 could reach) + static constexpr size_t SHARED_CACHE_SIZE = 160; + + public: + void trim(); + + private: static constexpr size_t CHUNK_SIZE = LazyFileBackend::CHUNK_SIZE; - struct Chunk - { - size_t index; - std::vector data; - uint64_t last_access; - }; std::string path_; std::unique_ptr backend_; std::vector> cache_; - uint64_t access_counter_ = 0; + // chunk index -> its place in cache_ + 1 (0: not here), so finding one doesn't walk the whole cache + std::vector where_; + Chunk* last_ = nullptr; + void forget(size_t at); + friend void trim_caches(); std::vector stitch_buffer_; // const void* get_chunk_data(size_t offset, size_t size); // Replaced by get_contiguous_data implementation Chunk* get_or_load_chunk(size_t chunk_index); + Chunk* remember(std::unique_ptr chunk); + // Copy a chunk the page already holds in memory, without suspending; false when it doesn't have it + bool take_from_page(size_t chunk_index, std::vector& out); }; + /** + * Runs touch() as a dry run: any read that would have to wait for a chunk gets zeros instead, and that chunk is + * fetched in the background. Returns true when touch() never had to wait, so everything it reads is now in + * memory (and reading it for real won't stall the game). Call it again later until it says yes. + * Whatever touch() reads during the dry run may be zeros: it must not keep any of it. + */ + bool probe(const std::function& touch); + + /** + * Between frames: every file's chunk cache back down to its usual size. + */ + void trim_caches(); + + /** + * Fetch a whole file into the page's cache in the background (small, often-used files). + */ + void warm_file(const std::string& path); + } // namespace LazyFS diff --git a/src/client/LazyFS/lazyfs.js b/src/client/LazyFS/lazyfs.js index 604dea8..f962bc1 100644 --- a/src/client/LazyFS/lazyfs.js +++ b/src/client/LazyFS/lazyfs.js @@ -37,8 +37,14 @@ var LazyFS = { pendingRequests: new Map(), requestIdCounter: 0, - // In-memory chunk cache: Map<"file:size:chunk", Uint8Array> + // In-memory chunk cache: Map<"file:size:chunk", Uint8Array>, oldest first (see cachePut) chunkCache: new Map(), + chunkCacheBytes: 0, + // Past this the least recently used chunks are dropped (they stay in IndexedDB) + CHUNK_CACHE_MAX_BYTES: 768 * 1024 * 1024, + // Chunks being fetched in the background (warmChunk), and the ones waiting for the next batch + warming: new Set(), + warmQueue: [], // File registry: Map files: new Map(), @@ -359,7 +365,7 @@ var LazyFS = { const fileEntry = this.files.get(filename); const versionTag = this.getFileVersionTag(fileEntry); const cacheKey = this.getChunkCacheKey(filename, versionTag, chunkIndex); - this.chunkCache.set(cacheKey, chunkData); + this.cachePut(cacheKey, chunkData); // Store in cache (persistent) if (versionTag !== 'unknown') { @@ -378,6 +384,92 @@ var LazyFS = { } }, + // ========== MEMORY CACHE ========== + + cachePut: function (key, data) { + const old = this.chunkCache.get(key); + if (old) { + this.chunkCacheBytes -= old.length; + this.chunkCache.delete(key); + } + this.chunkCache.set(key, data); + this.chunkCacheBytes += data.length; + for (const [k, v] of this.chunkCache) { + if (this.chunkCacheBytes <= this.CHUNK_CACHE_MAX_BYTES) break; + this.chunkCache.delete(k); + this.chunkCacheBytes -= v.length; + } + }, + + // A chunk in memory right now, or null; never waits (the C++ side calls this before suspending for a read) + peekChunk: function (filepath, chunkIndex) { + const fileEntry = this.files.get(filepath); + if (!fileEntry) return null; + const key = this.getChunkCacheKey(filepath, this.getFileVersionTag(fileEntry), chunkIndex); + const data = this.chunkCache.get(key); + if (!data) return null; + // (most recently used goes to the back) + this.chunkCache.delete(key); + this.chunkCache.set(key, data); + return data; + }, + + // Bring a chunk into memory in the background: IndexedDB if it's there, the server if not. Asks made in the + // same moment go out together, neighbouring chunks as one request. + warmChunk: function (filepath, chunkIndex) { + const fileEntry = this.files.get(filepath); + if (!fileEntry || fileEntry.size === null || fileEntry.size < 0) return; + const key = this.getChunkCacheKey(filepath, this.getFileVersionTag(fileEntry), chunkIndex); + if (this.chunkCache.has(key) || this.warming.has(key)) return; + this.warming.add(key); + this.warmQueue.push({ filepath, chunkIndex, key }); + if (this.warmQueue.length === 1) queueMicrotask(() => this.flushWarm()); + }, + + flushWarm: async function () { + const asks = this.warmQueue.splice(0); + if (!asks.length) return; + if (this.dbInitPromise) await this.dbInitPromise; + const missing = []; + await Promise.all(asks.map(async (a) => { + const fileEntry = this.files.get(a.filepath); + const cached = await this.getCachedChunk(a.filepath, this.getFileVersionTag(fileEntry), a.chunkIndex); + if (cached) { this.cachePut(a.key, cached); this.warming.delete(a.key); } + else missing.push(a); + })); + // (runs of neighbouring chunks of one file: one request each) + missing.sort((x, y) => (x.filepath < y.filepath ? -1 : x.filepath > y.filepath ? 1 : x.chunkIndex - y.chunkIndex)); + const runs = []; + for (const a of missing) { + const run = runs[runs.length - 1]; + if (run && run.filepath === a.filepath && a.chunkIndex === run.end + 1 && run.end - run.start < 15) { run.end = a.chunkIndex; run.keys.push(a.key); } + else runs.push({ filepath: a.filepath, start: a.chunkIndex, end: a.chunkIndex, keys: [a.key] }); + } + await Promise.all(runs.map(async (r) => { + try { await this.fetchChunks(r.filepath, r.start, r.end); } + catch (e) { console.warn('[LazyFS] Background fetch failed:', r.filepath, r.start, r.end, e); } + for (const k of r.keys) this.warming.delete(k); + })); + }, + + // A whole (small, often-used) file into memory and IndexedDB, strictly one chunk at a time: the assets server + // answers in order, so a reply the game is actually waiting for is never stuck behind more than one of these + warmFile: async function (filepath) { + const fileEntry = this.files.get(filepath); + if (!fileEntry || !(fileEntry.size > 0) || !this.CHUNK_SIZE) return; + if (this.dbInitPromise) await this.dbInitPromise; + const count = Math.ceil(fileEntry.size / this.CHUNK_SIZE); + for (let i = 0; i < count; i++) { + const versionTag = this.getFileVersionTag(fileEntry); + const key = this.getChunkCacheKey(filepath, versionTag, i); + if (this.chunkCache.has(key) || this.warming.has(key)) continue; + const cached = await this.getCachedChunk(filepath, versionTag, i); + if (cached) { this.cachePut(key, cached); continue; } + try { await this.fetchChunks(filepath, i, i); } catch (e) { return; } + await new Promise((r) => setTimeout(r, 60)); + } + }, + // ========== FILE OPERATIONS ========== /** @@ -419,10 +511,22 @@ var LazyFS = { /** * Fetch a batch of chunks */ - fetchChunks: async function (filepath, startChunk, endChunk) { - await this.connect(); - + fetchChunks: function (filepath, startChunk, endChunk) { + // (the same range asked twice at once, by a read and a background warm: one request, both wait on it) const key = `batch:${filepath}:${startChunk}:${endChunk}`; + this.batchesInFlight = this.batchesInFlight || new Map(); + let flight = this.batchesInFlight.get(key); + if (!flight) { + flight = this.fetchChunksOnce(filepath, startChunk, endChunk, key); + this.batchesInFlight.set(key, flight); + const done = () => { if (this.batchesInFlight.get(key) === flight) this.batchesInFlight.delete(key); }; + flight.then(done, done); + } + return flight; + }, + + fetchChunksOnce: async function (filepath, startChunk, endChunk, key) { + await this.connect(); return new Promise((resolve, reject) => { this.pendingRequests.set(key, { resolve, reject }); @@ -545,7 +649,7 @@ var LazyFS = { const cachedData = await this.getCachedChunk(filepath, versionTag, chunkIdx); if (cachedData) { // Success! Load to memory - this.chunkCache.set(cacheKey, cachedData); + this.cachePut(cacheKey, cachedData); this.logFetch(filepath, chunkIdx, cachedData.length, true); // Log cache hit // End current missing range diff --git a/src/client/Net/Handlers/MapObjectHandlers.cpp b/src/client/Net/Handlers/MapObjectHandlers.cpp index 1b1fc3a..56de567 100644 --- a/src/client/Net/Handlers/MapObjectHandlers.cpp +++ b/src/client/Net/Handlers/MapObjectHandlers.cpp @@ -22,6 +22,9 @@ #include "Helpers/MovementParser.h" #include "../../Audio/Audio.h" +#include "nlnx/nx.hpp" + +#include #include "../../Gameplay/Stage.h" #include "../../Gameplay/Spawn.h" @@ -177,7 +180,7 @@ namespace jrc recv.read_int(); //count of 5110000 recv.read_int(); // 'itemeffect' - recv.read_int(); // 'chair' + int32_t chair = recv.read_int(); Point position = recv.read_point(); int8_t stance = recv.read_byte(); @@ -221,6 +224,29 @@ namespace jrc Stage::get().get_chars().spawn({ cid, look, level, job, name, stance, position }); + if (chair > 0) + { + if (Optional other = Stage::get().get_chars().get_char(cid)) + other->set_chair(chair); + } + } + + // Someone else sat on a chair from their Set-up tab (0: got up). + void ShowChairHandler::handle(InPacket& recv) const + { + int32_t cid = recv.read_int(); + int32_t itemid = recv.read_int(); + if (Optional other = Stage::get().get_chars().get_char(cid)) + other->set_chair(itemid); + } + + // The server agreeing we got up (or sat on a map seat): nothing more to do here. + void CancelChairHandler::handle(InPacket& recv) const + { + if (recv.length() > 0 && recv.read_byte() == 0 && Stage::get().get_player().get_chair()) + { + Stage::get().get_player().set_chair(0); + } } @@ -288,6 +314,36 @@ namespace jrc } + void DordoSpiritHandler::handle(InPacket& recv) const + { + int8_t mode = recv.read_byte(); + int32_t oid = recv.read_int(); + Stage& stage = Stage::get(); + if (mode == 3) + { + // (the held monster's HP, for this spirit's status bar) + int32_t hp = recv.read_int(); + int32_t maxhp = recv.read_int(); + stage.get_spirit().held_hp(oid, hp, maxhp); + return; + } + + int32_t cid = recv.read_int(); + bool died = recv.read_bool(); + + if (!died) + { + stage.get_mobs().shudder(oid); + } + if (stage.is_player(cid)) + { + if (mode == 1) + stage.get_spirit().possessed(oid, stage.get_mobs()); + else if (mode == 2) + stage.get_spirit().released(oid, stage.get_mobs()); + } + } + void ShowForeignEffectHandler::handle(InPacket& recv) const { int32_t cid = recv.read_int(); @@ -309,9 +365,15 @@ namespace jrc Stage::get().get_combat().show_buff(cid, skillid, effect); } - else + else if (effect == 0) // level up + { + Stage::get().show_character_effect(cid, CharEffect::LEVELUP); + Sound(Sound::LEVELUP).play(); + } + else if (effect == 8) // job advance { - // todo + Stage::get().show_character_effect(cid, CharEffect::JOBCHANGE); + Sound(nl::nx::sound["Game.img"]["JobChanged"]).play(); } } @@ -365,7 +427,7 @@ namespace jrc recv.read_byte(); recv.read_byte(); // useskill - recv.read_byte(); // skill + int8_t activity = recv.read_byte(); // (24-41: one of its attacks, 24 + 2 * (n - 1), + 1 facing left) recv.read_byte(); // skill 1 recv.read_byte(); // skill 2 recv.read_byte(); // skill 3 @@ -375,6 +437,10 @@ namespace jrc std::vector movements = MovementParser::parse_movements(recv); Stage::get().get_mobs().send_movement(oid, position, std::move(movements)); + if (activity >= 24 && activity <= 41) + { + Stage::get().get_mobs().play_attack(oid, static_cast((activity - 24) / 2 + 1)); + } } @@ -465,6 +531,16 @@ namespace jrc Stage::get().get_drops().spawn({ oid, itemid, meso, owner, dropfrom, dropto, pickuptype, mode, playerdrop }); + + // (a monster's whole drop arrives at once: one swish for the lot, like the original) + static int64_t last_swish = 0; + int64_t now = std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count(); + if ((mode == 0 || mode == 1) && now - last_swish > 60) + { + last_swish = now; + Sound(Sound::DROP).play(); + } } @@ -519,4 +595,25 @@ namespace jrc Stage::get().get_reactors() .remove(oid, state, point); } + + void HitReactorHandler::handle(InPacket& recv) const + { + int32_t oid = recv.read_int(); + int8_t state = recv.read_byte(); + // (then its position, the hitter's stance and a frame delay: the reactor knows where it is) + + Stage::get().get_reactors().trigger(oid, state); + } + + void FacialExpressionHandler::handle(InPacket& recv) const + { + int32_t cid = recv.read_int(); + int32_t emote = recv.read_int(); + + if (Optional other = Stage::get().get_chars().get_char(cid)) + { + // (emote 1 is action 100, like our own F-keys) + other->set_expression(emote + 99); + } + } } diff --git a/src/client/Net/Handlers/MapObjectHandlers.h b/src/client/Net/Handlers/MapObjectHandlers.h index 312367b..c02f68a 100644 --- a/src/client/Net/Handlers/MapObjectHandlers.h +++ b/src/client/Net/Handlers/MapObjectHandlers.h @@ -60,6 +60,14 @@ namespace jrc }; + // Dordo Story: a monster spirit took hold of a monster (everyone sees it shudder; the spirit's own client starts + // walking it), or let go of it (or it died under the spirit). + // Opcode: DORDO_SPIRIT(464) + class DordoSpiritHandler : public PacketHandler + { + void handle(InPacket& recv) const override; + }; + // Display an effect on a character. // Opcode: SHOW_FOREIGN_EFFECT(198) class ShowForeignEffectHandler : public PacketHandler @@ -142,12 +150,36 @@ namespace jrc // Parse a ReactorSpawn and send it to the Stage spawn queue. // Opcode: SPAWN_REACTOR(279) + class ShowChairHandler : public PacketHandler + { + void handle(InPacket& recv) const override; + }; + + class CancelChairHandler : public PacketHandler + { + void handle(InPacket& recv) const override; + }; + class SpawnReactorHandler : public PacketHandler { void handle(InPacket& recv) const override; }; + // Another character made a face (an emote key). + // Opcode: FACIAL_EXPRESSION(193) + class FacialExpressionHandler : public PacketHandler + { + void handle(InPacket& recv) const override; + }; + + // A reactor was hit and moved to a new state: show it. + // Opcode: REACTOR_HIT(277) + class HitReactorHandler : public PacketHandler + { + void handle(InPacket& recv) const override; + }; + // Remove a reactor from the stage. // Opcode: REMOVE_REACTOR(280) class RemoveReactorHandler : public PacketHandler diff --git a/src/client/Net/Handlers/MessagingHandlers.cpp b/src/client/Net/Handlers/MessagingHandlers.cpp index 6e9b6a9..d1b99c2 100644 --- a/src/client/Net/Handlers/MessagingHandlers.cpp +++ b/src/client/Net/Handlers/MessagingHandlers.cpp @@ -1,4 +1,5 @@ #include "MessagingHandlers.h" +#include "../../Audio/Audio.h" #include "../../Character/Char.h" #include "../../Console.h" @@ -482,6 +483,9 @@ namespace jrc { int64_t time = recv.length() >= 8 ? recv.read_long() : 0; quests.complete(qid, time); + // (the quest-cleared jingle, as the original) + static const Sound cleared(nl::nx::sound["Game.img"]["QuestClear"]); + cleared.play(); } else { @@ -520,7 +524,11 @@ namespace jrc std::string message = "You have gained experience (+" + std::to_string(gain) + ")"; if (inchat) { - + // EXP from an NPC or a quest: said in the chat box, with the original's EXP sound + if (auto statusbar = UI::get().get_element()) + statusbar->send_chatline(message, UIChatbar::YELLOW); + static const Sound exp(nl::nx::sound["Game.img"]["IncEXP"]); + exp.play(); } else { diff --git a/src/client/Net/Handlers/NpcInteractionHandlers.cpp b/src/client/Net/Handlers/NpcInteractionHandlers.cpp index 1c8deca..cfd3a84 100644 --- a/src/client/Net/Handlers/NpcInteractionHandlers.cpp +++ b/src/client/Net/Handlers/NpcInteractionHandlers.cpp @@ -324,4 +324,27 @@ namespace jrc UI::get().enable(); } + + void ConfirmShopTransactionHandler::handle(InPacket& recv) const + { + int8_t code = recv.available() ? recv.read_byte() : 0; + std::string message; + switch (code) + { + case 0: // bought + case 8: // sold / recharged + return; + case 2: + case 5: + message = "You do not have enough mesos."; + break; + case 3: + message = "Please check if your inventory is full or not."; + break; + default: + message = "You can't do that right now."; + break; + } + UI::get().emplace(message, []() {}); + } } diff --git a/src/client/Net/Handlers/NpcInteractionHandlers.h b/src/client/Net/Handlers/NpcInteractionHandlers.h index 554d770..4d9d647 100644 --- a/src/client/Net/Handlers/NpcInteractionHandlers.h +++ b/src/client/Net/Handlers/NpcInteractionHandlers.h @@ -32,6 +32,12 @@ namespace jrc void handle(InPacket& recv) const override; }; + // The shop's answer to buying or selling: 0 / 8 done, otherwise why not (said in a notice, as the original). + class ConfirmShopTransactionHandler : public PacketHandler + { + void handle(InPacket& recv) const override; + }; + // Handles storage (trunk) open/update packets. class StorageHandler : public PacketHandler { diff --git a/src/client/Net/Handlers/PlayerHandlers.cpp b/src/client/Net/Handlers/PlayerHandlers.cpp index 61590bd..dedd835 100644 --- a/src/client/Net/Handlers/PlayerHandlers.cpp +++ b/src/client/Net/Handlers/PlayerHandlers.cpp @@ -148,6 +148,8 @@ namespace jrc { player.die(); + // (two seconds to see the tombstone land and the ghost before the dialog comes up) + player.set_death_notice([&player]() { UI::get().emplace( "You have died. Press OK to move to the nearest town.", [&player]() { @@ -156,6 +158,7 @@ namespace jrc ChangeMapPacket(true, player.get_stats().get_mapid(), "", false).dispatch(); } ); + }); } } else if (player.is_dead()) diff --git a/src/client/Net/Handlers/SetfieldHandlers.cpp b/src/client/Net/Handlers/SetfieldHandlers.cpp index c3dcda9..a1a88c5 100644 --- a/src/client/Net/Handlers/SetfieldHandlers.cpp +++ b/src/client/Net/Handlers/SetfieldHandlers.cpp @@ -26,23 +26,79 @@ #include "../../Timer.h" #include "../../Audio/Audio.h" #include "../../Gameplay/Stage.h" +#include "../../Util/Misc.h" #include "../../Graphics/GraphicsGL.h" #include "../../IO/UI.h" #include "../../Gameplay/CashShop.h" #include "../../IO/Window.h" +#include "../../Util/AssetReady.h" +#include "nlnx/nx.hpp" +#include "nlnx/node.hpp" +#include "nlnx/bitmap.hpp" + + +#ifdef MS_PLATFORM_WASM +#include +#endif namespace jrc { + namespace + { + // The page's loading screen hops an Orange Mushroom: its walk, handed over once (after the first map is in, + // so it never slows that) frame by frame as BGRA pixels, with each frame's origin and delay. It stays in the + // page's memory only. + void hand_page_mushroom() + { +#ifdef MS_PLATFORM_WASM + static bool handed = false; + if (handed) + return; + handed = true; + + nl::node move = nl::nx::mob["1210102.img"]["move"]; + for (int i = 0; ; i++) + { + nl::node frame = move[std::to_string(i)]; + if (frame.data_type() != nl::node::type::bitmap) + break; + nl::bitmap bmp = frame.get_bitmap(); + const void* pixels = bmp.data(); + if (!pixels) + break; + nl::vector2i origin = frame["origin"].get_vector(); + int32_t delay = static_cast(frame["delay"].get_integer(100)); + EM_ASM({ if (Module.onLoadingFrame) Module.onLoadingFrame(HEAPU8.slice($0, $0 + $1 * $2 * 4), $1, $2, $3, $4, $5, $6); }, + pixels, bmp.width(), bmp.height(), origin.first, origin.second, delay, i); + } +#endif + } + } + void SetfieldHandler::transition(int32_t mapid, uint8_t portalid) const { float fadestep = 0.025f; + // Load the map at black, then stay black until its art and everything living on it is in memory, so it + // comes back in whole instead of stopping on each new thing. Drawing stays locked meanwhile (a locked + // draw reads nothing), and opens as the fade back in starts. Window::get().fadeout(fadestep, [mapid, portalid](){ +#ifdef MS_PLATFORM_WASM + // (black now: the page puts up its loading screen if this takes a moment) + EM_ASM({ if (Module.onMapLoading) Module.onMapLoading(); }); +#endif GraphicsGL::get().clear(); Stage::get().load(mapid, portalid); UI::get().enable(); Timer::get().start(); + }, [mapid](){ + return AssetReady::map(mapid); + }, [](){ GraphicsGL::get().unlock(); +#ifdef MS_PLATFORM_WASM + EM_ASM({ if (Module.onMapShown) Module.onMapShown(); }); +#endif + hand_page_mushroom(); }); GraphicsGL::get().lock(); @@ -100,6 +156,12 @@ namespace jrc PlayerUpdatePacket().dispatch(); + // (came in as a monster spirit: say so, every time a channel takes us in, since that's a fresh login there) + if (getDordoString("spirit") == "1") + { + Stage::get().get_spirit().begin(); + } + Sound(Sound::GAMESTART).play(); CashShop::get().closed(); diff --git a/src/client/Net/OutPacket.h b/src/client/Net/OutPacket.h index 85027cd..2096401 100644 --- a/src/client/Net/OutPacket.h +++ b/src/client/Net/OutPacket.h @@ -90,6 +90,7 @@ namespace jrc RANGED_ATTACK = 45, MAGIC_ATTACK = 46, TAKE_DAMAGE = 48, + FACE_EXPRESSION = 51, // Messaging GENERAL_CHAT = 49, @@ -107,9 +108,13 @@ namespace jrc // Inventory GATHER_ITEMS = 69, + MESO_DROP = 94, SORT_ITEMS = 70, MOVE_ITEM = 71, USE_ITEM = 72, + // (chairs: sit on one from the Set-up tab, and get up again) + CANCEL_CHAIR = 0x2A, + USE_CHAIR = 0x2B, SCROLL_EQUIP = 86, // Player @@ -125,9 +130,11 @@ namespace jrc DENY_PARTY_REQUEST = 125, MOVE_MONSTER = 188, PICKUP_ITEM = 202, + DAMAGE_REACTOR = 205, PLAYER_UPDATE = 0xCF, // Custom + DORDO_SPIRIT = 464, // (Dordo Story's monster spirits, matched in our Cosmic) HASH_CHECK = 30000 }; } diff --git a/src/client/Net/PacketSwitch.cpp b/src/client/Net/PacketSwitch.cpp index bbcec57..71aa502 100644 --- a/src/client/Net/PacketSwitch.cpp +++ b/src/client/Net/PacketSwitch.cpp @@ -124,8 +124,10 @@ namespace jrc SHOW_ITEM_EFFECT = 194, SHOW_CHAIR = 196, + CANCEL_CHAIR_RESULT = 205, UPDATE_CHARLOOK = 197, SHOW_FOREIGN_EFFECT = 198, + DORDO_SPIRIT = 464, // (Dordo Story: a monster possessed by a spirit, or let go of) UPDATE_PARTYMEMBER_HP = 201, SHOW_ITEM_GAIN_INCHAT = 206, // this is terribly named LOCK_UI = 221, @@ -147,12 +149,15 @@ namespace jrc MAKE_NPC_SCRIPTED = 263, DROP_LOOT = 268, REMOVE_LOOT = 269, + FACIAL_EXPRESSION = 193, + HIT_REACTOR = 277, SPAWN_REACTOR = 279, REMOVE_REACTOR = 280, // NPC Interaction NPC_DIALOGUE = 304, OPEN_NPC_SHOP = 305, + CONFIRM_SHOP_TRANSACTION = 306, STORAGE = 309, KEYMAP = 335, @@ -185,8 +190,11 @@ namespace jrc // MapObject handlers emplace(); emplace(); + emplace(); + emplace(); emplace(); emplace(); + emplace(); emplace(); emplace(); emplace(); @@ -198,6 +206,8 @@ namespace jrc emplace(); emplace(); emplace(); + emplace(); + emplace(); emplace(); emplace(); @@ -237,6 +247,7 @@ namespace jrc // Npc Interaction Handlers emplace(); emplace(); + emplace(); emplace(); // Quest Handlers diff --git a/src/client/Net/Packets/AttackAndSkillPackets.h b/src/client/Net/Packets/AttackAndSkillPackets.h index dcc2da3..b55d7ec 100644 --- a/src/client/Net/Packets/AttackAndSkillPackets.h +++ b/src/client/Net/Packets/AttackAndSkillPackets.h @@ -141,4 +141,19 @@ namespace jrc // a point (4 bytes) could be added at the end } }; + + // Hit a reactor (a box, a plant…) with an attack: the server works out what happens (a new state, drops). + // Opcode: DAMAGE_REACTOR(205) + class DamageReactorPacket : public OutPacket + { + public: + DamageReactorPacket(int32_t oid, int32_t charpos, int16_t stance, int32_t skillid) : OutPacket(DAMAGE_REACTOR) + { + write_int(oid); + write_int(charpos); + write_short(stance); + write_int(0); + write_int(skillid); + } + }; } diff --git a/src/client/Net/Packets/GameplayPackets.h b/src/client/Net/Packets/GameplayPackets.h index 286ba98..5ab58da 100644 --- a/src/client/Net/Packets/GameplayPackets.h +++ b/src/client/Net/Packets/GameplayPackets.h @@ -204,4 +204,33 @@ namespace jrc public: PlayerUpdatePacket() : OutPacket(PLAYER_UPDATE) {} }; + + // Make a face (the F-keys): everyone on the map sees it. Emotes 1-7 are the free ones (action 100 = 1). + // Opcode: FACE_EXPRESSION(51) + class FaceExpressionPacket : public OutPacket + { + public: + FaceExpressionPacket(int32_t emote) : OutPacket(FACE_EXPRESSION) + { + write_int(emote); + } + }; + + // Dordo Story: become a monster spirit, take hold of a monster, let go of it. + // Opcode: DORDO_SPIRIT(464) + class SpiritPacket : public OutPacket + { + public: + enum Mode : int8_t { BECOME = 1, POSSESS = 2, RELEASE = 3, WARP = 4, RANDOM = 6 }; + + // (POSSESS: the monster's object id; WARP: the town's map id) + SpiritPacket(Mode mode, int32_t value = 0) : OutPacket(DORDO_SPIRIT) + { + write_byte(mode); + if (mode == POSSESS || mode == WARP) + { + write_int(value); + } + } + }; } diff --git a/src/client/Net/Packets/InventoryPackets.h b/src/client/Net/Packets/InventoryPackets.h index 3655062..bb2d5e1 100644 --- a/src/client/Net/Packets/InventoryPackets.h +++ b/src/client/Net/Packets/InventoryPackets.h @@ -87,6 +87,26 @@ namespace jrc // A packet which requests that an 'USE' item is used. // Opcode: USE_ITEM(72) + // Sits on a chair from the Set-up tab (the server shows it to everyone else). + class UseChairPacket : public OutPacket + { + public: + UseChairPacket(int32_t itemid) : OutPacket(USE_CHAIR) + { + write_int(itemid); + } + }; + + // Gets up from a chair (-1), or sits on the map's seat with this index. + class CancelChairPacket : public OutPacket + { + public: + CancelChairPacket(int16_t seat) : OutPacket(CANCEL_CHAIR) + { + write_short(seat); + } + }; + class UseItemPacket : public OutPacket { public: @@ -122,4 +142,16 @@ namespace jrc ScrollEquipPacket(int16_t source, Equipslot::Id target) : ScrollEquipPacket(source, target, 0) {} }; + + // Drop mesos on the ground (10 to 50,000 at a time). + // Opcode: MESO_DROP(94) + class DropMesoPacket : public OutPacket + { + public: + DropMesoPacket(int32_t amount) : OutPacket(MESO_DROP) + { + write_time(); + write_int(amount); + } + }; } diff --git a/src/client/Net/Packets/SelectCharPackets.h b/src/client/Net/Packets/SelectCharPackets.h index 9fc2b08..9d3cb9a 100644 --- a/src/client/Net/Packets/SelectCharPackets.h +++ b/src/client/Net/Packets/SelectCharPackets.h @@ -78,4 +78,18 @@ namespace jrc write_int(cid); } }; + + // Dordo Story: in as a monster spirit, not one of the account's characters. The server makes the account's + // spirit character if it has none yet and takes it in, as if it had been picked. + // Opcode: DORDO_SPIRIT(464), mode 5 + class SpiritLoginPacket : public OutPacket + { + public: + SpiritLoginPacket() : OutPacket(DORDO_SPIRIT) + { + write_byte(5); + write_string(MACS); + write_string(HWID); + } + }; } diff --git a/src/client/Net/SockInternal.cpp b/src/client/Net/SockInternal.cpp index 9b417f2..99feb0e 100644 --- a/src/client/Net/SockInternal.cpp +++ b/src/client/Net/SockInternal.cpp @@ -116,23 +116,28 @@ namespace public: int connect(const std::string& address, const std::string& port) { - std::string ws_url = jrc::Setting::get().load() + "://"; - - std::string proxy_ip = jrc::Setting::get().load(); - std::string proxy_port = jrc::Setting::get().load(); - - if (!proxy_ip.empty()) { - ws_url += proxy_ip; - } else { - ws_url += jrc::getBrowserHostname(); // Dynamic hostname from browser - } - - ws_url += ":"; - - if (!proxy_port.empty()) { - ws_url += proxy_port; - } else { - ws_url += WEB_SOCK_PORT; // Proxy server port fallback + // A hosting page can give the whole proxy URL (a path behind its web server, with its own ticket). + std::string ws_url = jrc::getDordoString("gameUrl"); + + if (ws_url.empty()) { + ws_url = jrc::Setting::get().load() + "://"; + + std::string proxy_ip = jrc::Setting::get().load(); + std::string proxy_port = jrc::Setting::get().load(); + + if (!proxy_ip.empty()) { + ws_url += proxy_ip; + } else { + ws_url += jrc::getBrowserHostname(); // Dynamic hostname from browser + } + + ws_url += ":"; + + if (!proxy_port.empty()) { + ws_url += proxy_port; + } else { + ws_url += WEB_SOCK_PORT; // Proxy server port fallback + } } jrc::Console::get().print("Connecting to WebSocket proxy: " + ws_url); diff --git a/src/client/Util/AssetReady.cpp b/src/client/Util/AssetReady.cpp new file mode 100644 index 0000000..d9c0ee5 --- /dev/null +++ b/src/client/Util/AssetReady.cpp @@ -0,0 +1,332 @@ +#include "AssetReady.h" + +#include "Misc.h" + +#include "../Data/ItemData.h" + +#include "nlnx/node.hpp" +#include "nlnx/nx.hpp" + +#include +#include +#include +#include +#include +#include + +#ifdef MS_PLATFORM_WASM +#include +#include +#endif + +namespace jrc +{ + namespace AssetReady + { + namespace + { +#ifdef MS_PLATFORM_WASM + // How long a "not yet" answer stands before the same thing is checked again (a check walks its whole + // node tree, so not every frame) + constexpr double RECHECK_MS = 120.0; + + std::unordered_set ready; + std::unordered_map last_check; + + bool check(const std::string& key, const std::function& touch) + { + if (ready.count(key)) + { + return true; + } + + double now = emscripten_get_now(); + auto last = last_check.find(key); + if (last != last_check.end() && now - last->second < RECHECK_MS) + { + return false; + } + + last_check[key] = now; + if (!LazyFS::probe(touch)) + { + return false; + } + + ready.insert(key); + last_check.erase(key); + return true; + } +#else + bool check(const std::string&, const std::function&) + { + return true; + } +#endif + + // An id written as text (map life, links); -1 when it isn't one (a dry run can read zeros) + int32_t parse_id(const std::string& text) + { + char* end = nullptr; + long value = std::strtol(text.c_str(), &end, 10); + return (text.empty() || *end != '\0' || value <= 0) ? -1 : static_cast(value); + } + + // The same nodes Mob's constructor reads: its own, the one it links to for looks, its sounds, its name + void touch_mob(int32_t id) + { + std::string strid = string_format::extend_id(id, 7); + nl::node src = nl::nx::mob[strid + ".img"]; + src.touch(); + + nl::node link = src["info"]["link"]; + std::string linkid = link.get_string(); + if (linkid.empty() && link.get_integer(0) > 0) + { + linkid = std::to_string(link.get_integer(0)); + } + if (int32_t linked = parse_id(linkid); linked > 0) + { + nl::nx::mob[string_format::extend_id(linked, 7) + ".img"].touch(); + } + + nl::nx::sound["Mob.img"][strid].touch(); + nl::nx::string["Mob.img"][std::to_string(id)].touch(); + } + + void touch_npc(int32_t id) + { + nl::node src = nl::nx::npc[string_format::extend_id(id, 7) + ".img"]; + src.touch(); + + std::string link = src["info"]["link"]; + if (!link.empty()) + { + nl::nx::npc[link + ".img"].touch(); + } + + nl::nx::string["Npc.img"][std::to_string(id)].touch(); + } + + // The same nodes ItemData's constructor reads: the item's info (icons, price) and its name + void touch_item(int32_t id) + { + std::string strprefix = "0" + std::to_string(id / 10000); + std::string strid = "0" + std::to_string(id); + std::string name = std::to_string(id); + switch (id / 1000000) + { + case 1: + { + std::string category = ItemData::get_eqcategory(id); + nl::nx::character[category][strid + ".img"]["info"].touch(); + nl::nx::string["Eqp.img"]["Eqp"][category][name].touch(); + break; + } + case 2: + nl::nx::item["Consume"][strprefix + ".img"][strid]["info"].touch(); + nl::nx::string["Consume.img"][name].touch(); + break; + case 3: + nl::nx::item["Install"][strprefix + ".img"][strid]["info"].touch(); + nl::nx::string["Ins.img"][name].touch(); + break; + case 4: + nl::nx::item["Etc"][strprefix + ".img"][strid]["info"].touch(); + nl::nx::string["Etc.img"]["Etc"][name].touch(); + break; + case 5: + if (id / 10000 == 500) + { + nl::nx::item["Pet"][name + ".img"]["info"].touch(); + nl::nx::string["Pet.img"][name].touch(); + } + else + { + nl::nx::item["Cash"][strprefix + ".img"][strid]["info"].touch(); + nl::nx::string["Cash.img"][name].touch(); + } + break; + } + } + + void touch_reactor(int32_t id) + { + nl::nx::reactor[string_format::extend_id(id, 7) + ".img"].touch(); + } + } + + bool mob(int32_t id) + { + return check("m" + std::to_string(id), [id]() { touch_mob(id); }); + } + + bool npc(int32_t id) + { + return check("n" + std::to_string(id), [id]() { touch_npc(id); }); + } + + bool reactor(int32_t id) + { + return check("r" + std::to_string(id), [id]() { touch_reactor(id); }); + } + + bool item(int32_t id) + { + return check("i" + std::to_string(id), [id]() { touch_item(id); }); + } + + bool look(const LookEntry& look) + { + // (the key is the whole outfit: a fren who changes clothes gets checked again) + std::string key = "c" + std::to_string(look.skin) + "." + std::to_string(look.faceid) + "." + std::to_string(look.hairid); + for (const auto& equip : look.equips) + { + key += "." + std::to_string(equip.second); + } + for (const auto& equip : look.maskedequips) + { + key += "." + std::to_string(equip.second); + } + + return check(key, [&look]() { + std::string skin = string_format::extend_id(look.skin, 2); + nl::nx::character["000020" + skin + ".img"].touch(); + nl::nx::character["000120" + skin + ".img"].touch(); + nl::nx::character["Face"]["000" + std::to_string(look.faceid) + ".img"].touch(); + nl::nx::character["Hair"]["000" + std::to_string(look.hairid) + ".img"].touch(); + + auto touch_equip = [](int32_t itemid) { + std::string category = ItemData::get_eqcategory(itemid); + if (!category.empty()) + { + nl::nx::character[category]["0" + std::to_string(itemid) + ".img"].touch(); + } + }; + for (const auto& equip : look.equips) + { + touch_equip(equip.second); + } + for (const auto& equip : look.maskedequips) + { + touch_equip(equip.second); + } + }); + } + + bool game_windows(uint16_t job) + { + // (a warm-up only: if it isn't all in after a few looks, stop looking. Each look walks every node of + // these windows, and while they're still coming down it kept doing that every 120 ms: on a fresh visit + // with little memory to spare the game slowed to a crawl, map fade-ins never finished) + static std::unordered_map tries; + static std::unordered_map asked; + if (tries[job] >= 4) + { + return true; + } + int64_t now = std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count(); + if (now - asked[job] < 1000) + { + return false; + } + asked[job] = now; + bool done = check("W" + std::to_string(job), [job]() { + nl::node ui = nl::nx::ui; + ui["UIWindow4.img"]["Stat"].touch(); + ui["UIWindow4.img"]["Equip"].touch(); + ui["UIWindow2.img"]["Skill"].touch(); + ui["UIWindow2.img"]["Item"].touch(); + ui["UIWindow2.img"]["WorldMap"].touch(); + ui["UIWindow.img"]["Quest"].touch(); + ui["UIWindow.img"]["KeyConfig"].touch(); + ui["UIWindow.img"]["UserList"]["backgrnd"].touch(); + ui["UIWindow.img"]["UserList"]["Tab"].touch(); + ui["UIWindow.img"]["UserList"]["Party"].touch(); + ui["Basic.img"].touch(); + + // the skill books along this job's path (112: 000, 100, 110, 111, 112; Cygnus and Aran start at + // 1000 and 2000), with their names and descriptions + std::unordered_set books = { job / 1000 * 1000, job / 100 * 100, job / 10 * 10, job }; + if (job % 10 > 1) + { + books.insert(job - 1); + } + for (int32_t book : books) + { + nl::nx::skill[string_format::extend_id(book, 3) + ".img"].touch(); + } + nl::nx::string["Skill.img"].touch(); + }); + if (!done) + { + tries[job]++; + } + return done; + } + + bool map(int32_t mapid) + { + return check("M" + std::to_string(mapid), [mapid]() { + std::string prefix = std::to_string(mapid / 100000000); + nl::node src = nl::nx::map["Map"]["Map" + prefix][string_format::extend_id(mapid, 9) + ".img"]; + src.touch(); + + // the art the map's layers point at (the same paths Background, Tile and Obj use) + nl::node back = nl::nx::map["Back"]; + for (nl::node bg : src["back"]) + { + back[bg["bS"] + ".img"][bg["ani"].get_bool() ? "ani" : "back"][bg["no"]].touch(); + } + for (int layer = 0; layer < 8; ++layer) + { + nl::node lsrc = src[std::to_string(layer)]; + std::string tileset = lsrc["info"]["tS"] + ".img"; + for (nl::node tile : lsrc["tile"]) + { + nl::nx::map["Tile"][tileset][tile["u"]][tile["no"]].touch(); + } + for (nl::node obj : lsrc["obj"]) + { + nl::nx::map["Obj"][obj["oS"] + ".img"][obj["l0"]][obj["l1"]][obj["l2"]].touch(); + } + } + + // its music (info/bgm is "Bgm00/Name", stored as Bgm00.img/Name) + std::string bgm = src["info"]["bgm"]; + size_t split = bgm.find('/'); + if (split != std::string::npos) + { + nl::nx::sound.resolve(bgm.substr(0, split) + ".img/" + bgm.substr(split + 1)).touch(); + } + + // whatever lives here: the monsters and NPCs the server is about to spawn, and the reactors + for (nl::node life : src["life"]) + { + std::string type = life["type"]; + int32_t id = parse_id(life["id"]); + if (id < 0) + { + continue; + } + if (type == "m") + { + touch_mob(id); + } + else if (type == "n") + { + touch_npc(id); + } + } + for (nl::node reactor : src["reactor"]) + { + if (int32_t id = parse_id(reactor["id"]); id > 0) + { + touch_reactor(id); + } + } + }); + } + } +} diff --git a/src/client/Util/AssetReady.h b/src/client/Util/AssetReady.h new file mode 100644 index 0000000..a4d2fa3 --- /dev/null +++ b/src/client/Util/AssetReady.h @@ -0,0 +1,27 @@ +#pragma once + +#include "../Net/Login.h" + +#include + +namespace jrc +{ + // Is the art for something about to appear already in memory? Asked before a monster, NPC, reactor or another + // player goes on the map, and before a new map fades in, so drawing them never stops the game to wait for its + // files. While the answer is "not yet", the missing pieces come down in the background; ask again later. + // (Each check runs at most every so often per thing, and a thing found ready stays ready.) + namespace AssetReady + { + bool mob(int32_t id); + bool npc(int32_t id); + bool reactor(int32_t id); + // An item's data and icons (what ItemData reads), for a drop about to fall + bool item(int32_t id); + bool look(const LookEntry& look); + // A map's own art (backgrounds, tiles, objects, music) and everything listed as living on it + bool map(int32_t mapid); + // The game windows a key opens (stats, skills with this job's skill books, items, equips, quests, keys, + // party, world map): asked over and over once in game, so the first press of S or K finds them in memory + bool game_windows(uint16_t job); + } +} diff --git a/src/client/Util/Misc.h b/src/client/Util/Misc.h index f043888..942ea85 100644 --- a/src/client/Util/Misc.h +++ b/src/client/Util/Misc.h @@ -110,7 +110,30 @@ namespace jrc if (hostname) free(hostname); return result; } + + // A string the hosting page put on Module.Dordo (the game socket URL, the account to log in with). + // Empty when the page didn't set one, so callers fall back to their normal behaviour. + inline std::string getDordoString(const char* key) + { + char* value = (char*)EM_ASM_PTR({ + var d = Module.Dordo; + var k = UTF8ToString($0); + var v = (d && typeof d[k] === "string") ? d[k] : ""; + var len = lengthBytesUTF8(v) + 1; + var ptr = _malloc(len); + stringToUTF8(v, ptr, len); + return ptr; + }, key); + std::string result = value ? value : ""; + if (value) free(value); + return result; + } #else + inline std::string getDordoString(const char*) + { + return ""; + } + inline std::string getBrowserHostname() { return "127.0.0.1"; diff --git a/src/client/Util/NxFiles.cpp b/src/client/Util/NxFiles.cpp index 74c6d00..164cf52 100644 --- a/src/client/Util/NxFiles.cpp +++ b/src/client/Util/NxFiles.cpp @@ -78,6 +78,26 @@ namespace jrc return { Error::NLNX, message.c_str() }; } + // The post-Chaos UI.nx dropped the old login map (MapLogin.img), the scene the character select stands in. + // A v83 UI.nx served as Login.nx brings it back; without it the screens just use a flat backdrop. + constexpr const char* LOGIN_SCENE_NX = "Login.nx"; +#ifdef MS_PLATFORM_WASM + const bool has_login_scene = LazyFS::RegisterFile(LOGIN_SCENE_NX, std::string("/assets/") + LOGIN_SCENE_NX); +#else + const bool has_login_scene = std::ifstream{ LOGIN_SCENE_NX }.good(); +#endif + if (has_login_scene) + { + try + { + nl::nx::login = nl::nx::add_file(LOGIN_SCENE_NX); + } + catch (const std::exception&) + { + Console::get().print("[init] Login.nx could not be read; using the flat login backdrop."); + } + } + constexpr const char* POSTCHAOS_BITMAP = "Login.img/WorldSelect/BtChannel/layer:bg"; // Attempt to resolve it to log if this "version" identifier exists diff --git a/src/nlnx/bitmap.cpp b/src/nlnx/bitmap.cpp index e7de766..2aba9b9 100644 --- a/src/nlnx/bitmap.cpp +++ b/src/nlnx/bitmap.cpp @@ -50,15 +50,23 @@ namespace nl if (l + 0x20 > bitmap_buf.size()) bitmap_buf.resize(l + 0x20); - uint64_t data_offset = m_offset + 4; - - uint32_t read_len = l; - std::vector src_buf(read_len); + // The stored form is [compressed length][LZ4 data]. Reading the unpacked size instead came up short for + // small or noisy images (LZ4 can be a few bytes bigger than its input), and the unchecked decoder then + // read past the end of the buffer: garbage pixels, or a memory access out of bounds. + uint32_t compressed = 0; + if (!io_read(fd, &compressed, sizeof(compressed), m_offset)) + return nullptr; + // (LZ4's worst case for l bytes is l + l / 255 + 16) + if (compressed == 0 || compressed > l + l / 255 + 16) + return nullptr; - if (!io_read(fd, src_buf.data(), read_len, data_offset)) + std::vector src_buf(compressed); + if (!io_read(fd, src_buf.data(), compressed, m_offset + 4)) return nullptr; - ::LZ4_decompress_fast(src_buf.data(), bitmap_buf.data(), static_cast(l)); + int unpacked = ::LZ4_decompress_safe(src_buf.data(), bitmap_buf.data(), static_cast(compressed), static_cast(l)); + if (unpacked != static_cast(l)) + return nullptr; return bitmap_buf.data(); } uint16_t bitmap::width() const diff --git a/src/nlnx/node.cpp b/src/nlnx/node.cpp index 8711b76..8dae0b9 100644 --- a/src/nlnx/node.cpp +++ b/src/nlnx/node.cpp @@ -593,4 +593,41 @@ namespace nl { } return n; } + void node::touch() const { +#ifdef MS_PLATFORM_WASM + auto d = DATA_PTR; + if (!d) return; + // (copied out first: the reads below may push the chunk d points into out of the cache) + auto const kind = d->type; + uint32_t index = 0; + size_t length = 0; + if (kind == type::bitmap) { + index = d->bitmap.index; + length = 4 + 4u * d->bitmap.width * d->bitmap.height; + } else if (kind == type::audio) { + index = d->audio.index; + length = d->audio.length; + } + name(); + auto loader = static_cast(const_cast(m_file->base)); + if (kind == type::string) { + get_string(); + } else if (kind == type::bitmap || kind == type::audio) { + uint64_t table = kind == type::bitmap ? m_file->bitmap_table : m_file->audio_table; + auto offset = get_data(m_file, table + index * sizeof(uint64_t)); + if (offset && length) { + uint64_t at = *offset; + if (kind == type::bitmap) { + // (a bitmap is its compressed length, then that many bytes) + auto compressed = get_data(m_file, at); + length = 4 + (compressed ? *compressed : 0); + } + loader->touch_range(at, length); + } + } + for (auto child : *this) { + child.touch(); + } +#endif + } } diff --git a/src/nlnx/node.hpp b/src/nlnx/node.hpp index 4d0a548..7ec9b7b 100644 --- a/src/nlnx/node.hpp +++ b/src/nlnx/node.hpp @@ -114,6 +114,9 @@ namespace nl { int32_t y() const; //The name of the node std::string name() const; + //Reads everything in this node and all below it that drawing or playing it would (names, strings, the + //bytes of bitmaps and sounds), so it's in memory: used inside LazyFS::probe to ask "is this all here yet?" + void touch() const; //The number of children in the node size_t size() const; //Gets the type of data contained within the node diff --git a/src/nlnx/nx.cpp b/src/nlnx/nx.cpp index 366e7ca..015888c 100644 --- a/src/nlnx/nx.cpp +++ b/src/nlnx/nx.cpp @@ -43,6 +43,7 @@ namespace nl { return *files.back(); } node base, character, effect, etc, item, map, mob, morph, npc, quest, reactor, skill, sound, string, tamingmob, ui; + node login; void load_all() { if (exists("Base.nx")) { base = add_file("Base.nx"); diff --git a/src/nlnx/nx.hpp b/src/nlnx/nx.hpp index af6632a..60253c9 100644 --- a/src/nlnx/nx.hpp +++ b/src/nlnx/nx.hpp @@ -19,11 +19,17 @@ #pragma once #include "nxfwd.hpp" +#include + namespace nl { namespace nx { //Pre-defined nodes to access standard MapleStory style data //Make sure you called load_all first extern node base, character, effect, etc, item, map, mob, morph, npc, quest, reactor, skill, sound, string, tamingmob, ui; + //An optional extra file's root (an older UI.nx kept for its login scene); empty when there isn't one + extern node login; + //Opens one more nx file and returns its root + node add_file(std::string name); //Loads the pre-defined nodes from a standard setup of nx files for MapleStory //Only call this function once void load_all(); diff --git a/tests/npc_dialog_test.cpp b/tests/npc_dialog_test.cpp index 2a5d309..d279ae4 100644 --- a/tests/npc_dialog_test.cpp +++ b/tests/npc_dialog_test.cpp @@ -141,7 +141,7 @@ TEST_CASE("NPC rich text preserves content and dialog navigation") const int16_t tile = art["c"].get_bitmap().height(); const int16_t bottom = art["s"].get_bitmap().height(); const auto short_page = Layout::measure(roger.height(), top, tile, bottom, 600); - REQUIRE_MESSAGE((short_page.text_top == top + Layout::PADDING), "First line must start below the frame and clipping boundary"); + REQUIRE_MESSAGE((short_page.text_top == std::min(Layout::WHITE_TOP, top) + Layout::PADDING), "First line must start inside the white field, below the frame's rule"); const auto long_page = Layout::measure(long_word.height(), top, tile, bottom, 600); REQUIRE_MESSAGE((long_page.text_top == short_page.text_top), "Long pages must keep their first line reachable at scroll zero"); REQUIRE_MESSAGE((long_page.tiles * tile + top + bottom <= 560), "Dialog growth must leave screen margins");