nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
bag_window.cc
Go to the documentation of this file.
1#include "client/bag_window.h"
2
3#include <imgui.h>
4
5#include <algorithm>
6#include <cfloat>
7#include <cstddef>
8#include <cstdint>
9#include <cstring>
10#include <optional>
11#include <string>
12#include <utility>
13#include <vector>
14
15#include "absl/strings/str_cat.h"
16#include "absl/strings/substitute.h"
17#include "client/icon.h"
18#include "client/names.h"
19#include "client/theme.h"
20#include "client/translations.h"
21#include "extras/IconsFontAwesome6.h"
22#include "protocol/places.h"
23#include "server/inventory.h"
24
25namespace nanommo {
26
27namespace {
28
29constexpr char kPayload[] = "ITEM";
30// In points, at a scale of one.
31constexpr float kBagSlot = 52.0f;
32constexpr int kColumns = 6;
33// Font Awesome's circle-question, for an item this client doesn't have.
34constexpr uint32_t kUnknownIcon = 0xF059;
35
36// Where a dragged item comes from, and where in its slot the mouse took hold
37// of it. ImGui copies a payload byte for byte, so it's plain data, not the
38// Place message.
39struct Dragged {
40 bool worn = false;
41 uint32_t slot = 0;
42 ImVec2 grab;
43};
44
45// The item the player's holding, while they drag one.
46std::optional<Dragged> Held() {
47 const ImGuiPayload* payload = ImGui::GetDragDropPayload();
48 if (payload == nullptr || !payload->IsDataType(kPayload)) {
49 return std::nullopt;
50 }
51 Dragged dragged;
52 std::memcpy(&dragged, payload->Data, sizeof(dragged));
53 return dragged;
54}
55
56protocol::Place PlaceOf(const Dragged& dragged) {
57 return dragged.worn ? Worn(static_cast<items::Slot>(dragged.slot))
58 : InBag(dragged.slot);
59}
60
61uint32_t Key(const protocol::Place& place) {
62 return place.has_bag() ? place.bag() : static_cast<uint32_t>(place.worn());
63}
64
65bool SamePlace(const protocol::Place& a, const protocol::Place& b) {
66 return a.where_case() == b.where_case() && Key(a) == Key(b);
67}
68
69const items::Stack* StackAt(const protocol::Inventory& bag,
70 const protocol::Place& place) {
71 const auto& slots = place.has_bag() ? bag.bag() : bag.worn();
72 const auto found = slots.find(Key(place));
73 return found != slots.end() ? &found->second : nullptr;
74}
75
76const items::Item* Find(const ItemTable& items, uint32_t id) {
77 const auto found = items.by_id.find(id);
78 return found != items.by_id.end() ? &found->second : nullptr;
79}
80
81const char* StatName(items::Stat stat) {
82 switch (stat) {
83 case items::STAT_DAMAGE:
84 return Tr("damage");
85 case items::STAT_HEALTH:
86 return Tr("health");
87 case items::STAT_ARMOUR:
88 return Tr("armour");
89 default:
90 return Tr("nothing");
91 }
92}
93
94std::string Added(const items::Modifier& modifier) {
95 return absl::StrCat(modifier.amount() >= 0 ? "+" : "", modifier.amount(), " ",
96 StatName(modifier.stat()));
97}
98
99// An empty slot that's worn shows what goes in it, greyed out.
100uint32_t SlotIcon(items::Slot slot) {
101 switch (slot) {
102 case items::SLOT_MAIN_HAND:
103 return 0xF6DE; // hand-fist
104 case items::SLOT_OFF_HAND:
105 return 0xF132; // shield
106 case items::SLOT_HEAD:
107 return 0xF8C0; // hat-cowboy
108 case items::SLOT_BODY:
109 return 0xF553; // shirt
110 case items::SLOT_LEGS:
111 return 0xF554; // person-walking
112 case items::SLOT_FEET:
113 return 0xF696; // socks
114 default:
115 return kUnknownIcon;
116 }
117}
118
119// The item's icon's colour, from its tint, as 0xRRGGBBAA, or the paper's.
120ImU32 TintOf(const items::Item* item) {
121 if (item == nullptr || !item->look().has_tint()) {
122 return colors::kPaper;
123 }
124 const uint32_t rgba = item->look().tint();
125 return IM_COL32((rgba >> 24) & 0xFF, (rgba >> 16) & 0xFF, (rgba >> 8) & 0xFF,
126 rgba & 0xFF);
127}
128
129protocol::ItemAction MoveTo(const protocol::Place& from,
130 const protocol::Place& to, uint32_t count = 0) {
131 protocol::ItemAction action;
132 *action.mutable_move()->mutable_from() = from;
133 *action.mutable_move()->mutable_to() = to;
134 action.mutable_move()->set_count(count);
135 return action;
136}
137
138// Whether the server would move what's at from to to: the bag's own rules,
139// which it keeps, tried on a copy.
140bool Fits(const ItemTable& items, const protocol::Inventory& bag,
141 const protocol::Place& from, const protocol::Place& to) {
142 Inventory copy(bag);
143 return copy.Move(items, from, to).ok();
144}
145
146} // namespace
147
148std::vector<std::string> ItemLines(const ItemTable& items,
149 const items::Stack& stack) {
150 const items::Item* item = Find(items, stack.item());
151 if (item == nullptr) {
152 return {Tr("An item this client doesn't know")};
153 }
154 std::vector<std::string> lines = {NameOf(*item)};
155 if (item->has_equip()) {
156 lines.push_back(
157 absl::Substitute(Tr("Worn: $0"), NameOf(item->equip().slot())));
158 }
159 for (const items::Modifier& modifier : item->equip().modifiers()) {
160 lines.push_back(Added(modifier));
161 }
162 for (const items::Modifier& roll : stack.rolls()) {
163 lines.push_back(absl::Substitute(Tr("$0, rolled"), Added(roll)));
164 }
165 if (item->has_use()) {
166 const items::Use& use = item->use();
167 lines.push_back(use.cooldown_ms() > 0
168 ? absl::Substitute(Tr("Use: heals $0, one every $1 s"),
169 use.heal(), use.cooldown_ms() / 1000)
170 : absl::Substitute(Tr("Use: heals $0"), use.heal()));
171 }
172 if (StackSize(*item) > 1) {
173 lines.push_back(absl::Substitute(Tr("Stacks up to $0"), StackSize(*item)));
174 }
175 return lines;
176}
177
178std::optional<uint32_t> FirstEmptySlot(const protocol::Inventory& bag) {
179 for (uint32_t slot = 0; slot < kBagSlots; ++slot) {
180 if (!bag.bag().contains(slot)) {
181 return slot;
182 }
183 }
184 return std::nullopt;
185}
186
187std::optional<protocol::ItemAction> QuickAction(const ItemTable& items,
188 const protocol::Inventory& bag,
189 const protocol::Place& place) {
190 const items::Stack* stack = StackAt(bag, place);
191 const items::Item* item =
192 stack != nullptr ? Find(items, stack->item()) : nullptr;
193 if (item == nullptr) {
194 return std::nullopt;
195 }
196 if (place.has_worn()) {
197 if (const std::optional<uint32_t> empty = FirstEmptySlot(bag)) {
198 return MoveTo(place, InBag(*empty));
199 }
200 return std::nullopt;
201 }
202 if (item->has_use()) {
203 protocol::ItemAction action;
204 action.set_use(place.bag());
205 return action;
206 }
207 if (item->has_equip()) {
208 return MoveTo(place, Worn(item->equip().slot()));
209 }
210 return std::nullopt;
211}
212
213std::optional<protocol::ItemAction> ItemSlot(const ItemTable& items,
214 const protocol::Inventory& bag,
215 const protocol::Place& place,
216 float size, bool locked) {
217 const items::Stack* stack = StackAt(bag, place);
218 const items::Item* item =
219 stack != nullptr ? Find(items, stack->item()) : nullptr;
220 std::optional<protocol::ItemAction> action;
221 ImGui::PushID(place.has_bag() ? static_cast<int>(place.bag())
222 : 100 + static_cast<int>(place.worn()));
223
224 ImGui::InvisibleButton("##slot", {size, size});
225 const bool hovered = ImGui::IsItemHovered();
226 const ImVec2 min = ImGui::GetItemRectMin();
227 const ImVec2 max = ImGui::GetItemRectMax();
228
229 // Taken hold of, it follows the mouse, from where it was held. Offered in
230 // a trade, it stays, as the trade takes it from here.
231 if (stack != nullptr && !locked &&
232 ImGui::BeginDragDropSource(ImGuiDragDropFlags_SourceNoPreviewTooltip)) {
233 const ImVec2 down = ImGui::GetIO().MouseClickedPos[ImGuiMouseButton_Left];
234 const Dragged dragged{.worn = place.has_worn(),
235 .slot = Key(place),
236 .grab = {down.x - min.x, down.y - min.y}};
237 ImGui::SetDragDropPayload(kPayload, &dragged, sizeof(dragged),
238 ImGuiCond_Once);
239 ImGui::EndDragDropSource();
240 }
241 const std::optional<Dragged> held = Held();
242 const bool source = held && SamePlace(PlaceOf(*held), place);
243
244 // Lit green where what's held would go, by the server's own rules, and red
245 // where it wouldn't.
246 ImU32 edge = 0;
247 if (held && !source && ImGui::BeginDragDropTarget()) {
248 const protocol::Place from = PlaceOf(*held);
249 const bool fits = !locked && Fits(items, bag, from, place);
250 edge = fits ? colors::kGood : colors::kHealth;
251 if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(
252 kPayload, ImGuiDragDropFlags_AcceptBeforeDelivery |
253 ImGuiDragDropFlags_AcceptNoDrawDefaultRect);
254 payload != nullptr && payload->IsDelivery() && fits) {
255 // With Shift, half the stack goes, and the rest stays.
256 const items::Stack* moving = StackAt(bag, from);
257 const uint32_t count =
258 ImGui::GetIO().KeyShift && moving != nullptr && moving->count() > 1
259 ? moving->count() / 2
260 : 0;
261 action = MoveTo(from, place, count);
262 }
263 ImGui::EndDragDropTarget();
264 } else if (hovered && !held) {
265 edge = colors::kGold;
266 }
267
268 DrawSlot(ImGui::GetWindowDrawList(), min, max, edge);
269 ImDrawList* draw = ImGui::GetWindowDrawList();
270 // What's held is drawn over the slot under it, so the verdict goes round the
271 // slot as well, where it still shows.
272 if (held && !source && edge != 0) {
273 const float out = Ui(3.0f);
274 draw->AddRect({min.x - out, min.y - out}, {max.x + out, max.y + out}, edge,
275 Ui(2.0f), 0, Ui(2.0f));
276 }
277 if (stack != nullptr) {
278 const ImU32 tint = TintOf(item);
279 const std::string icon =
280 Icon(item != nullptr ? item->look().icon() : kUnknownIcon);
281 // Its place stays, faint, while it's held, and what's offered in a trade
282 // is faint until it's over.
283 const float alpha = source ? 0.25f : locked ? 0.45f : 1.0f;
284 DrawSlotIcon(draw, min, max, icon.c_str(), tint, alpha);
285 if (stack->count() > 1 && !source) {
286 const std::string count = absl::StrCat(stack->count());
287 ImFont* bold = GetFonts().bold;
288 const float count_size = Ui(14.0f);
289 const ImVec2 extent =
290 bold->CalcTextSizeA(count_size, FLT_MAX, 0.0f, count.c_str());
292 draw, bold, count_size,
293 {max.x - extent.x - Ui(4.0f), max.y - extent.y - Ui(2.0f)},
294 colors::kPaper, count.c_str());
295 }
296 if (source) {
297 DrawDragged(icon.c_str(), tint, size, held->grab);
298 }
299 } else if (place.has_worn()) {
300 // An empty slot that's worn shows what goes in it, faint.
301 DrawSlotIcon(draw, min, max, Icon(SlotIcon(place.worn())).c_str(),
302 colors::kMuted, 0.3f);
303 }
304
305 if (stack != nullptr && !locked && hovered &&
306 ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) {
307 action = QuickAction(items, bag, place);
308 }
309 if (hovered && !held && !ImGui::IsPopupOpen("menu")) {
310 ImGui::BeginTooltip();
311 if (stack == nullptr) {
312 ImGui::TextDisabled(
313 "%s", place.has_worn() ? NameOf(place.worn()) : Tr("Empty"));
314 } else {
315 const std::vector<std::string> lines = ItemLines(items, *stack);
316 ImGui::PushFont(GetFonts().title, 15.0f);
317 ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(colors::kGoldLight),
318 "%s", lines.front().c_str());
319 ImGui::PopFont();
320 for (std::size_t i = 1; i < lines.size(); ++i) {
321 ImGui::TextDisabled("%s", lines[i].c_str());
322 }
323 if (locked) {
324 ImGui::TextDisabled("%s", Tr("Offered in the trade"));
325 }
326 }
327 ImGui::EndTooltip();
328 }
329
330 if (stack != nullptr && !locked && ImGui::BeginPopupContextItem("menu")) {
331 if (place.has_bag() && item != nullptr && item->has_use() &&
332 ImGui::MenuItem(TrLabel("Use"))) {
333 action.emplace().set_use(place.bag());
334 }
335 if (place.has_bag() && item != nullptr && item->has_equip() &&
336 ImGui::MenuItem(TrLabel("Wear"))) {
337 action = MoveTo(place, Worn(item->equip().slot()));
338 }
339 const std::optional<uint32_t> empty = FirstEmptySlot(bag);
340 // Greyed out when the bag has no room for it.
341 if (place.has_worn() &&
342 ImGui::MenuItem(TrLabel("Take off"), nullptr, false,
343 empty.has_value()) &&
344 empty) {
345 action = MoveTo(place, InBag(*empty));
346 }
347 if (ImGui::MenuItem(TrLabel("Throw away"))) {
348 *action.emplace().mutable_destroy() = place;
349 }
350 ImGui::EndPopup();
351 }
352 ImGui::PopID();
353 return action;
354}
355
356bool StackSlot(const ItemTable& items, const items::Stack* stack, float size,
357 uint32_t edge) {
358 const bool clicked = ImGui::InvisibleButton("##stack", {size, size});
359 const ImVec2 min = ImGui::GetItemRectMin();
360 const ImVec2 max = ImGui::GetItemRectMax();
361 ImDrawList* draw = ImGui::GetWindowDrawList();
362 DrawSlot(draw, min, max, edge);
363 if (stack == nullptr) {
364 return false;
365 }
366 const items::Item* item = Find(items, stack->item());
368 draw, min, max,
369 Icon(item != nullptr ? item->look().icon() : kUnknownIcon).c_str(),
370 TintOf(item));
371 if (stack->count() > 1) {
372 const std::string count = absl::StrCat(stack->count());
373 ImFont* bold = GetFonts().bold;
374 const float count_size = Ui(14.0f);
375 const ImVec2 extent =
376 bold->CalcTextSizeA(count_size, FLT_MAX, 0.0f, count.c_str());
377 DrawShadowedText(draw, bold, count_size,
378 {max.x - extent.x - Ui(4.0f), max.y - extent.y - Ui(2.0f)},
379 colors::kPaper, count.c_str());
380 }
381 if (ImGui::IsItemHovered()) {
382 const std::vector<std::string> lines = ItemLines(items, *stack);
383 ImGui::BeginTooltip();
384 ImGui::PushFont(GetFonts().title, 15.0f);
385 ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(colors::kGoldLight), "%s",
386 lines.front().c_str());
387 ImGui::PopFont();
388 for (std::size_t i = 1; i < lines.size(); ++i) {
389 ImGui::TextDisabled("%s", lines[i].c_str());
390 }
391 ImGui::EndTooltip();
392 }
393 return clicked;
394}
395
396std::optional<protocol::Place> AcceptItem() {
397 const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(kPayload);
398 if (payload == nullptr) {
399 return std::nullopt;
400 }
401 Dragged dragged;
402 std::memcpy(&dragged, payload->Data, sizeof(dragged));
403 return PlaceOf(dragged);
404}
405
406std::optional<protocol::ItemAction> BagWindow::Build(
407 const protocol::Inventory& bag, const protocol::TradeSide& offered) {
408 std::optional<protocol::ItemAction> action;
409 // Let go of over nothing, from the bag or from what's worn, it's thrown
410 // away, once the player says so.
411 if (const std::optional<Dragged> held = Held();
412 held && ImGui::IsMouseReleased(ImGuiMouseButton_Left) &&
413 !ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow |
414 ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) {
415 throwing_ = PlaceOf(*held);
416 }
417 if (throwing_) {
418 if (std::optional<protocol::ItemAction> done = BuildThrowAway(bag)) {
419 action = std::move(done);
420 }
421 }
422 if (!visible_) {
423 return action;
424 }
425 const ImVec2 display = ImGui::GetIO().DisplaySize;
426 ImGui::SetNextWindowPos({display.x - Ui(18.0f), display.y * 0.55f},
427 ImGuiCond_FirstUseEver, {1.0f, 0.5f});
428 if (BeginPanel("Bag", &visible_,
429 ImGuiWindowFlags_AlwaysAutoResize |
430 ImGuiWindowFlags_NoSavedSettings)) {
431 const float slot = Ui(kBagSlot);
432 ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, Ui(ImVec2{5.0f, 5.0f}));
433 for (uint32_t index = 0; index < kBagSlots; ++index) {
434 if (index % kColumns != 0) {
435 ImGui::SameLine();
436 }
437 if (std::optional<protocol::ItemAction> done = ItemSlot(
438 items_, bag, InBag(index), slot, offered.bag().contains(index))) {
439 action = std::move(done);
440 }
441 }
442 ImGui::PopStyleVar();
443 // Gold takes no slot, so it goes under them.
444 ImGui::TextColored(
445 ImGui::ColorConvertU32ToFloat4(colors::kGold), ICON_FA_COINS " %s",
446 absl::Substitute(TrN("$0 gold", "$0 gold", bag.gold()), bag.gold())
447 .c_str());
448 }
449 EndPanel();
450 return action;
451}
452
453std::optional<protocol::ItemAction> BagWindow::BuildThrowAway(
454 const protocol::Inventory& bag) {
455 if (!throwing_) {
456 return std::nullopt;
457 }
458 const protocol::Place place = *throwing_;
459 const items::Stack* stack = StackAt(bag, place);
460 const items::Item* item =
461 stack != nullptr ? Find(items_, stack->item()) : nullptr;
462 if (stack == nullptr) {
463 throwing_.reset();
464 return std::nullopt;
465 }
466 const ImVec2 display = ImGui::GetIO().DisplaySize;
467 ImGui::SetNextWindowPos({display.x / 2.0f, display.y * 0.42f},
468 ImGuiCond_Always, {0.5f, 0.5f});
469 bool open = true;
470 std::optional<protocol::ItemAction> action;
471 BeginPanel("Throw away?", &open,
472 ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove |
473 ImGuiWindowFlags_NoSavedSettings);
474 const char* name = item != nullptr ? NameOf(*item) : Tr("this item");
475 ImGui::TextUnformatted(
476 absl::Substitute(
477 TrN("Throw away the $1, for good?",
478 "Throw away all $0 of the $1, for good?", CountOf(*stack)),
479 CountOf(*stack), name)
480 .c_str());
481 ImGui::Spacing();
482 if (GameButton("Throw away", {Ui(150.0f), 0.0f}, true)) {
483 *action.emplace().mutable_destroy() = place;
484 open = false;
485 }
486 ImGui::SameLine();
487 if (GameButton("Keep it", {Ui(150.0f), 0.0f}) ||
488 ImGui::IsKeyPressed(ImGuiKey_Escape)) {
489 open = false;
490 }
491 EndPanel();
492 if (!open) {
493 throwing_.reset();
494 }
495 return action;
496}
497
498} // namespace nanommo
std::optional< protocol::ItemAction > Build(const protocol::Inventory &bag, const protocol::TradeSide &offered={})
What's offered in a trade stays in its slot until the trade's over.
constexpr ImU32 kGood
Definition theme.h:32
constexpr ImU32 kGoldLight
Definition theme.h:22
constexpr ImU32 kMuted
Definition theme.h:27
constexpr ImU32 kPaper
Definition theme.h:26
constexpr ImU32 kGold
Definition theme.h:21
constexpr ImU32 kHealth
Definition theme.h:30
Definition chat.cc:9
bool BeginPanel(const char *name, bool *open, ImGuiWindowFlags flags, float alpha)
Definition theme.cc:320
uint32_t CountOf(const items::Stack &stack)
How many are in the stack, which is one when it doesn't say.
Definition items.cc:102
float Ui(float points)
Definition theme.h:67
void EndPanel()
Definition theme.cc:379
const char * Tr(const char *text)
std::string Icon(uint32_t code)
Definition icon.h:12
const char * TrN(const char *one, const char *many, uint64_t n)
The form for the count: in English, one for 1 and many for the rest.
const char * TrLabel(const char *label)
void DrawSlotIcon(ImDrawList *draw, ImVec2 min, ImVec2 max, const char *icon, ImU32 color, float alpha)
An icon in the middle of a slot, in its colour, on a glow of that colour.
Definition theme.cc:519
constexpr uint32_t kBagSlots
How many slots each player's bag has.
Definition items.h:15
std::optional< uint32_t > FirstEmptySlot(const protocol::Inventory &bag)
The first slot of the bag with nothing in it, if it has one.
uint32_t StackSize(const items::Item &item)
How many of the item go in one slot of a bag.
Definition items.cc:98
protocol::Place Worn(items::Slot slot)
A slot that's worn.
Definition places.cc:13
protocol::Place InBag(uint32_t slot)
A place in the bag, by its slot from zero.
Definition places.cc:7
std::optional< protocol::ItemAction > QuickAction(const ItemTable &items, const protocol::Inventory &bag, const protocol::Place &place)
std::optional< protocol::Place > AcceptItem()
std::optional< protocol::ItemAction > ItemSlot(const ItemTable &items, const protocol::Inventory &bag, const protocol::Place &place, float size, bool locked)
bool StackSlot(const ItemTable &items, const items::Stack *stack, float size, uint32_t edge)
void DrawDragged(const char *icon, ImU32 color, float size, ImVec2 grab)
Definition theme.cc:536
bool GameButton(const char *label, ImVec2 size, bool primary, bool enabled)
Definition theme.cc:381
void DrawShadowedText(ImDrawList *draw, ImFont *font, float size, ImVec2 at, ImU32 color, const char *text)
Text with a shadow under it.
Definition theme.cc:272
void DrawSlot(ImDrawList *draw, ImVec2 min, ImVec2 max, ImU32 edge)
Definition theme.cc:480
const Fonts & GetFonts()
Definition theme.cc:66
const char * NameOf(const items::Item &item)
Definition names.cc:14
std::vector< std::string > ItemLines(const ItemTable &items, const items::Stack &stack)
ImFont * bold
Definition theme.h:43
The items in the items file, by id.
Definition items.h:18