Debian Codegraph @

src/cdogsed/nk_window.c

raw symbols SCIP
1 /*
2 C-Dogs SDL
3 A port of the legendary (and fun) action/arcade cdogs.
4 Copyright (c) 2019-2023 Cong Xu
5 All rights reserved.
6
7 Redistribution and use in source and binary forms, with or without
8 modification, are permitted provided that the following conditions are met:
9
10 Redistributions of source code must retain the above copyright notice, this
11 list of conditions and the following disclaimer.
12 Redistributions in binary form must reproduce the above copyright notice,
13 this list of conditions and the following disclaimer in the documentation
14 and/or other materials provided with the distribution.
15
16 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 POSSIBILITY OF SUCH DAMAGE.
27 */
28 #include "nk_window.h"
29
30 #include <stdbool.h>
31
32 #include <SDL_opengl.h>
33 #define NK_INCLUDE_FIXED_TYPES
34 #define NK_INCLUDE_STANDARD_IO
35 #define NK_INCLUDE_DEFAULT_ALLOCATOR
36 #define NK_INCLUDE_VERTEX_BUFFER_OUTPUT
37 #define NK_INCLUDE_FONT_BAKING
38 #define NK_INCLUDE_DEFAULT_FONT
39 #define NK_BUTTON_TRIGGER_ON_RELEASE
40 #define NK_IMPLEMENTATION
41 #define NK_SDL_GL2_IMPLEMENTATION
42 #ifdef _MSC_VER
43 // Guard against compile time constant in nk_memset
44 #pragma warning(push)
45 #pragma warning(disable : 4127)
46 #endif
47 #include <nuklear/nuklear.h>
48 #ifdef _MSC_VER
49 #pragma warning(pop)
50 #endif
51 #include <cdogs/draw/draw_actor.h>
52 #include <cdogs/log.h>
53 #include <cdogs/sys_config.h>
54 #include <nuklear/nuklear_sdl_gl2.h>
55
56 void NKWindowInit(NKWindowConfig *cfg)
57 {
58 SDL_Init(SDL_INIT_VIDEO);
59 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
60 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
61 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
62 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
63 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
64
65 cfg->win = SDL_CreateWindow(
66 cfg->Title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
67 cfg->Size.x, cfg->Size.y,
68 SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | cfg->WindowFlags);
69 SDL_SetWindowMinimumSize(cfg->win, cfg->MinSize.x, cfg->MinSize.y);
70 if (cfg->Icon)
71 {
72 SDL_SetWindowIcon(cfg->win, cfg->Icon);
73 }
74
75 cfg->glContext = SDL_GL_CreateContext(cfg->win);
76 glEnable(GL_TEXTURE_2D);
77 glEnable(GL_BLEND);
78 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
79
80 cfg->ctx = nk_sdl_init(cfg->win);
81 cfg->ctx->style.checkbox.hover.data.color = nk_rgb(96, 96, 96);
82 cfg->ctx->style.checkbox.normal.data.color = nk_rgb(64, 64, 64);
83 cfg->ctx->style.checkbox.cursor_hover.data.color = nk_rgb(255, 255, 255);
84 cfg->ctx->style.checkbox.cursor_normal.data.color = nk_rgb(200, 200, 200);
85
86 // Initialise fonts
87 struct nk_font_atlas *atlas;
88 nk_sdl_font_stash_begin(&atlas);
89 nk_sdl_font_stash_end();
90 }
91
92 static bool HandleEvents(EventHandlers *handler, const Uint32 ticks);
93 static bool Draw(const NKWindowConfig cfg);
94 void NKWindow(NKWindowConfig cfg)
95 {
96 CASSERT(cfg.win, "Error: did not initialise window");
97 CASSERT(cfg.ctx, "Error: did not initialise NK context");
98 EventReset(cfg.Handlers);
99 MouseSetCursor(&cfg.Handlers->mouse, SDL_SYSTEM_CURSOR_ARROW);
100 if (SDL_SetWindowModalFor(cfg.win, gGraphicsDevice.gameWindow.window) != 0)
101 {
102 LOG(LM_EDIT, LL_ERROR, "Failed to set modal parent: %s",
103 SDL_GetError());
104 }
105 Uint32 ticksNow = SDL_GetTicks();
106 Uint32 ticksElapsed = 0;
107 for (;;)
108 {
109 Uint32 ticksThen = ticksNow;
110 ticksNow = SDL_GetTicks();
111 ticksElapsed += ticksNow - ticksThen;
112 if (ticksElapsed < 1000 / FPS_FRAMELIMIT)
113 {
114 SDL_Delay(1);
115 continue;
116 }
117
118 // Note: drawing contains input processing too
119 nk_input_begin(cfg.ctx);
120 if (!HandleEvents(cfg.Handlers, ticksNow))
121 {
122 goto bail;
123 }
124 if (!Draw(cfg))
125 {
126 goto bail;
127 }
128 nk_input_end(cfg.ctx);
129
130 ticksElapsed = 0;
131 }
132
133 bail:
134 nk_sdl_shutdown();
135 SDL_GL_DeleteContext(cfg.glContext);
136 SDL_DestroyWindow(cfg.win);
137 }
138 static bool HandleEvents(EventHandlers *handler, const Uint32 ticks)
139 {
140 EventPoll(handler, ticks, nk_sdl_handle_event);
141 bool run = !handler->HasQuit;
142 const SDL_Scancode sc = KeyGetPressed(&handler->keyboard);
143 if (sc == SDL_SCANCODE_ESCAPE)
144 {
145 run = false;
146 }
147 // Capture quit event; don't allow main window to quit
148 handler->HasQuit = false;
149 return run;
150 }
151 static bool Draw(const NKWindowConfig cfg)
152 {
153 if (!cfg.Draw(cfg.win, cfg.ctx, cfg.DrawData))
154 {
155 return false;
156 }
157
158 int winWidth, winHeight;
159 SDL_GetWindowSize(cfg.win, &winWidth, &winHeight);
160 glViewport(0, 0, winWidth, winHeight);
161 glClear(GL_COLOR_BUFFER_BIT);
162 glClearColor(
163 cfg.BG.r / 255.0f, cfg.BG.g / 255.0f, cfg.BG.b / 255.0f,
164 cfg.BG.a / 255.0f);
165
166 nk_sdl_render(NK_ANTI_ALIASING_ON);
167 SDL_GL_SwapWindow(cfg.win);
168
169 return true;
170 }
171
172 static void BeforeDrawTex(const GLuint texid);
173
174 // Custom controls
175 int nk_combo_separator_image(
176 struct nk_context *ctx, const GLuint *img_ids,
177 const char *items_separated_by_separator, int separator, int selected,
178 int count, int item_height, struct nk_vec2 size)
179 {
180 int i;
181 int max_height;
182 struct nk_vec2 item_spacing;
183 struct nk_vec2 window_padding;
184 const char *current_item;
185 const char *iter;
186 int length = 0;
187
188 NK_ASSERT(ctx);
189 NK_ASSERT(items_separated_by_separator);
190 if (!ctx || !items_separated_by_separator)
191 return selected;
192
193 /* calculate popup window */
194 item_spacing = ctx->style.window.spacing;
195 window_padding =
196 nk_panel_get_padding(&ctx->style, ctx->current->layout->type);
197 max_height = count * item_height + count * (int)item_spacing.y;
198 max_height += (int)item_spacing.y * 2 + (int)window_padding.y * 2;
199 size.y = NK_MIN(size.y, (float)max_height);
200
201 /* find selected item */
202 current_item = items_separated_by_separator;
203 for (i = 0; i < count; ++i)
204 {
205 iter = current_item;
206 while (*iter && *iter != separator)
207 iter++;
208 length = (int)(iter - current_item);
209 if (i == selected)
210 break;
211 current_item = iter + 1;
212 }
213
214 // Get widget bounds for drawing currently selected item image later
215 struct nk_rect bounds;
216 nk_layout_widget_space(&bounds, ctx, ctx->current, nk_false);
217 bounds.x += size.x - 56;
218 bounds.y += 2;
219 bounds.w = (float)12 * PIC_SCALE;
220 bounds.h = (float)12 * PIC_SCALE;
221
222 if (nk_combo_begin_text(ctx, current_item, length, size))
223 {
224 current_item = items_separated_by_separator;
225 nk_layout_row_dynamic(ctx, (float)item_height, 1);
226 for (i = 0; i < count; ++i)
227 {
228 const struct nk_image img = nk_image_id(img_ids[i]);
229 // TODO: image size
230 BeforeDrawTex(img_ids[i]);
231 iter = current_item;
232 while (*iter && *iter != separator)
233 iter++;
234 length = (int)(iter - current_item);
235 if (nk_contextual_item_image_text(
236 ctx, img, current_item, length, NK_TEXT_LEFT))
237 selected = i;
238 current_item = current_item + length + 1;
239 }
240 nk_combo_end(ctx);
241 }
242
243 // Also draw currently selected image
244 if (img_ids != NULL)
245 {
246 const struct nk_image comboImg = nk_image_id(img_ids[selected]);
247 BeforeDrawTex(img_ids[selected]);
248 nk_draw_image(&ctx->current->buffer, bounds, &comboImg, nk_white);
249 }
250
251 return selected;
252 }
253
254 static Pic PadEven(const Pic *pic);
255 void LoadTexFromPic(const GLuint texid, const Pic *pic)
256 {
257 if (pic == NULL)
258 {
259 return;
260 }
261 glBindTexture(GL_TEXTURE_2D, texid);
262 Pic padded = PadEven(pic);
263 glTexImage2D(
264 GL_TEXTURE_2D, 0, GL_RGBA, padded.size.x, padded.size.y, 0, GL_BGRA,
265 GL_UNSIGNED_BYTE, padded.Data);
266 PicFree(&padded);
267 glBindTexture(GL_TEXTURE_2D, 0);
268 }
269 static Pic PadEven(const Pic *pic)
270 {
271 // OGL needs even dimensions for texture
272 Pic p;
273 memset(&p, 0, sizeof p);
274 p.size = svec2i((pic->size.x + 1) / 2 * 2, (pic->size.y + 1) / 2 * 2);
275 CASSERT(p.size.x > 0 && p.size.y > 0, "invalid pic size");
276 CCALLOC(p.Data, p.size.x * p.size.y * sizeof *((Pic *)0)->Data);
277 for (int i = 0; i < pic->size.y; i++)
278 {
279 memcpy(
280 p.Data + i * p.size.x, pic->Data + i * pic->size.x,
281 pic->size.x * sizeof *p.Data);
282 }
283 return p;
284 }
285
286 bool DrawCheckbox(
287 struct nk_context *ctx, const char *label, const char *tooltip,
288 bool *value)
289 {
290 int iValue = (int)*value;
291 const bool changed = nk_checkbox_label(ctx, label, &iValue);
292 *value = (bool)iValue;
293 if (tooltip && nk_widget_is_hovered(ctx))
294 {
295 nk_tooltip(ctx, tooltip);
296 }
297 return changed;
298 }
299
300 bool DrawNumberSlider(
301 struct nk_context *ctx, const char *label, const char *tooltip,
302 const int min, const int max, const int step, int *value)
303 {
304 const int origValue = *value;
305 nk_property_int(ctx, label, min, value, max, step, 1.0f);
306 if (tooltip && nk_widget_is_hovered(ctx))
307 {
308 nk_tooltip(ctx, tooltip);
309 }
310 return origValue != *value;
311 }
312
313 void DrawPic(
314 struct nk_context *ctx, const Pic *pic, const GLuint texid,
315 const struct vec2i pos, const float scale)
316 {
317 if (pic != NULL)
318 {
319 LoadTexFromPic(texid, pic);
320 }
321 struct nk_image tex = nk_image_id((int)texid);
322 BeforeDrawTex(texid);
323 struct nk_rect bounds;
324 nk_layout_widget_space(&bounds, ctx, ctx->current, nk_true);
325 bounds.x += pos.x * scale;
326 bounds.y += pos.y * scale;
327 if (pic != NULL)
328 {
329 bounds.w = pic->size.x * scale;
330 bounds.h = pic->size.y * scale;
331 }
332 else
333 {
334 bounds.w = 0;
335 bounds.h = 0;
336 }
337 nk_draw_image(&ctx->current->buffer, bounds, &tex, nk_white);
338 }
339
340 void DrawTextbox(
341 struct nk_context *ctx, char *value, const int len, const char *tooltip,
342 const nk_flags flags)
343 {
344 nk_edit_string_zero_terminated(ctx, flags, value, len, nk_filter_default);
345 if (tooltip && nk_widget_is_hovered(ctx))
346 {
347 nk_tooltip(ctx, tooltip);
348 }
349 }
350
351 bool ColorPicker(
352 struct nk_context *ctx, const float height, const char *label, color_t *c)
353 {
354 bool changed = false;
355 nk_label(ctx, label, NK_TEXT_LEFT);
356 struct nk_color color = {c->r, c->g, c->b, 255};
357 const struct nk_color colorOriginal = color;
358 if (nk_combo_begin_color(ctx, color, nk_vec2(nk_widget_width(ctx), 400)))
359 {
360 nk_layout_row_dynamic(ctx, 110, 1);
361 struct nk_colorf colorf = nk_color_cf(color);
362 colorf = nk_color_picker(ctx, colorf, NK_RGB);
363 color = nk_rgb_cf(colorf);
364 nk_layout_row_dynamic(ctx, height, 1);
365 color.r = (nk_byte)nk_propertyi(ctx, "#R:", 0, color.r, 255, 1, 1);
366 color.g = (nk_byte)nk_propertyi(ctx, "#G:", 0, color.g, 255, 1, 1);
367 color.b = (nk_byte)nk_propertyi(ctx, "#B:", 0, color.b, 255, 1, 1);
368 nk_combo_end(ctx);
369 c->r = color.r;
370 c->g = color.g;
371 c->b = color.b;
372 if (memcmp(&color, &colorOriginal, sizeof color))
373 {
374 changed = true;
375 }
376 }
377 return changed;
378 }
379
380 static void BeforeDrawTex(const GLuint texid)
381 {
382 glBindTexture(GL_TEXTURE_2D, texid);
383 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
384 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
385 }
386
387 void PickupClassDrawPropsSidebar(
388 struct nk_context *ctx, const PickupClass *pc, const float rh)
389 {
390 nk_layout_row_dynamic(ctx, rh, 1);
391
392 char buf[256];
393
394 nk_label(ctx, pc->Name, NK_TEXT_LEFT);
395
396 CA_FOREACH(const PickupEffect, pe, pc->Effects)
397 nk_spacing(ctx, 1);
398 sprintf(buf, "Type: %s", PickupTypeStr(pe->Type));
399 nk_label(ctx, buf, NK_TEXT_LEFT);
400 switch (pe->Type)
401 {
402 case PICKUP_JEWEL:
403 sprintf(buf, "Score: %d", pe->u.Score);
404 nk_label(ctx, buf, NK_TEXT_LEFT);
405 break;
406 case PICKUP_HEALTH:
407 sprintf(buf, "Health: %d%s", pe->u.Heal.Amount, pe->u.Heal.ExceedMax ? " (exceed max)" : "");
408 nk_label(ctx, buf, NK_TEXT_LEFT);
409 break;
410 case PICKUP_AMMO: {
411 const Ammo *a = AmmoGetById(&gAmmo, pe->u.Ammo.Id);
412 sprintf(buf, "Ammo: %s", a->Name);
413 nk_label(ctx, buf, NK_TEXT_LEFT);
414 sprintf(buf, "Amount: %d", (int)pe->u.Ammo.Amount);
415 nk_label(ctx, buf, NK_TEXT_LEFT);
416 }
417 break;
418 case PICKUP_KEYCARD:
419 sprintf(buf, "Key: %s", KeycardStr(pe->u.Keys));
420 nk_label(ctx, buf, NK_TEXT_LEFT);
421 break;
422 case PICKUP_GUN: {
423 const WeaponClass *wc = IdWeaponClass(pe->u.GunId);
424 sprintf(buf, "Weapon: %s", wc->name);
425 nk_label(ctx, buf, NK_TEXT_LEFT);
426 }
427 case PICKUP_SHOW_MAP:
428 break;
429 case PICKUP_LIVES:
430 sprintf(buf, "Lives: %d", pe->u.Lives);
431 nk_label(ctx, buf, NK_TEXT_LEFT);
432 break;
433 default:
434 CASSERT(false, "Unknown pickup type");
435 break;
436 }
437 CA_FOREACH_END()
438 }