yaze 0.2.0
Link to the Past ROM Editor
 
Loading...
Searching...
No Matches
asset_browser.cc
Go to the documentation of this file.
1#include "asset_browser.h"
2
3#include "absl/strings/str_format.h"
4
5namespace yaze {
6namespace app {
7namespace gui {
8
9using namespace ImGui;
10
11const ImGuiTableSortSpecs* AssetObject::s_current_sort_specs = NULL;
12
14 const std::array<gfx::Bitmap, kNumGfxSheets>& bmp_manager) {
15 PushItemWidth(GetFontSize() * 10);
16 SeparatorText("Contents");
17 Checkbox("Show Type Overlay", &ShowTypeOverlay);
18 SameLine();
19 Checkbox("Allow Sorting", &AllowSorting);
20 SameLine();
21 Checkbox("Stretch Spacing", &StretchSpacing);
22 SameLine();
23 Checkbox("Allow dragging unselected item", &AllowDragUnselected);
24 SameLine();
25 Checkbox("Allow box-selection", &AllowBoxSelect);
26 SameLine();
27 SliderFloat("Icon Size", &IconSize, 16.0f, 128.0f, "%.0f");
28 SameLine();
29 SliderInt("Icon Spacing", &IconSpacing, 0, 32);
30 SameLine();
31 SliderInt("Icon Hit Spacing", &IconHitSpacing, 0, 32);
32 PopItemWidth();
33
34 // Filter by types
35 static bool filter_type[4] = {true, true, true, true};
36 Text("Filter by type:");
37 SameLine();
38 Checkbox("Unsorted", &filter_type[0]);
39 SameLine();
40 Checkbox("Dungeon", &filter_type[1]);
41 SameLine();
42 Checkbox("Overworld", &filter_type[2]);
43 SameLine();
44 Checkbox("Sprite", &filter_type[3]);
45
46 // Show a table with ONLY one header row to showcase the idea/possibility of
47 // using this to provide a sorting UI
48 if (AllowSorting) {
49 PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
50 ImGuiTableFlags table_flags_for_sort_specs =
51 ImGuiTableFlags_Sortable | ImGuiTableFlags_SortMulti |
52 ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Borders;
53 if (BeginTable("for_sort_specs_only", 2, table_flags_for_sort_specs,
54 ImVec2(0.0f, GetFrameHeight()))) {
55 TableSetupColumn("Index");
56 TableSetupColumn("Type");
57 TableHeadersRow();
58 if (ImGuiTableSortSpecs* sort_specs = TableGetSortSpecs())
59 if (sort_specs->SpecsDirty || RequestSort) {
60 AssetObject::SortWithSortSpecs(sort_specs, Items.Data, Items.Size);
61 sort_specs->SpecsDirty = RequestSort = false;
62 }
63 EndTable();
64 }
65 PopStyleVar();
66 }
67
68 ImGuiIO& io = GetIO();
69 SetNextWindowContentSize(ImVec2(
70 0.0f, LayoutOuterPadding +
72 if (BeginChild("Assets", ImVec2(0.0f, -GetTextLineHeightWithSpacing()),
73 ImGuiChildFlags_Border, ImGuiWindowFlags_NoMove)) {
74 ImDrawList* draw_list = GetWindowDrawList();
75
76 const float avail_width = GetContentRegionAvail().x;
77 UpdateLayoutSizes(avail_width);
78
79 // Calculate and store start position.
80 ImVec2 start_pos = GetCursorScreenPos();
81 start_pos = ImVec2(start_pos.x + LayoutOuterPadding,
82 start_pos.y + LayoutOuterPadding);
83 SetCursorScreenPos(start_pos);
84
85 // Multi-select
86 ImGuiMultiSelectFlags ms_flags = ImGuiMultiSelectFlags_ClearOnEscape |
87 ImGuiMultiSelectFlags_ClearOnClickVoid;
88
89 // - Enable box-select (in 2D mode, so that changing box-select rectangle
90 // X1/X2 boundaries will affect clipped items)
91 if (AllowBoxSelect) ms_flags |= ImGuiMultiSelectFlags_BoxSelect2d;
92
93 // - This feature allows dragging an unselected item without selecting it
94 // (rarely used)
96 ms_flags |= ImGuiMultiSelectFlags_SelectOnClickRelease;
97
98 // - Enable keyboard wrapping on X axis
99 // (FIXME-MULTISELECT: We haven't designed/exposed a general nav wrapping
100 // api yet, so this flag is provided as a courtesy to avoid doing:
101 // NavMoveRequestTryWrapping(GetCurrentWindow(),
102 // ImGuiNavMoveFlags_WrapX);
103 // When we finish implementing a more general API for this, we will
104 // obsolete this flag in favor of the new system)
105 ms_flags |= ImGuiMultiSelectFlags_NavWrapX;
106
107 ImGuiMultiSelectIO* ms_io =
108 BeginMultiSelect(ms_flags, Selection.Size, Items.Size);
109
110 // Use custom selection adapter: store ID in selection (recommended)
111 Selection.UserData = this;
112 Selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self_,
113 int idx) {
114 GfxSheetAssetBrowser* self = (GfxSheetAssetBrowser*)self_->UserData;
115 return self->Items[idx].ID;
116 };
117 Selection.ApplyRequests(ms_io);
118
119 const bool want_delete =
120 (Shortcut(ImGuiKey_Delete, ImGuiInputFlags_Repeat) &&
121 (Selection.Size > 0)) ||
123 const int item_curr_idx_to_focus =
124 want_delete ? Selection.ApplyDeletionPreLoop(ms_io, Items.Size) : -1;
125 RequestDelete = false;
126
127 // Push LayoutSelectableSpacing (which is LayoutItemSpacing minus
128 // hit-spacing, if we decide to have hit gaps between items) Altering
129 // style ItemSpacing may seem unnecessary as we position every items using
130 // SetCursorScreenPos()... But it is necessary for two reasons:
131 // - Selectables uses it by default to visually fill the space between two
132 // items.
133 // - The vertical spacing would be measured by Clipper to calculate line
134 // height if we didn't provide it explicitly (here we do).
135 PushStyleVar(ImGuiStyleVar_ItemSpacing,
137
138 // Rendering parameters
139 const ImU32 icon_type_overlay_colors[5] = {
140 0, IM_COL32(200, 70, 70, 255), IM_COL32(70, 170, 70, 255),
141 IM_COL32(70, 70, 200, 255), IM_COL32(200, 200, 200, 255)};
142 const ImU32 icon_bg_color = GetColorU32(ImGuiCol_MenuBarBg);
143 const ImVec2 icon_type_overlay_size = ImVec2(5.0f, 5.0f);
144 const bool display_label = (LayoutItemSize.x >= CalcTextSize("999").x);
145
146 const int column_count = LayoutColumnCount;
147 ImGuiListClipper clipper;
148 clipper.Begin(LayoutLineCount, LayoutItemStep.y);
149
150 // Ensure focused item line is not clipped.
151 if (item_curr_idx_to_focus != -1)
152 clipper.IncludeItemByIndex(item_curr_idx_to_focus / column_count);
153
154 // Ensure RangeSrc item line is not clipped.
155 if (ms_io->RangeSrcItem != -1)
156 clipper.IncludeItemByIndex((int)ms_io->RangeSrcItem / column_count);
157
158 while (clipper.Step()) {
159 for (int line_idx = clipper.DisplayStart; line_idx < clipper.DisplayEnd;
160 line_idx++) {
161 const int item_min_idx_for_current_line = line_idx * column_count;
162 const int item_max_idx_for_current_line =
163 IM_MIN((line_idx + 1) * column_count, Items.Size);
164 for (int item_idx = item_min_idx_for_current_line;
165 item_idx < item_max_idx_for_current_line; ++item_idx) {
166 AssetObject* item_data = &Items[item_idx];
167 PushID((int)item_data->ID);
168
169 // Position item
170 ImVec2 pos =
171 ImVec2(start_pos.x + (item_idx % column_count) * LayoutItemStep.x,
172 start_pos.y + line_idx * LayoutItemStep.y);
173 SetCursorScreenPos(pos);
174
175 SetNextItemSelectionUserData(item_idx);
176 bool item_is_selected = Selection.Contains((ImGuiID)item_data->ID);
177 bool item_is_visible = IsRectVisible(LayoutItemSize);
178 Selectable("", item_is_selected, ImGuiSelectableFlags_None,
180
181 // Update our selection state immediately (without waiting for
182 // EndMultiSelect() requests) because we use this to alter the color
183 // of our text/icon.
184 if (IsItemToggledSelection()) item_is_selected = !item_is_selected;
185
186 // Focus (for after deletion)
187 if (item_curr_idx_to_focus == item_idx) SetKeyboardFocusHere(-1);
188
189 // Drag and drop
190 if (BeginDragDropSource()) {
191 // Create payload with full selection OR single unselected item.
192 // (the later is only possible when using
193 // ImGuiMultiSelectFlags_SelectOnClickRelease)
194 if (GetDragDropPayload() == NULL) {
195 ImVector<ImGuiID> payload_items;
196 void* it = NULL;
197 ImGuiID id = 0;
198 if (!item_is_selected)
199 payload_items.push_back(item_data->ID);
200 else
201 while (Selection.GetNextSelectedItem(&it, &id))
202 payload_items.push_back(id);
203 SetDragDropPayload("ASSETS_BROWSER_ITEMS", payload_items.Data,
204 (size_t)payload_items.size_in_bytes());
205 }
206
207 // Display payload content in tooltip, by extracting it from the
208 // payload data (we could read from selection, but it is more
209 // correct and reusable to read from payload)
210 const ImGuiPayload* payload = GetDragDropPayload();
211 const int payload_count =
212 (int)payload->DataSize / (int)sizeof(ImGuiID);
213 Text("%d assets", payload_count);
214
215 EndDragDropSource();
216 }
217
218 // Render icon (a real app would likely display an image/thumbnail
219 // here) Because we use ImGuiMultiSelectFlags_BoxSelect2d, clipping
220 // vertical may occasionally be larger, so we coarse-clip our
221 // rendering as well.
222 if (item_is_visible) {
223 ImVec2 box_min(pos.x - 1, pos.y - 1);
224 ImVec2 box_max(box_min.x + LayoutItemSize.x + 2,
225 box_min.y + LayoutItemSize.y + 2); // Dubious
226 draw_list->AddRectFilled(box_min, box_max,
227 icon_bg_color); // Background color
228
229 if (display_label) {
230 ImU32 label_col = GetColorU32(
231 item_is_selected ? ImGuiCol_Text : ImGuiCol_TextDisabled);
232 draw_list->AddImage(
233 (ImTextureID)(intptr_t)bmp_manager[item_data->ID].texture(),
234 box_min, box_max, ImVec2(0, 0), ImVec2(1, 1),
235 GetColorU32(ImVec4(1, 1, 1, 1)));
236 draw_list->AddText(ImVec2(box_min.x, box_max.y - GetFontSize()),
237 label_col,
238 absl::StrFormat("%X", item_data->ID).c_str());
239 }
240 if (ShowTypeOverlay && item_data->Type != 0) {
241 ImU32 type_col = icon_type_overlay_colors
242 [item_data->Type % IM_ARRAYSIZE(icon_type_overlay_colors)];
243 draw_list->AddRectFilled(
244 ImVec2(box_max.x - 2 - icon_type_overlay_size.x,
245 box_min.y + 2),
246 ImVec2(box_max.x - 2,
247 box_min.y + 2 + icon_type_overlay_size.y),
248 type_col);
249 }
250 }
251
252 PopID();
253 }
254 }
255 }
256 clipper.End();
257 PopStyleVar(); // ImGuiStyleVar_ItemSpacing
258
259 // Context menu
260 if (BeginPopupContextWindow()) {
261 Text("Selection: %d items", Selection.Size);
262 Separator();
263 if (BeginMenu("Set Type")) {
264 if (MenuItem("Unsorted")) {
265 void* it = NULL;
266 ImGuiID id = 0;
267 while (Selection.GetNextSelectedItem(&it, &id)) Items[id].Type = 0;
268 }
269 if (MenuItem("Dungeon")) {
270 void* it = NULL;
271 ImGuiID id = 0;
272 while (Selection.GetNextSelectedItem(&it, &id)) Items[id].Type = 1;
273 }
274 if (MenuItem("Overworld")) {
275 void* it = NULL;
276 ImGuiID id = 0;
277 while (Selection.GetNextSelectedItem(&it, &id)) Items[id].Type = 2;
278 }
279 if (MenuItem("Sprite")) {
280 void* it = NULL;
281 ImGuiID id = 0;
282 while (Selection.GetNextSelectedItem(&it, &id)) Items[id].Type = 3;
283 }
284 EndMenu();
285 }
286 Separator();
287 if (MenuItem("Delete", "Del", false, Selection.Size > 0))
288 RequestDelete = true;
289 EndPopup();
290 }
291
292 ms_io = EndMultiSelect();
293 Selection.ApplyRequests(ms_io);
294 if (want_delete)
295 Selection.ApplyDeletionPostLoop(ms_io, Items, item_curr_idx_to_focus);
296
297 // Zooming with CTRL+Wheel
298 if (IsWindowAppearing()) ZoomWheelAccum = 0.0f;
299 if (IsWindowHovered() && io.MouseWheel != 0.0f &&
300 IsKeyDown(ImGuiMod_Ctrl) && IsAnyItemActive() == false) {
301 ZoomWheelAccum += io.MouseWheel;
302 if (fabsf(ZoomWheelAccum) >= 1.0f) {
303 // Calculate hovered item index from mouse location
304 // FIXME: Locking aiming on 'hovered_item_idx' (with a cool-down
305 // timer) would ensure zoom keeps on it.
306 const float hovered_item_nx =
307 (io.MousePos.x - start_pos.x + LayoutItemSpacing * 0.5f) /
309 const float hovered_item_ny =
310 (io.MousePos.y - start_pos.y + LayoutItemSpacing * 0.5f) /
312 const int hovered_item_idx =
313 ((int)hovered_item_ny * LayoutColumnCount) + (int)hovered_item_nx;
314 // SetTooltip("%f,%f -> item %d", hovered_item_nx,
315 // hovered_item_ny, hovered_item_idx); // Move those 4 lines in block
316 // above for easy debugging
317
318 // Zoom
319 IconSize *= powf(1.1f, (float)(int)ZoomWheelAccum);
320 IconSize = IM_CLAMP(IconSize, 16.0f, 128.0f);
322 UpdateLayoutSizes(avail_width);
323
324 // Manipulate scroll to that we will land at the same Y location of
325 // currently hovered item.
326 // - Calculate next frame position of item under mouse
327 // - Set new scroll position to be used in next BeginChild()
328 // call.
329 float hovered_item_rel_pos_y =
330 ((float)(hovered_item_idx / LayoutColumnCount) +
331 fmodf(hovered_item_ny, 1.0f)) *
333 hovered_item_rel_pos_y += GetStyle().WindowPadding.y;
334 float mouse_local_y = io.MousePos.y - GetWindowPos().y;
335 SetScrollY(hovered_item_rel_pos_y - mouse_local_y);
336 }
337 }
338 }
339 EndChild();
340
341 Text("Selected: %d/%d items", Selection.Size, Items.Size);
342}
343
344} // namespace gui
345} // namespace app
346} // namespace yaze
#define IM_CLAMP(V, MN, MX)
#define IM_MIN(A, B)
Definition input.cc:18
Definition common.cc:22
static const ImGuiTableSortSpecs * s_current_sort_specs
static void SortWithSortSpecs(ImGuiTableSortSpecs *sort_specs, AssetObject *items, int items_count)
void ApplyDeletionPostLoop(ImGuiMultiSelectIO *ms_io, ImVector< ITEM_TYPE > &items, int item_curr_idx_to_select)
int ApplyDeletionPreLoop(ImGuiMultiSelectIO *ms_io, int items_count)
void Draw(const std::array< gfx::Bitmap, kNumGfxSheets > &bmp_manager)
ExampleSelectionWithDeletion Selection
void UpdateLayoutSizes(float avail_width)