From d4e695420d1e613e9dd9560a0c0f5c22bcedf614 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ludwig=20F=C3=BCchsl?= Date: Fri, 25 Feb 2022 11:13:01 +0100 Subject: [PATCH 001/106] Added GDI full featured window code --- demo/gdi_native_nuklear/build.bat | 6 + demo/gdi_native_nuklear/main.cpp | 37 + demo/gdi_native_nuklear/nuklear_gdi.h | 932 ++++++++++++++++++++++++++ demo/gdi_native_nuklear/window.h | 377 +++++++++++ 4 files changed, 1352 insertions(+) create mode 100644 demo/gdi_native_nuklear/build.bat create mode 100644 demo/gdi_native_nuklear/main.cpp create mode 100644 demo/gdi_native_nuklear/nuklear_gdi.h create mode 100644 demo/gdi_native_nuklear/window.h diff --git a/demo/gdi_native_nuklear/build.bat b/demo/gdi_native_nuklear/build.bat new file mode 100644 index 0000000..65a8ce6 --- /dev/null +++ b/demo/gdi_native_nuklear/build.bat @@ -0,0 +1,6 @@ +@echo off + +rem This will use VS2015 for compiler +call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x86 + +cl /nologo /W3 /O2 /fp:fast /Gm- /D_CRT_SECURE_NO_DEPRECATE /Fedemo.exe main.cpp user32.lib gdi32.lib Msimg32.lib /link /incremental:no diff --git a/demo/gdi_native_nuklear/main.cpp b/demo/gdi_native_nuklear/main.cpp new file mode 100644 index 0000000..000ea2a --- /dev/null +++ b/demo/gdi_native_nuklear/main.cpp @@ -0,0 +1,37 @@ +#include +#include + +#pragma comment(linker,"\"/manifestdependency:type='win32' \ +name='Microsoft.Windows.Common-Controls' version='6.0.0.0' \ +processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") + +#define NK_INCLUDE_FIXED_TYPES +#define NK_INCLUDE_STANDARD_IO +#define NK_INCLUDE_STANDARD_VARARGS +#define NK_INCLUDE_DEFAULT_ALLOCATOR +#define NK_IMPLEMENTATION +#define NK_GDI_IMPLEMENTATION +#include "../../nuklear.h" +#include "nuklear_gdi.h" + +#define NKGDI_IMPLEMENT_WINDOW +#include "window.h" + +INT WINAPI wWinMain(HINSTANCE _In_ hInstance, HINSTANCE _In_opt_ hPrevInstance, PWSTR _In_ cmdArgs, INT _In_ cmdShow) +{ + NkGdi::Window w1(500, 500, "F1", 10, 10); + w1.AllowSizing = false; + w1.AllowMaximize = false; + w1.AllowMove = false; + w1.HasTitlebar = false; + + NkGdi::Window w2(500, 500, "F2", 520, 10); + w2.AllowSizing = true; + w2.AllowMaximize = true; + w2.AllowMove = true; + w2.HasTitlebar = true; + + while (w1.Update() && w2.Update()) Sleep(20); + + return 0; +} diff --git a/demo/gdi_native_nuklear/nuklear_gdi.h b/demo/gdi_native_nuklear/nuklear_gdi.h new file mode 100644 index 0000000..aef6452 --- /dev/null +++ b/demo/gdi_native_nuklear/nuklear_gdi.h @@ -0,0 +1,932 @@ +/* + * Nuklear - 1.32.0 - public domain + * no warrenty implied; use at your own risk. + * authored from 2015-2016 by Micha Mettke + */ + /* + * ============================================================== + * + * API + * + * =============================================================== + */ +#ifndef NK_GDI_H_ +#define NK_GDI_H_ + +#ifdef __cplusplus +extern "C"{ +#endif + +typedef struct GdiFont GdiFont; +struct _nk_gdi_ctx; +typedef struct _nk_gdi_ctx* nk_gdi_ctx; + +NK_API struct nk_context* nk_gdi_init(nk_gdi_ctx* gdi, GdiFont* font, HDC window_dc, unsigned int width, unsigned int height); +NK_API int nk_gdi_handle_event(nk_gdi_ctx gdi, HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam); +NK_API void nk_gdi_render(nk_gdi_ctx gdi, struct nk_color clear); +NK_API void nk_gdi_shutdown(nk_gdi_ctx gdi); + +/* font */ +NK_API GdiFont* nk_gdifont_create(const char* name, int size); +NK_API void nk_gdifont_del(GdiFont* font); +NK_API void nk_gdi_set_font(nk_gdi_ctx gdi, GdiFont* font); + +#ifdef __cplusplus +} +#endif + +#endif + +/* + * ============================================================== + * + * IMPLEMENTATION + * + * =============================================================== + */ +#ifdef NK_GDI_IMPLEMENTATION + +#include +#include + +struct GdiFont { + struct nk_user_font nk; + int height; + HFONT handle; + HDC dc; +}; + +struct _nk_gdi_ctx { + HBITMAP bitmap; + HDC window_dc; + HDC memory_dc; + unsigned int width; + unsigned int height; + struct nk_context ctx; +}; + +static void +nk_create_image(struct nk_image* image, const char* frame_buffer, const int width, const int height) +{ + if (image && frame_buffer && (width > 0) && (height > 0)) + { + const unsigned char* src = (const unsigned char*)frame_buffer; + INT row = ((width * 3 + 3) & ~3); + LPBYTE lpBuf, pb = NULL; + BITMAPINFO bi = { 0 }; + HBITMAP hbm; + int v, i; + + image->w = width; + image->h = height; + image->region[0] = 0; + image->region[1] = 0; + image->region[2] = width; + image->region[3] = height; + + bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); + bi.bmiHeader.biWidth = width; + bi.bmiHeader.biHeight = height; + bi.bmiHeader.biPlanes = 1; + bi.bmiHeader.biBitCount = 24; + bi.bmiHeader.biCompression = BI_RGB; + bi.bmiHeader.biSizeImage = row * height; + + hbm = CreateDIBSection(NULL, &bi, DIB_RGB_COLORS, (void**)&lpBuf, NULL, 0); + + pb = lpBuf + row * height; + for (v = 0; v < height; v++) + { + pb -= row; + for (i = 0; i < row; i += 3) + { + pb[i + 0] = src[0]; + pb[i + 1] = src[1]; + pb[i + 2] = src[2]; + src += 3; + } + } + SetDIBits(NULL, hbm, 0, height, lpBuf, &bi, DIB_RGB_COLORS); + image->handle.ptr = hbm; + } +} + +static void +nk_delete_image(struct nk_image* image) +{ + if (image && image->handle.id != 0) + { + HBITMAP hbm = (HBITMAP)image->handle.ptr; + DeleteObject(hbm); + memset(image, 0, sizeof(struct nk_image)); + } +} + +static void +nk_gdi_draw_image(nk_gdi_ctx gdi, short x, short y, unsigned short w, unsigned short h, + struct nk_image img, struct nk_color col) +{ + HBITMAP hbm = (HBITMAP)img.handle.ptr; + HDC hDCBits; + BITMAP bitmap; + + if (!gdi->memory_dc || !hbm) + return; + + hDCBits = CreateCompatibleDC(gdi->memory_dc); + GetObject(hbm, sizeof(BITMAP), (LPSTR)&bitmap); + SelectObject(hDCBits, hbm); + StretchBlt(gdi->memory_dc, x, y, w, h, hDCBits, 0, 0, bitmap.bmWidth, bitmap.bmHeight, SRCCOPY); + DeleteDC(hDCBits); +} + +static COLORREF +convert_color(struct nk_color c) +{ + return c.r | (c.g << 8) | (c.b << 16); +} + +static void +nk_gdi_scissor(HDC dc, float x, float y, float w, float h) +{ + SelectClipRgn(dc, NULL); + IntersectClipRect(dc, (int)x, (int)y, (int)(x + w + 1), (int)(y + h + 1)); +} + +static void +nk_gdi_stroke_line(HDC dc, short x0, short y0, short x1, + short y1, unsigned int line_thickness, struct nk_color col) +{ + COLORREF color = convert_color(col); + + HPEN pen = NULL; + if (line_thickness == 1) { + SetDCPenColor(dc, color); + } + else { + pen = CreatePen(PS_SOLID, line_thickness, color); + SelectObject(dc, pen); + } + + MoveToEx(dc, x0, y0, NULL); + LineTo(dc, x1, y1); + + if (pen) { + SelectObject(dc, GetStockObject(DC_PEN)); + DeleteObject(pen); + } +} + +static void +nk_gdi_stroke_rect(HDC dc, short x, short y, unsigned short w, + unsigned short h, unsigned short r, unsigned short line_thickness, struct nk_color col) +{ + COLORREF color = convert_color(col); + HGDIOBJ br; + HPEN pen = NULL; + + if (line_thickness == 1) { + SetDCPenColor(dc, color); + } + else { + pen = CreatePen(PS_SOLID, line_thickness, color); + SelectObject(dc, pen); + } + + br = SelectObject(dc, GetStockObject(NULL_BRUSH)); + if (r == 0) { + Rectangle(dc, x, y, x + w, y + h); + } + else { + RoundRect(dc, x, y, x + w, y + h, r, r); + } + SelectObject(dc, br); + + if (pen) { + SelectObject(dc, GetStockObject(DC_PEN)); + DeleteObject(pen); + } +} + +static void +nk_gdi_fill_rect(HDC dc, short x, short y, unsigned short w, + unsigned short h, unsigned short r, struct nk_color col) +{ + COLORREF color = convert_color(col); + + if (r == 0) { + RECT rect; + SetRect(&rect, x, y, x + w, y + h); + SetBkColor(dc, color); + ExtTextOutW(dc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL); + } + else { + SetDCPenColor(dc, color); + SetDCBrushColor(dc, color); + RoundRect(dc, x, y, x + w, y + h, r, r); + } +} +static void +nk_gdi_set_vertexColor(PTRIVERTEX tri, struct nk_color col) +{ + tri->Red = col.r << 8; + tri->Green = col.g << 8; + tri->Blue = col.b << 8; + tri->Alpha = 0xff << 8; +} + +static void +nk_gdi_rect_multi_color(nk_gdi_ctx gdi, HDC dc, short x, short y, unsigned short w, + unsigned short h, struct nk_color left, struct nk_color top, + struct nk_color right, struct nk_color bottom) +{ + BLENDFUNCTION alphaFunction; + // GRADIENT_RECT gRect; + GRADIENT_TRIANGLE gTri[2]; + TRIVERTEX vt[4]; + alphaFunction.BlendOp = AC_SRC_OVER; + alphaFunction.BlendFlags = 0; + alphaFunction.SourceConstantAlpha = 0; + alphaFunction.AlphaFormat = AC_SRC_ALPHA; + + /* TODO: This Case Needs Repair.*/ + /* Top Left Corner */ + vt[0].x = x; + vt[0].y = y; + nk_gdi_set_vertexColor(&vt[0], left); + /* Top Right Corner */ + vt[1].x = x + w; + vt[1].y = y; + nk_gdi_set_vertexColor(&vt[1], top); + /* Bottom Left Corner */ + vt[2].x = x; + vt[2].y = y + h; + nk_gdi_set_vertexColor(&vt[2], right); + + /* Bottom Right Corner */ + vt[3].x = x + w; + vt[3].y = y + h; + nk_gdi_set_vertexColor(&vt[3], bottom); + + gTri[0].Vertex1 = 0; + gTri[0].Vertex2 = 1; + gTri[0].Vertex3 = 2; + gTri[1].Vertex1 = 2; + gTri[1].Vertex2 = 1; + gTri[1].Vertex3 = 3; + GdiGradientFill(dc, vt, 4, gTri, 2, GRADIENT_FILL_TRIANGLE); + AlphaBlend(gdi->window_dc, x, y, x + w, y + h, gdi->memory_dc, x, y, x + w, y + h, alphaFunction); + +} + +static BOOL +SetPoint(POINT* p, LONG x, LONG y) +{ + if (!p) + return FALSE; + p->x = x; + p->y = y; + return TRUE; +} + +static void +nk_gdi_fill_triangle(HDC dc, short x0, short y0, short x1, + short y1, short x2, short y2, struct nk_color col) +{ + COLORREF color = convert_color(col); + POINT points[3]; + + SetPoint(&points[0], x0, y0); + SetPoint(&points[1], x1, y1); + SetPoint(&points[2], x2, y2); + + SetDCPenColor(dc, color); + SetDCBrushColor(dc, color); + Polygon(dc, points, 3); +} + +static void +nk_gdi_stroke_triangle(HDC dc, short x0, short y0, short x1, + short y1, short x2, short y2, unsigned short line_thickness, struct nk_color col) +{ + COLORREF color = convert_color(col); + POINT points[4]; + HPEN pen = NULL; + + SetPoint(&points[0], x0, y0); + SetPoint(&points[1], x1, y1); + SetPoint(&points[2], x2, y2); + SetPoint(&points[3], x0, y0); + + if (line_thickness == 1) { + SetDCPenColor(dc, color); + } + else { + pen = CreatePen(PS_SOLID, line_thickness, color); + SelectObject(dc, pen); + } + + Polyline(dc, points, 4); + + if (pen) { + SelectObject(dc, GetStockObject(DC_PEN)); + DeleteObject(pen); + } +} + +static void +nk_gdi_fill_polygon(HDC dc, const struct nk_vec2i* pnts, int count, struct nk_color col) +{ + int i = 0; +#define MAX_POINTS 64 + POINT points[MAX_POINTS]; + COLORREF color = convert_color(col); + SetDCBrushColor(dc, color); + SetDCPenColor(dc, color); + for (i = 0; i < count && i < MAX_POINTS; ++i) { + points[i].x = pnts[i].x; + points[i].y = pnts[i].y; + } + Polygon(dc, points, i); +#undef MAX_POINTS +} + +static void +nk_gdi_stroke_polygon(HDC dc, const struct nk_vec2i* pnts, int count, + unsigned short line_thickness, struct nk_color col) +{ + COLORREF color = convert_color(col); + HPEN pen = NULL; + if (line_thickness == 1) { + SetDCPenColor(dc, color); + } + else { + pen = CreatePen(PS_SOLID, line_thickness, color); + SelectObject(dc, pen); + } + + if (count > 0) { + int i; + MoveToEx(dc, pnts[0].x, pnts[0].y, NULL); + for (i = 1; i < count; ++i) + LineTo(dc, pnts[i].x, pnts[i].y); + LineTo(dc, pnts[0].x, pnts[0].y); + } + + if (pen) { + SelectObject(dc, GetStockObject(DC_PEN)); + DeleteObject(pen); + } +} + +static void +nk_gdi_stroke_polyline(HDC dc, const struct nk_vec2i* pnts, + int count, unsigned short line_thickness, struct nk_color col) +{ + COLORREF color = convert_color(col); + HPEN pen = NULL; + if (line_thickness == 1) { + SetDCPenColor(dc, color); + } + else { + pen = CreatePen(PS_SOLID, line_thickness, color); + SelectObject(dc, pen); + } + + if (count > 0) { + int i; + MoveToEx(dc, pnts[0].x, pnts[0].y, NULL); + for (i = 1; i < count; ++i) + LineTo(dc, pnts[i].x, pnts[i].y); + } + + if (pen) { + SelectObject(dc, GetStockObject(DC_PEN)); + DeleteObject(pen); + } +} + +static void +nk_gdi_fill_circle(HDC dc, short x, short y, unsigned short w, + unsigned short h, struct nk_color col) +{ + COLORREF color = convert_color(col); + SetDCBrushColor(dc, color); + SetDCPenColor(dc, color); + Ellipse(dc, x, y, x + w, y + h); +} + +static void +nk_gdi_stroke_circle(HDC dc, short x, short y, unsigned short w, + unsigned short h, unsigned short line_thickness, struct nk_color col) +{ + COLORREF color = convert_color(col); + HPEN pen = NULL; + if (line_thickness == 1) { + SetDCPenColor(dc, color); + } + else { + pen = CreatePen(PS_SOLID, line_thickness, color); + SelectObject(dc, pen); + } + + SetDCBrushColor(dc, OPAQUE); + Ellipse(dc, x, y, x + w, y + h); + + if (pen) { + SelectObject(dc, GetStockObject(DC_PEN)); + DeleteObject(pen); + } +} + +static void +nk_gdi_stroke_curve(HDC dc, struct nk_vec2i p1, + struct nk_vec2i p2, struct nk_vec2i p3, struct nk_vec2i p4, + unsigned short line_thickness, struct nk_color col) +{ + COLORREF color = convert_color(col); + POINT p[4]; + HPEN pen = NULL; + + SetPoint(&p[0], p1.x, p1.y); + SetPoint(&p[1], p2.x, p2.y); + SetPoint(&p[2], p3.x, p3.y); + SetPoint(&p[3], p4.x, p4.y); + + if (line_thickness == 1) { + SetDCPenColor(dc, color); + } + else { + pen = CreatePen(PS_SOLID, line_thickness, color); + SelectObject(dc, pen); + } + + SetDCBrushColor(dc, OPAQUE); + PolyBezier(dc, p, 4); + + if (pen) { + SelectObject(dc, GetStockObject(DC_PEN)); + DeleteObject(pen); + } +} + +static void +nk_gdi_draw_text(HDC dc, short x, short y, unsigned short w, unsigned short h, + const char* text, int len, GdiFont* font, struct nk_color cbg, struct nk_color cfg) +{ + int wsize; + WCHAR* wstr; + + if (!text || !font || !len) return; + + wsize = MultiByteToWideChar(CP_UTF8, 0, text, len, NULL, 0); + wstr = (WCHAR*)_alloca(wsize * sizeof(wchar_t)); + MultiByteToWideChar(CP_UTF8, 0, text, len, wstr, wsize); + + SetBkColor(dc, convert_color(cbg)); + SetTextColor(dc, convert_color(cfg)); + + SelectObject(dc, font->handle); + ExtTextOutW(dc, x, y, ETO_OPAQUE, NULL, wstr, wsize, NULL); +} + +static void +nk_gdi_clear(nk_gdi_ctx gdi, HDC dc, struct nk_color col) +{ + COLORREF color = convert_color(col); + RECT rect; + SetRect(&rect, 0, 0, gdi->width, gdi->height); + SetBkColor(dc, color); + + ExtTextOutW(dc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL); +} + +static void +nk_gdi_blit(nk_gdi_ctx gdi, HDC dc) +{ + BitBlt(dc, 0, 0, gdi->width, gdi->height, gdi->memory_dc, 0, 0, SRCCOPY); + +} + +GdiFont* +nk_gdifont_create(const char* name, int size) +{ + TEXTMETRICW metric; + GdiFont* font = (GdiFont*)calloc(1, sizeof(GdiFont)); + if (!font) + return NULL; + font->dc = CreateCompatibleDC(0); + font->handle = CreateFontA(size, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_DONTCARE, name); + SelectObject(font->dc, font->handle); + GetTextMetricsW(font->dc, &metric); + font->height = metric.tmHeight; + return font; +} + +static float +nk_gdifont_get_text_width(nk_handle handle, float height, const char* text, int len) +{ + GdiFont* font = (GdiFont*)handle.ptr; + SIZE size; + int wsize; + WCHAR* wstr; + if (!font || !text) + return 0; + + wsize = MultiByteToWideChar(CP_UTF8, 0, text, len, NULL, 0); + wstr = (WCHAR*)_alloca(wsize * sizeof(wchar_t)); + MultiByteToWideChar(CP_UTF8, 0, text, len, wstr, wsize); + if (GetTextExtentPoint32W(font->dc, wstr, wsize, &size)) + return (float)size.cx; + return -1.0f; +} + +void +nk_gdifont_del(GdiFont* font) +{ + if (!font) return; + DeleteObject(font->handle); + DeleteDC(font->dc); + free(font); +} + +static void +nk_gdi_clipboard_paste(nk_handle usr, struct nk_text_edit* edit) +{ + (void)usr; + if (IsClipboardFormatAvailable(CF_UNICODETEXT) && OpenClipboard(NULL)) + { + HGLOBAL mem = GetClipboardData(CF_UNICODETEXT); + if (mem) + { + SIZE_T size = GlobalSize(mem) - 1; + if (size) + { + LPCWSTR wstr = (LPCWSTR)GlobalLock(mem); + if (wstr) + { + int utf8size = WideCharToMultiByte(CP_UTF8, 0, wstr, (int)(size / sizeof(wchar_t)), NULL, 0, NULL, NULL); + if (utf8size) + { + char* utf8 = (char*)malloc(utf8size); + if (utf8) + { + WideCharToMultiByte(CP_UTF8, 0, wstr, (int)(size / sizeof(wchar_t)), utf8, utf8size, NULL, NULL); + nk_textedit_paste(edit, utf8, utf8size); + free(utf8); + } + } + GlobalUnlock(mem); + } + } + } + CloseClipboard(); + } +} + +static void +nk_gdi_clipboard_copy(nk_handle usr, const char* text, int len) +{ + if (OpenClipboard(NULL)) + { + int wsize = MultiByteToWideChar(CP_UTF8, 0, text, len, NULL, 0); + if (wsize) + { + HGLOBAL mem = (HGLOBAL)GlobalAlloc(GMEM_MOVEABLE, (wsize + 1) * sizeof(wchar_t)); + if (mem) + { + wchar_t* wstr = (wchar_t*)GlobalLock(mem); + if (wstr) + { + MultiByteToWideChar(CP_UTF8, 0, text, len, wstr, wsize); + wstr[wsize] = 0; + GlobalUnlock(mem); + + SetClipboardData(CF_UNICODETEXT, mem); + } + } + } + CloseClipboard(); + } +} + +NK_API struct nk_context* +nk_gdi_init(nk_gdi_ctx* gdi, GdiFont* gdifont, HDC window_dc, unsigned int width, unsigned int height) +{ + *gdi = (nk_gdi_ctx)malloc(sizeof(struct _nk_gdi_ctx)); + + struct nk_user_font* font = &gdifont->nk; + font->userdata = nk_handle_ptr(gdifont); + font->height = (float)gdifont->height; + font->width = nk_gdifont_get_text_width; + + (*gdi)->bitmap = CreateCompatibleBitmap(window_dc, width, height); + (*gdi)->window_dc = window_dc; + (*gdi)->memory_dc = CreateCompatibleDC(window_dc); + (*gdi)->width = width; + (*gdi)->height = height; + SelectObject((*gdi)->memory_dc, (*gdi)->bitmap); + + nk_init_default(&(*gdi)->ctx, font); + (*gdi)->ctx.clip.copy = nk_gdi_clipboard_copy; + (*gdi)->ctx.clip.paste = nk_gdi_clipboard_paste; + return &(*gdi)->ctx; +} + +NK_API void +nk_gdi_set_font(nk_gdi_ctx gdi, GdiFont* gdifont) +{ + struct nk_user_font* font = &gdifont->nk; + font->userdata = nk_handle_ptr(gdifont); + font->height = (float)gdifont->height; + font->width = nk_gdifont_get_text_width; + nk_style_set_font(&gdi->ctx, font); +} + +NK_API int +nk_gdi_handle_event(nk_gdi_ctx gdi, HWND wnd, UINT msg, WPARAM wparam, LPARAM lparam) +{ + switch (msg) + { + case WM_SIZE: + { + unsigned width = LOWORD(lparam); + unsigned height = HIWORD(lparam); + if (width != gdi->width || height != gdi->height) + { + DeleteObject(gdi->bitmap); + gdi->bitmap = CreateCompatibleBitmap(gdi->window_dc, width, height); + gdi->width = width; + gdi->height = height; + SelectObject(gdi->memory_dc, gdi->bitmap); + } + break; + } + + case WM_PAINT: + { + PAINTSTRUCT paint; + HDC dc = BeginPaint(wnd, &paint); + nk_gdi_blit(gdi, dc); + EndPaint(wnd, &paint); + return 1; + } + + case WM_KEYDOWN: + case WM_KEYUP: + case WM_SYSKEYDOWN: + case WM_SYSKEYUP: + { + int down = !((lparam >> 31) & 1); + int ctrl = GetKeyState(VK_CONTROL) & (1 << 15); + + switch (wparam) + { + case VK_SHIFT: + case VK_LSHIFT: + case VK_RSHIFT: + nk_input_key(&gdi->ctx, NK_KEY_SHIFT, down); + return 1; + + case VK_DELETE: + nk_input_key(&gdi->ctx, NK_KEY_DEL, down); + return 1; + + case VK_RETURN: + nk_input_key(&gdi->ctx, NK_KEY_ENTER, down); + return 1; + + case VK_TAB: + nk_input_key(&gdi->ctx, NK_KEY_TAB, down); + return 1; + + case VK_LEFT: + if (ctrl) + nk_input_key(&gdi->ctx, NK_KEY_TEXT_WORD_LEFT, down); + else + nk_input_key(&gdi->ctx, NK_KEY_LEFT, down); + return 1; + + case VK_RIGHT: + if (ctrl) + nk_input_key(&gdi->ctx, NK_KEY_TEXT_WORD_RIGHT, down); + else + nk_input_key(&gdi->ctx, NK_KEY_RIGHT, down); + return 1; + + case VK_BACK: + nk_input_key(&gdi->ctx, NK_KEY_BACKSPACE, down); + return 1; + + case VK_HOME: + nk_input_key(&gdi->ctx, NK_KEY_TEXT_START, down); + nk_input_key(&gdi->ctx, NK_KEY_SCROLL_START, down); + return 1; + + case VK_END: + nk_input_key(&gdi->ctx, NK_KEY_TEXT_END, down); + nk_input_key(&gdi->ctx, NK_KEY_SCROLL_END, down); + return 1; + + case VK_NEXT: + nk_input_key(&gdi->ctx, NK_KEY_SCROLL_DOWN, down); + return 1; + + case VK_PRIOR: + nk_input_key(&gdi->ctx, NK_KEY_SCROLL_UP, down); + return 1; + + case 'C': + if (ctrl) { + nk_input_key(&gdi->ctx, NK_KEY_COPY, down); + return 1; + } + break; + + case 'V': + if (ctrl) { + nk_input_key(&gdi->ctx, NK_KEY_PASTE, down); + return 1; + } + break; + + case 'X': + if (ctrl) { + nk_input_key(&gdi->ctx, NK_KEY_CUT, down); + return 1; + } + break; + + case 'Z': + if (ctrl) { + nk_input_key(&gdi->ctx, NK_KEY_TEXT_UNDO, down); + return 1; + } + break; + + case 'R': + if (ctrl) { + nk_input_key(&gdi->ctx, NK_KEY_TEXT_REDO, down); + return 1; + } + break; + } + return 0; + } + + case WM_CHAR: + if (wparam >= 32) + { + nk_input_unicode(&gdi->ctx, (nk_rune)wparam); + return 1; + } + break; + + case WM_LBUTTONDOWN: + nk_input_button(&gdi->ctx, NK_BUTTON_LEFT, (short)LOWORD(lparam), (short)HIWORD(lparam), 1); + SetCapture(wnd); + return 1; + + case WM_LBUTTONUP: + nk_input_button(&gdi->ctx, NK_BUTTON_DOUBLE, (short)LOWORD(lparam), (short)HIWORD(lparam), 0); + nk_input_button(&gdi->ctx, NK_BUTTON_LEFT, (short)LOWORD(lparam), (short)HIWORD(lparam), 0); + ReleaseCapture(); + return 1; + + case WM_RBUTTONDOWN: + nk_input_button(&gdi->ctx, NK_BUTTON_RIGHT, (short)LOWORD(lparam), (short)HIWORD(lparam), 1); + SetCapture(wnd); + return 1; + + case WM_RBUTTONUP: + nk_input_button(&gdi->ctx, NK_BUTTON_RIGHT, (short)LOWORD(lparam), (short)HIWORD(lparam), 0); + ReleaseCapture(); + return 1; + + case WM_MBUTTONDOWN: + nk_input_button(&gdi->ctx, NK_BUTTON_MIDDLE, (short)LOWORD(lparam), (short)HIWORD(lparam), 1); + SetCapture(wnd); + return 1; + + case WM_MBUTTONUP: + nk_input_button(&gdi->ctx, NK_BUTTON_MIDDLE, (short)LOWORD(lparam), (short)HIWORD(lparam), 0); + ReleaseCapture(); + return 1; + + case WM_MOUSEWHEEL: + nk_input_scroll(&gdi->ctx, nk_vec2(0, (float)(short)HIWORD(wparam) / WHEEL_DELTA)); + return 1; + + case WM_MOUSEMOVE: + nk_input_motion(&gdi->ctx, (short)LOWORD(lparam), (short)HIWORD(lparam)); + return 1; + + case WM_LBUTTONDBLCLK: + nk_input_button(&gdi->ctx, NK_BUTTON_DOUBLE, (short)LOWORD(lparam), (short)HIWORD(lparam), 1); + return 1; + } + + return 0; +} + +NK_API void +nk_gdi_shutdown(nk_gdi_ctx gdi) +{ + DeleteObject(gdi->memory_dc); + DeleteObject(gdi->bitmap); + nk_free(&gdi->ctx); +} + +NK_API void +nk_gdi_render(nk_gdi_ctx gdi, struct nk_color clear) +{ + const struct nk_command* cmd; + + HDC memory_dc = gdi->memory_dc; + SelectObject(memory_dc, GetStockObject(DC_PEN)); + SelectObject(memory_dc, GetStockObject(DC_BRUSH)); + nk_gdi_clear(gdi, memory_dc, clear); + + nk_foreach(cmd, &gdi->ctx) + { + switch (cmd->type) { + case NK_COMMAND_NOP: break; + case NK_COMMAND_SCISSOR: { + const struct nk_command_scissor* s = (const struct nk_command_scissor*)cmd; + nk_gdi_scissor(memory_dc, s->x, s->y, s->w, s->h); + } break; + case NK_COMMAND_LINE: { + const struct nk_command_line* l = (const struct nk_command_line*)cmd; + nk_gdi_stroke_line(memory_dc, l->begin.x, l->begin.y, l->end.x, + l->end.y, l->line_thickness, l->color); + } break; + case NK_COMMAND_RECT: { + const struct nk_command_rect* r = (const struct nk_command_rect*)cmd; + nk_gdi_stroke_rect(memory_dc, r->x, r->y, r->w, r->h, + (unsigned short)r->rounding, r->line_thickness, r->color); + } break; + case NK_COMMAND_RECT_FILLED: { + const struct nk_command_rect_filled* r = (const struct nk_command_rect_filled*)cmd; + nk_gdi_fill_rect(memory_dc, r->x, r->y, r->w, r->h, + (unsigned short)r->rounding, r->color); + } break; + case NK_COMMAND_CIRCLE: { + const struct nk_command_circle* c = (const struct nk_command_circle*)cmd; + nk_gdi_stroke_circle(memory_dc, c->x, c->y, c->w, c->h, c->line_thickness, c->color); + } break; + case NK_COMMAND_CIRCLE_FILLED: { + const struct nk_command_circle_filled* c = (const struct nk_command_circle_filled*)cmd; + nk_gdi_fill_circle(memory_dc, c->x, c->y, c->w, c->h, c->color); + } break; + case NK_COMMAND_TRIANGLE: { + const struct nk_command_triangle* t = (const struct nk_command_triangle*)cmd; + nk_gdi_stroke_triangle(memory_dc, t->a.x, t->a.y, t->b.x, t->b.y, + t->c.x, t->c.y, t->line_thickness, t->color); + } break; + case NK_COMMAND_TRIANGLE_FILLED: { + const struct nk_command_triangle_filled* t = (const struct nk_command_triangle_filled*)cmd; + nk_gdi_fill_triangle(memory_dc, t->a.x, t->a.y, t->b.x, t->b.y, + t->c.x, t->c.y, t->color); + } break; + case NK_COMMAND_POLYGON: { + const struct nk_command_polygon* p = (const struct nk_command_polygon*)cmd; + nk_gdi_stroke_polygon(memory_dc, p->points, p->point_count, p->line_thickness, p->color); + } break; + case NK_COMMAND_POLYGON_FILLED: { + const struct nk_command_polygon_filled* p = (const struct nk_command_polygon_filled*)cmd; + nk_gdi_fill_polygon(memory_dc, p->points, p->point_count, p->color); + } break; + case NK_COMMAND_POLYLINE: { + const struct nk_command_polyline* p = (const struct nk_command_polyline*)cmd; + nk_gdi_stroke_polyline(memory_dc, p->points, p->point_count, p->line_thickness, p->color); + } break; + case NK_COMMAND_TEXT: { + const struct nk_command_text* t = (const struct nk_command_text*)cmd; + nk_gdi_draw_text(memory_dc, t->x, t->y, t->w, t->h, + (const char*)t->string, t->length, + (GdiFont*)t->font->userdata.ptr, + t->background, t->foreground); + } break; + case NK_COMMAND_CURVE: { + const struct nk_command_curve* q = (const struct nk_command_curve*)cmd; + nk_gdi_stroke_curve(memory_dc, q->begin, q->ctrl[0], q->ctrl[1], + q->end, q->line_thickness, q->color); + } break; + case NK_COMMAND_RECT_MULTI_COLOR: { + const struct nk_command_rect_multi_color* r = (const struct nk_command_rect_multi_color*)cmd; + nk_gdi_rect_multi_color(gdi, memory_dc, r->x, r->y, r->w, r->h, r->left, r->top, r->right, r->bottom); + } break; + case NK_COMMAND_IMAGE: { + const struct nk_command_image* i = (const struct nk_command_image*)cmd; + nk_gdi_draw_image(gdi, i->x, i->y, i->w, i->h, i->img, i->col); + } break; + case NK_COMMAND_ARC: + case NK_COMMAND_ARC_FILLED: + default: break; + } + } + nk_gdi_blit(gdi, gdi->window_dc); + nk_clear(&gdi->ctx); +} + +#endif diff --git a/demo/gdi_native_nuklear/window.h b/demo/gdi_native_nuklear/window.h new file mode 100644 index 0000000..123e4a7 --- /dev/null +++ b/demo/gdi_native_nuklear/window.h @@ -0,0 +1,377 @@ +#pragma once + +namespace NkGdi +{ + // Container for window management + class WindowClass + { + public: + // Public exposed name + static const wchar_t* const ClassName; + + WindowClass(const WindowClass&) = delete; + private: + // Instance + static WindowClass ClassInstance; + + // Sigelton + WindowClass(); + }; + + // Window base class + class Window + { + friend class WindowClass; + + public: + // Default constructs + Window() = default; + Window(const Window&) = delete; + Window(Window&&) = default; + // Constructor + Window(unsigned int width, unsigned int height, const char* name, int posX = 100, int posY = 100); + // Destructor + ~Window(); + + // Processs window events and render the window (returns true as long as window is open) + bool Update(); + + // Properties + bool AllowSizing = true; + bool AllowMaximize = true; + bool AllowMove = true; + bool HasTitlebar = true; + + public: + // Called when the core window gets an event + virtual LRESULT OnWindowMessage(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam); + + // Called when the window is created + inline virtual void OnCreate() {}; + // Called when the window is destroyed + inline virtual void OnDestroy() {}; + // Called when the windows is beein updated (before events are served) + inline virtual void OnUpdate() {}; + // Called when the window is beeing closed by the user (return false to abort) + inline virtual bool OnClose() { return true; }; + // Called when nuklear drawcalls can be issued (return false to close the window) + inline virtual bool OnDraw(nk_context* ctx) { return true; }; + + private: + // Static window procs + static LRESULT wndProcSetup(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam); + static LRESULT wndProcRun(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam); + + private: + // Window handle + HWND m_window = NULL; + + // Nuklear context + nk_gdi_ctx m_nkGdiCtx = nullptr; + nk_context* m_nkCtx = nullptr; + + // Nuklear objects + GdiFont* m_gdiFont = nullptr; + HDC m_windowDc = NULL; + + // Window runtime features + bool m_isOpen = true; + bool m_isDraggin = false; + bool m_wsOverride = false; + bool m_isMaximized = false; + POINT m_dragOffset = {}; + int m_width = 0; + int m_height = 0; + }; +} + +#ifdef NKGDI_IMPLEMENT_WINDOW + +const wchar_t* const NkGdi::WindowClass::ClassName = L"WNDCLS_NkGdi"; +NkGdi::WindowClass NkGdi::WindowClass::ClassInstance; + +NkGdi::WindowClass::WindowClass() +{ + // Describe class + WNDCLASSEXW cls; + cls.cbSize = sizeof(WNDCLASSEXW); + cls.style = CS_OWNDC | CS_DBLCLKS; + cls.lpfnWndProc = &Window::wndProcSetup; + cls.cbClsExtra = 0; + cls.cbWndExtra = 0; + cls.hInstance = GetModuleHandle(NULL); + cls.hIcon = LoadIcon(NULL, IDI_APPLICATION); + cls.hCursor = LoadCursor(NULL, IDC_ARROW); + cls.hbrBackground = NULL; + cls.lpszMenuName = nullptr; + cls.lpszClassName = ClassName; + cls.hIconSm = NULL; + + // Register class + RegisterClassExW(&cls); +} + +NkGdi::Window::Window(unsigned int width, unsigned int height, const char* name, int posX, int posY) +{ + DWORD styleEx = WS_EX_WINDOWEDGE; + DWORD style = WS_POPUP; + + // Compute window size + RECT cr; + cr.left = 0; + cr.top = 0; + cr.right = width; + cr.bottom = height; + AdjustWindowRectEx(&cr, style, FALSE, styleEx); + + // Create the window + m_window = CreateWindowExW( + styleEx, + WindowClass::ClassName, + L"NkGdi", + style | WS_VISIBLE, + posX, posY, + cr.right - cr.left, cr.bottom - cr.top, + NULL, NULL, + GetModuleHandleW(nullptr), + this + ); + + // Rename window to user picked name + SetWindowTextA(m_window, name); + + // Get DC + m_windowDc = GetWindowDC(m_window); + + // Create font + m_gdiFont = nk_gdifont_create("Arial", 16); + m_nkCtx = nk_gdi_init(&m_nkGdiCtx, m_gdiFont, m_windowDc, width, height); +} + +NkGdi::Window::~Window() +{ + // Destroy GDI context + if (m_nkGdiCtx) + { + nk_gdi_shutdown(m_nkGdiCtx); + } + + // Destroy font + if (m_gdiFont) + { + nk_gdifont_del(m_gdiFont); + } + + // Close DC + if (m_windowDc) + { + ReleaseDC(m_window, m_windowDc); + } + + // Destroy window + if (m_window) + { + CloseWindow(m_window); + DestroyWindow(m_window); + } +} + +bool NkGdi::Window::Update() +{ + // Only process events while window is open + if (m_isOpen) + { + // Notify class that event processing has stated + OnUpdate(); + + // Windows event loop + MSG msg = {}; + nk_input_begin(m_nkCtx); + while (PeekMessage(&msg, m_window, 0, 0, PM_REMOVE)) + { + TranslateMessage(&msg); + DispatchMessageW(&msg); + } + nk_input_end(m_nkCtx); + + // Get title + char title[1024]; + GetWindowTextA(m_window, title, 1024); + + // Window body + if (m_wsOverride) + nk_window_set_bounds(m_nkCtx, title, nk_rect(0, 0, m_width, m_height)); + if (nk_begin(m_nkCtx, title, nk_rect(0, 0, m_width, m_height), + NK_WINDOW_BORDER | + (HasTitlebar ? NK_WINDOW_CLOSABLE | NK_WINDOW_TITLE : NULL) | + (m_isMaximized || !AllowSizing ? NULL : NK_WINDOW_SCALABLE) + )) + { + if(!OnDraw(m_nkCtx)) + m_isOpen = false; + + // Update window size + struct nk_rect bounds = nk_window_get_bounds(m_nkCtx); + if(bounds.w != m_width || bounds.h != m_height) + SetWindowPos(m_window, NULL, 0, 0, bounds.w, bounds.h, SWP_NOMOVE | SWP_NOOWNERZORDER); + } + else + { + // Handle window closing + if(OnClose()) + m_isOpen = false; + } + nk_end(m_nkCtx); + m_wsOverride = false; + + // Final render pass + nk_gdi_render(m_nkGdiCtx, nk_rgb(30, 30, 30)); + } + + return m_isOpen; +} + +LRESULT NkGdi::Window::OnWindowMessage(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + // Switch on supplied message code + switch (msg) + { + // Close event + case WM_CLOSE: + if (OnClose()) + m_isOpen = false; + return 0; // Will always be handled internaly + + // While sizing + case WM_SIZING: + { + RECT cr; + GetClientRect(wnd, &cr); + m_width = cr.right - cr.left; + m_height = cr.bottom - cr.top; + } + break; + + // When sized + case WM_SIZE: + { + // Adjust maximize properties + if (wParam == SIZE_MAXIMIZED) + { + HMONITOR monitor = MonitorFromWindow(wnd, MONITOR_DEFAULTTOPRIMARY); + MONITORINFO monitorInfo; + monitorInfo.cbSize = sizeof(MONITORINFO); + if (GetMonitorInfoW(monitor, &monitorInfo)) + { + m_height = monitorInfo.rcWork.bottom - monitorInfo.rcWork.top; + m_width = monitorInfo.rcWork.right - monitorInfo.rcWork.left; + m_wsOverride = true; + m_isMaximized = true; + SetWindowPos(wnd, NULL, 0, 0, m_width, m_height, SWP_NOMOVE | SWP_NOZORDER); + } + } + else if (wParam == SIZE_RESTORED) + { + m_isMaximized = false; + } + + // Compute new bounds + RECT cr; + GetClientRect(wnd, &cr); + m_width = cr.right - cr.left; + m_height = cr.bottom - cr.top; + } + break; + + // When mouse start l-press (drag window) + case WM_LBUTTONDOWN: + { + if (HIWORD(lParam) <= 30 && AllowMove) + { + // Start dragging + m_isDraggin = true; + m_dragOffset.x = LOWORD(lParam); + m_dragOffset.y = HIWORD(lParam); + } + } + break; + + // When mouse stops l-press (drag window) + case WM_LBUTTONUP: + m_isDraggin = false; + break; + + // Mouse movement (dragging) + case WM_MOUSEMOVE: + { + if (m_isDraggin && !m_isMaximized) + { + // Get mouse postion and substract offset + POINT cursorPos; + GetCursorPos(&cursorPos); + cursorPos.x -= m_dragOffset.x; + cursorPos.y -= m_dragOffset.y; + // Use as new position + ShowWindow(m_window, SW_RESTORE); + SetWindowPos(wnd, NULL, cursorPos.x, cursorPos.y, 0, 0, SWP_NOSIZE | SWP_NOZORDER); + } + } + break; + + // On mouse doubble click (maximize) + case WM_LBUTTONDBLCLK: + { + if (HIWORD(lParam) <= 30 && AllowMaximize) + { + if (m_isMaximized) + { + ShowWindow(wnd, SW_RESTORE); + } + else + { + ShowWindow(wnd, SW_MAXIMIZE); + } + m_wsOverride = true; + } + } + break; + } + + // Send to nuklear + if (m_nkGdiCtx && nk_gdi_handle_event(m_nkGdiCtx, wnd, msg, wParam, lParam)) + return 0; + + // In case this is ever reached: Run default behaviour + return DefWindowProc(wnd, msg, wParam, lParam); +} + +LRESULT NkGdi::Window::wndProcSetup(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + // Wait for setup message + if (msg == WM_NCCREATE) + { + // Get creation parameters & window pointer + CREATESTRUCT* ptrCr = (CREATESTRUCT*)lParam; + Window* ptrWindow = (Window*)ptrCr->lpCreateParams; + + // Store pointer and new proc in window + SetWindowLongPtr(wnd, GWLP_USERDATA, (LONG_PTR)ptrWindow); + SetWindowLongPtr(wnd, GWLP_WNDPROC, (LONG_PTR)&wndProcRun); + + // Handled by window + return ptrWindow->OnWindowMessage(wnd, msg, wParam, lParam); + } + + // Default handler + return DefWindowProc(wnd, msg, wParam, lParam); +} + +LRESULT NkGdi::Window::wndProcRun(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + // Get window pointer + Window* ptrWindow = (Window*)GetWindowLongPtr(wnd, GWLP_USERDATA); + // Call window + return ptrWindow->OnWindowMessage(wnd, msg, wParam, lParam); +} + +#endif From 169470d2e3bfcea4956aeb5ae82a127f29f5afaa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ludwig=20F=C3=BCchsl?= Date: Mon, 28 Feb 2022 14:57:47 +0100 Subject: [PATCH 002/106] Converted from C++ to C WARNING: Is currently not working! Needs more debugging. --- demo/gdi_native_nuklear/build.bat | 2 +- demo/gdi_native_nuklear/{main.cpp => main.c} | 25 +- demo/gdi_native_nuklear/window.h | 356 +++++++++---------- 3 files changed, 183 insertions(+), 200 deletions(-) rename demo/gdi_native_nuklear/{main.cpp => main.c} (61%) diff --git a/demo/gdi_native_nuklear/build.bat b/demo/gdi_native_nuklear/build.bat index 65a8ce6..2f87f8e 100644 --- a/demo/gdi_native_nuklear/build.bat +++ b/demo/gdi_native_nuklear/build.bat @@ -3,4 +3,4 @@ rem This will use VS2015 for compiler call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x86 -cl /nologo /W3 /O2 /fp:fast /Gm- /D_CRT_SECURE_NO_DEPRECATE /Fedemo.exe main.cpp user32.lib gdi32.lib Msimg32.lib /link /incremental:no +cl /nologo /W3 /O2 /fp:fast /Gm- /D_CRT_SECURE_NO_DEPRECATE /Fedemo.exe main.c user32.lib gdi32.lib Msimg32.lib /link /incremental:no diff --git a/demo/gdi_native_nuklear/main.cpp b/demo/gdi_native_nuklear/main.c similarity index 61% rename from demo/gdi_native_nuklear/main.cpp rename to demo/gdi_native_nuklear/main.c index 000ea2a..70ba268 100644 --- a/demo/gdi_native_nuklear/main.cpp +++ b/demo/gdi_native_nuklear/main.c @@ -1,5 +1,4 @@ #include -#include #pragma comment(linker,"\"/manifestdependency:type='win32' \ name='Microsoft.Windows.Common-Controls' version='6.0.0.0' \ @@ -19,19 +18,21 @@ processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") INT WINAPI wWinMain(HINSTANCE _In_ hInstance, HINSTANCE _In_opt_ hPrevInstance, PWSTR _In_ cmdArgs, INT _In_ cmdShow) { - NkGdi::Window w1(500, 500, "F1", 10, 10); - w1.AllowSizing = false; - w1.AllowMaximize = false; - w1.AllowMove = false; - w1.HasTitlebar = false; + struct nkgdi_window w1, w2; - NkGdi::Window w2(500, 500, "F2", 520, 10); - w2.AllowSizing = true; - w2.AllowMaximize = true; - w2.AllowMove = true; - w2.HasTitlebar = true; + w1.allow_sizing = 0; + w1.allow_maximize = 0; + w1.allow_move = 0; + w1.has_titlebar = 0; + nkgdi_window_create(&w1, 500, 500, "F1", 10, 10); + + w2.allow_sizing = 1; + w2.allow_maximize = 1; + w2.allow_move = 1; + w2.has_titlebar = 1; + nkgdi_window_create(&w2, 500, 500, "F2", 520, 10); - while (w1.Update() && w2.Update()) Sleep(20); + while (nkgdi_window_update(&w1) && nkgdi_window_update(&w2)) Sleep(20); return 0; } diff --git a/demo/gdi_native_nuklear/window.h b/demo/gdi_native_nuklear/window.h index 123e4a7..ce60475 100644 --- a/demo/gdi_native_nuklear/window.h +++ b/demo/gdi_native_nuklear/window.h @@ -1,117 +1,93 @@ -#pragma once +#ifndef NK_GDI_WINDOW +#define NK_GDI_WINDOW -namespace NkGdi +#define NK_GDI_WINDOW_CLS L"WNDCLS_NkGdi" + +#include + +/* Functin pointer types for window callbacks */ +typedef void(*nkgdi_window_func_update)(void); +typedef int(*nkgdi_window_func_close)(void); +typedef int(*nkgdi_window_func_draw)(struct nk_context*); + +/* Window container / context */ +struct nkgdi_window { - // Container for window management - class WindowClass + /* Properties */ + int allow_sizing; + int allow_maximize; + int allow_move; + int has_titlebar; + + /* Callbacks */ + nkgdi_window_func_update cb_on_update; + nkgdi_window_func_close cb_on_close; + nkgdi_window_func_draw cb_on_draw; + + /* Internal Data */ + struct { - public: - // Public exposed name - static const wchar_t* const ClassName; + // Window handle + HWND window_handle; - WindowClass(const WindowClass&) = delete; - private: - // Instance - static WindowClass ClassInstance; + // Nuklear context + nk_gdi_ctx nk_gdi_ctx; + struct nk_context* nk_ctx; - // Sigelton - WindowClass(); - }; + // Nuklear objects + GdiFont* gdi_font; + HDC window_dc; - // Window base class - class Window - { - friend class WindowClass; + // Window runtime features + int is_open; + int is_draggin; + int ws_override; + int is_maximized; + POINT drag_offset; + int width; + int height; + }_internal; +}; - public: - // Default constructs - Window() = default; - Window(const Window&) = delete; - Window(Window&&) = default; - // Constructor - Window(unsigned int width, unsigned int height, const char* name, int posX = 100, int posY = 100); - // Destructor - ~Window(); - - // Processs window events and render the window (returns true as long as window is open) - bool Update(); - - // Properties - bool AllowSizing = true; - bool AllowMaximize = true; - bool AllowMove = true; - bool HasTitlebar = true; - - public: - // Called when the core window gets an event - virtual LRESULT OnWindowMessage(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam); - - // Called when the window is created - inline virtual void OnCreate() {}; - // Called when the window is destroyed - inline virtual void OnDestroy() {}; - // Called when the windows is beein updated (before events are served) - inline virtual void OnUpdate() {}; - // Called when the window is beeing closed by the user (return false to abort) - inline virtual bool OnClose() { return true; }; - // Called when nuklear drawcalls can be issued (return false to close the window) - inline virtual bool OnDraw(nk_context* ctx) { return true; }; - - private: - // Static window procs - static LRESULT wndProcSetup(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam); - static LRESULT wndProcRun(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam); - - private: - // Window handle - HWND m_window = NULL; - - // Nuklear context - nk_gdi_ctx m_nkGdiCtx = nullptr; - nk_context* m_nkCtx = nullptr; - - // Nuklear objects - GdiFont* m_gdiFont = nullptr; - HDC m_windowDc = NULL; - - // Window runtime features - bool m_isOpen = true; - bool m_isDraggin = false; - bool m_wsOverride = false; - bool m_isMaximized = false; - POINT m_dragOffset = {}; - int m_width = 0; - int m_height = 0; - }; -} +/* API */ +void nkgdi_window_init(void); +void nkgdi_window_shutdown(void); +void nkgdi_window_create(struct nkgdi_window* wnd, unsigned int width, unsigned int height, const char* name, int posX, int posY); +int nkgdi_window_update(struct nkgdi_window* wnd); +void nkgdi_window_destroy(struct nkgdi_window* wnd); #ifdef NKGDI_IMPLEMENT_WINDOW -const wchar_t* const NkGdi::WindowClass::ClassName = L"WNDCLS_NkGdi"; -NkGdi::WindowClass NkGdi::WindowClass::ClassInstance; +LRESULT nkgdi_window_proc_setup(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam); +LRESULT nkgdi_window_proc_run(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam); -NkGdi::WindowClass::WindowClass() +void nkgdi_window_init(void) { // Describe class WNDCLASSEXW cls; cls.cbSize = sizeof(WNDCLASSEXW); cls.style = CS_OWNDC | CS_DBLCLKS; - cls.lpfnWndProc = &Window::wndProcSetup; + cls.lpfnWndProc = &nkgdi_window_proc_setup; cls.cbClsExtra = 0; cls.cbWndExtra = 0; cls.hInstance = GetModuleHandle(NULL); cls.hIcon = LoadIcon(NULL, IDI_APPLICATION); cls.hCursor = LoadCursor(NULL, IDC_ARROW); cls.hbrBackground = NULL; - cls.lpszMenuName = nullptr; - cls.lpszClassName = ClassName; + cls.lpszMenuName = NULL; + cls.lpszClassName = NK_GDI_WINDOW_CLS; cls.hIconSm = NULL; // Register class RegisterClassExW(&cls); } -NkGdi::Window::Window(unsigned int width, unsigned int height, const char* name, int posX, int posY) +void nkgdi_window_shutdown(void) +{ + UnregisterClassW(NK_GDI_WINDOW_CLS, GetModuleHandle(NULL)); +} + +void nkgdi_window_create(struct nkgdi_window* wnd, unsigned int width, unsigned int height, const char* name, int posX, int posY) { DWORD styleEx = WS_EX_WINDOWEDGE; DWORD style = WS_POPUP; @@ -125,121 +101,155 @@ NkGdi::Window::Window(unsigned int width, unsigned int height, const char* name, AdjustWindowRectEx(&cr, style, FALSE, styleEx); // Create the window - m_window = CreateWindowExW( + wnd->_internal.window_handle = CreateWindowExW( styleEx, - WindowClass::ClassName, + NK_GDI_WINDOW_CLS, L"NkGdi", style | WS_VISIBLE, posX, posY, cr.right - cr.left, cr.bottom - cr.top, NULL, NULL, - GetModuleHandleW(nullptr), - this + GetModuleHandleW(NULL), + wnd ); // Rename window to user picked name - SetWindowTextA(m_window, name); + SetWindowTextA(wnd->_internal.window_handle, name); // Get DC - m_windowDc = GetWindowDC(m_window); + wnd->_internal.window_dc = GetWindowDC(wnd->_internal.window_handle); // Create font - m_gdiFont = nk_gdifont_create("Arial", 16); - m_nkCtx = nk_gdi_init(&m_nkGdiCtx, m_gdiFont, m_windowDc, width, height); + wnd->_internal.gdi_font = nk_gdifont_create("Arial", 16); + wnd->_internal.nk_ctx = nk_gdi_init(&wnd->_internal.nk_gdi_ctx, wnd->_internal.gdi_font, wnd->_internal.window_dc, width, height); + + // Setup internal data + wnd->_internal.is_open = 1; + wnd->_internal.is_draggin = 0; + wnd->_internal.ws_override = 0; + wnd->_internal.is_maximized = 0; + wnd->_internal.drag_offset.x = 0; + wnd->_internal.drag_offset.y = 0; + wnd->_internal.width = 0; + wnd->_internal.height = 0; } -NkGdi::Window::~Window() +void nkgdi_window_destroy(struct nkgdi_window* wnd) { // Destroy GDI context - if (m_nkGdiCtx) + if (wnd->_internal.nk_gdi_ctx) { - nk_gdi_shutdown(m_nkGdiCtx); + nk_gdi_shutdown(wnd->_internal.nk_gdi_ctx); } // Destroy font - if (m_gdiFont) + if (wnd->_internal.gdi_font) { - nk_gdifont_del(m_gdiFont); + nk_gdifont_del(wnd->_internal.gdi_font); } // Close DC - if (m_windowDc) + if (wnd->_internal.window_dc) { - ReleaseDC(m_window, m_windowDc); + ReleaseDC(wnd->_internal.window_handle, wnd->_internal.window_dc); } // Destroy window - if (m_window) + if (wnd->_internal.window_handle) { - CloseWindow(m_window); - DestroyWindow(m_window); + CloseWindow(wnd->_internal.window_handle); + DestroyWindow(wnd->_internal.window_handle); } } -bool NkGdi::Window::Update() +int nkgdi_window_update(struct nkgdi_window* wnd) { // Only process events while window is open - if (m_isOpen) + if (wnd->_internal.is_open) { - // Notify class that event processing has stated - OnUpdate(); - // Windows event loop - MSG msg = {}; - nk_input_begin(m_nkCtx); - while (PeekMessage(&msg, m_window, 0, 0, PM_REMOVE)) + MSG msg; + nk_input_begin(wnd->_internal.nk_ctx); + while (PeekMessage(&msg, wnd->_internal.window_handle, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessageW(&msg); } - nk_input_end(m_nkCtx); + nk_input_end(wnd->_internal.nk_ctx); // Get title char title[1024]; - GetWindowTextA(m_window, title, 1024); + GetWindowTextA(wnd->_internal.window_handle, title, 1024); + + // Window flags + nk_flags window_flags = NK_WINDOW_BORDER; + if(wnd->has_titlebar) + window_flags |= NK_WINDOW_CLOSABLE | NK_WINDOW_TITLE; + if(!wnd->_internal.is_maximized && wnd->allow_sizing) + window_flags |= NK_WINDOW_SCALABLE; // Window body - if (m_wsOverride) - nk_window_set_bounds(m_nkCtx, title, nk_rect(0, 0, m_width, m_height)); - if (nk_begin(m_nkCtx, title, nk_rect(0, 0, m_width, m_height), - NK_WINDOW_BORDER | - (HasTitlebar ? NK_WINDOW_CLOSABLE | NK_WINDOW_TITLE : NULL) | - (m_isMaximized || !AllowSizing ? NULL : NK_WINDOW_SCALABLE) - )) + if (wnd->_internal.ws_override) + nk_window_set_bounds(wnd->_internal.nk_ctx, title, nk_rect(0, 0, wnd->_internal.width, wnd->_internal.height)); + if (nk_begin(wnd->_internal.nk_ctx, title, nk_rect(0, 0, wnd->_internal.width, wnd->_internal.height), window_flags)) { - if(!OnDraw(m_nkCtx)) - m_isOpen = false; + if(!wnd->cb_on_draw(wnd->_internal.nk_ctx)) + wnd->_internal.is_open = 0; // Update window size - struct nk_rect bounds = nk_window_get_bounds(m_nkCtx); - if(bounds.w != m_width || bounds.h != m_height) - SetWindowPos(m_window, NULL, 0, 0, bounds.w, bounds.h, SWP_NOMOVE | SWP_NOOWNERZORDER); + struct nk_rect bounds = nk_window_get_bounds(wnd->_internal.nk_ctx); + if(bounds.w != wnd->_internal.width || bounds.h != wnd->_internal.height) + SetWindowPos(wnd->_internal.window_handle, NULL, 0, 0, bounds.w, bounds.h, SWP_NOMOVE | SWP_NOOWNERZORDER); } else { // Handle window closing - if(OnClose()) - m_isOpen = false; + if(!wnd->cb_on_close || wnd->cb_on_close()) + wnd->_internal.is_open = 0; } - nk_end(m_nkCtx); - m_wsOverride = false; + nk_end(wnd->_internal.nk_ctx); + wnd->_internal.ws_override = 0; // Final render pass - nk_gdi_render(m_nkGdiCtx, nk_rgb(30, 30, 30)); + nk_gdi_render(wnd->_internal.nk_gdi_ctx, nk_rgb(30, 30, 30)); } - return m_isOpen; + return wnd->_internal.is_open; } -LRESULT NkGdi::Window::OnWindowMessage(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) +LRESULT nkgdi_window_proc_setup(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) { + // Wait for setup message + if (msg == WM_NCCREATE) + { + // Get creation parameters & window pointer + CREATESTRUCT* ptrCr = (CREATESTRUCT*)lParam; + struct nkgdi_window* nkgdi_wnd = (struct nkgdi_window*)ptrCr->lpCreateParams; + + // Store pointer and new proc in window + SetWindowLongPtr(wnd, GWLP_USERDATA, (LONG_PTR)nkgdi_wnd); + SetWindowLongPtr(wnd, GWLP_WNDPROC, (LONG_PTR)&nkgdi_window_proc_run); + + // Handled by window + return nkgdi_window_proc_run(wnd, msg, wParam, lParam); + } + + // Default handler + return DefWindowProc(wnd, msg, wParam, lParam); +} + +LRESULT nkgdi_window_proc_run(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + // Get window pointer + struct nkgdi_window* nkwnd = (struct nkgdi_window*)GetWindowLongPtrW(wnd, GWLP_USERDATA); + // Switch on supplied message code switch (msg) { // Close event case WM_CLOSE: - if (OnClose()) - m_isOpen = false; + if(!nkwnd->cb_on_close || nkwnd->cb_on_close()) + nkwnd->_internal.is_open = 0; return 0; // Will always be handled internaly // While sizing @@ -247,8 +257,8 @@ LRESULT NkGdi::Window::OnWindowMessage(HWND wnd, UINT msg, WPARAM wParam, LPARAM { RECT cr; GetClientRect(wnd, &cr); - m_width = cr.right - cr.left; - m_height = cr.bottom - cr.top; + nkwnd->_internal.width = cr.right - cr.left; + nkwnd->_internal.height = cr.bottom - cr.top; } break; @@ -263,56 +273,56 @@ LRESULT NkGdi::Window::OnWindowMessage(HWND wnd, UINT msg, WPARAM wParam, LPARAM monitorInfo.cbSize = sizeof(MONITORINFO); if (GetMonitorInfoW(monitor, &monitorInfo)) { - m_height = monitorInfo.rcWork.bottom - monitorInfo.rcWork.top; - m_width = monitorInfo.rcWork.right - monitorInfo.rcWork.left; - m_wsOverride = true; - m_isMaximized = true; - SetWindowPos(wnd, NULL, 0, 0, m_width, m_height, SWP_NOMOVE | SWP_NOZORDER); + nkwnd->_internal.height = monitorInfo.rcWork.bottom - monitorInfo.rcWork.top; + nkwnd->_internal.width = monitorInfo.rcWork.right - monitorInfo.rcWork.left; + nkwnd->_internal.ws_override = 1; + nkwnd->_internal.is_maximized = 1; + SetWindowPos(wnd, NULL, 0, 0, nkwnd->_internal.width, nkwnd->_internal.height, SWP_NOMOVE | SWP_NOZORDER); } } else if (wParam == SIZE_RESTORED) { - m_isMaximized = false; + nkwnd->_internal.is_maximized = 0; } // Compute new bounds RECT cr; GetClientRect(wnd, &cr); - m_width = cr.right - cr.left; - m_height = cr.bottom - cr.top; + nkwnd->_internal.width = cr.right - cr.left; + nkwnd->_internal.height = cr.bottom - cr.top; } break; // When mouse start l-press (drag window) case WM_LBUTTONDOWN: { - if (HIWORD(lParam) <= 30 && AllowMove) + if (HIWORD(lParam) <= 30 && nkwnd->allow_move) { // Start dragging - m_isDraggin = true; - m_dragOffset.x = LOWORD(lParam); - m_dragOffset.y = HIWORD(lParam); + nkwnd->_internal.is_draggin = 1; + nkwnd->_internal.drag_offset.x = LOWORD(lParam); + nkwnd->_internal.drag_offset.y = HIWORD(lParam); } } break; // When mouse stops l-press (drag window) case WM_LBUTTONUP: - m_isDraggin = false; + nkwnd->_internal.is_draggin = 0; break; // Mouse movement (dragging) case WM_MOUSEMOVE: { - if (m_isDraggin && !m_isMaximized) + if (nkwnd->_internal.is_draggin && !nkwnd->_internal.is_maximized) { // Get mouse postion and substract offset POINT cursorPos; GetCursorPos(&cursorPos); - cursorPos.x -= m_dragOffset.x; - cursorPos.y -= m_dragOffset.y; + cursorPos.x -= nkwnd->_internal.drag_offset.x; + cursorPos.y -= nkwnd->_internal.drag_offset.y; // Use as new position - ShowWindow(m_window, SW_RESTORE); + ShowWindow(wnd, SW_RESTORE); SetWindowPos(wnd, NULL, cursorPos.x, cursorPos.y, 0, 0, SWP_NOSIZE | SWP_NOZORDER); } } @@ -321,9 +331,9 @@ LRESULT NkGdi::Window::OnWindowMessage(HWND wnd, UINT msg, WPARAM wParam, LPARAM // On mouse doubble click (maximize) case WM_LBUTTONDBLCLK: { - if (HIWORD(lParam) <= 30 && AllowMaximize) + if (HIWORD(lParam) <= 30 && nkwnd->allow_maximize) { - if (m_isMaximized) + if (nkwnd->_internal.is_maximized) { ShowWindow(wnd, SW_RESTORE); } @@ -331,47 +341,19 @@ LRESULT NkGdi::Window::OnWindowMessage(HWND wnd, UINT msg, WPARAM wParam, LPARAM { ShowWindow(wnd, SW_MAXIMIZE); } - m_wsOverride = true; + nkwnd->_internal.ws_override = 1; } } break; } // Send to nuklear - if (m_nkGdiCtx && nk_gdi_handle_event(m_nkGdiCtx, wnd, msg, wParam, lParam)) + if (nkwnd->_internal.nk_gdi_ctx && nk_gdi_handle_event(nkwnd->_internal.nk_gdi_ctx, wnd, msg, wParam, lParam)) return 0; // In case this is ever reached: Run default behaviour return DefWindowProc(wnd, msg, wParam, lParam); } -LRESULT NkGdi::Window::wndProcSetup(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) -{ - // Wait for setup message - if (msg == WM_NCCREATE) - { - // Get creation parameters & window pointer - CREATESTRUCT* ptrCr = (CREATESTRUCT*)lParam; - Window* ptrWindow = (Window*)ptrCr->lpCreateParams; - - // Store pointer and new proc in window - SetWindowLongPtr(wnd, GWLP_USERDATA, (LONG_PTR)ptrWindow); - SetWindowLongPtr(wnd, GWLP_WNDPROC, (LONG_PTR)&wndProcRun); - - // Handled by window - return ptrWindow->OnWindowMessage(wnd, msg, wParam, lParam); - } - - // Default handler - return DefWindowProc(wnd, msg, wParam, lParam); -} - -LRESULT NkGdi::Window::wndProcRun(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) -{ - // Get window pointer - Window* ptrWindow = (Window*)GetWindowLongPtr(wnd, GWLP_USERDATA); - // Call window - return ptrWindow->OnWindowMessage(wnd, msg, wParam, lParam); -} - +#endif #endif From 33395aabdb439ac41998f5c57982d2dfc8fc09a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ludwig=20F=C3=BCchsl?= Date: Mon, 28 Feb 2022 15:53:54 +0100 Subject: [PATCH 003/106] Fixed non displayed windows. WARNING: Drawing is not done correctly --- demo/gdi_native_nuklear/main.c | 16 ++++++++++++++++ demo/gdi_native_nuklear/window.h | 6 +++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/demo/gdi_native_nuklear/main.c b/demo/gdi_native_nuklear/main.c index 70ba268..05ed83b 100644 --- a/demo/gdi_native_nuklear/main.c +++ b/demo/gdi_native_nuklear/main.c @@ -16,23 +16,39 @@ processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") #define NKGDI_IMPLEMENT_WINDOW #include "window.h" +int drawCallback(struct nk_context* ctx) +{ + nk_label(ctx, "Label", NK_TEXT_ALIGN_CENTERED); + nk_button_label(ctx, "Test 1234"); + return 1; +} + INT WINAPI wWinMain(HINSTANCE _In_ hInstance, HINSTANCE _In_opt_ hPrevInstance, PWSTR _In_ cmdArgs, INT _In_ cmdShow) { + nkgdi_window_init(); struct nkgdi_window w1, w2; + memset(&w1, 0x0, sizeof(struct nkgdi_window)); + memset(&w2, 0x0, sizeof(struct nkgdi_window)); w1.allow_sizing = 0; w1.allow_maximize = 0; w1.allow_move = 0; w1.has_titlebar = 0; + w1.cb_on_draw = &drawCallback; nkgdi_window_create(&w1, 500, 500, "F1", 10, 10); w2.allow_sizing = 1; w2.allow_maximize = 1; w2.allow_move = 1; w2.has_titlebar = 1; + w2.cb_on_draw = &drawCallback; nkgdi_window_create(&w2, 500, 500, "F2", 520, 10); while (nkgdi_window_update(&w1) && nkgdi_window_update(&w2)) Sleep(20); + nkgdi_window_destroy(&w1); + nkgdi_window_destroy(&w2); + + nkgdi_window_shutdown(); return 0; } diff --git a/demo/gdi_native_nuklear/window.h b/demo/gdi_native_nuklear/window.h index ce60475..ee1b5de 100644 --- a/demo/gdi_native_nuklear/window.h +++ b/demo/gdi_native_nuklear/window.h @@ -130,8 +130,8 @@ void nkgdi_window_create(struct nkgdi_window* wnd, unsigned int width, unsigned wnd->_internal.is_maximized = 0; wnd->_internal.drag_offset.x = 0; wnd->_internal.drag_offset.y = 0; - wnd->_internal.width = 0; - wnd->_internal.height = 0; + wnd->_internal.width = width; + wnd->_internal.height = height; } void nkgdi_window_destroy(struct nkgdi_window* wnd) @@ -193,7 +193,7 @@ int nkgdi_window_update(struct nkgdi_window* wnd) nk_window_set_bounds(wnd->_internal.nk_ctx, title, nk_rect(0, 0, wnd->_internal.width, wnd->_internal.height)); if (nk_begin(wnd->_internal.nk_ctx, title, nk_rect(0, 0, wnd->_internal.width, wnd->_internal.height), window_flags)) { - if(!wnd->cb_on_draw(wnd->_internal.nk_ctx)) + if(wnd->cb_on_draw && !wnd->cb_on_draw(wnd->_internal.nk_ctx)) wnd->_internal.is_open = 0; // Update window size From a31c6c0089a2e13ad6dbfc8cc29cc975cf3afcc3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ludwig=20F=C3=BCchsl?= Date: Fri, 4 Mar 2022 13:16:47 +0100 Subject: [PATCH 004/106] Bug fix & Added comments --- demo/gdi_native_nuklear/main.c | 76 +++++++++++++- demo/gdi_native_nuklear/nuklear_gdi.h | 5 + demo/gdi_native_nuklear/window.h | 142 +++++++++++++++----------- 3 files changed, 164 insertions(+), 59 deletions(-) diff --git a/demo/gdi_native_nuklear/main.c b/demo/gdi_native_nuklear/main.c index 05ed83b..b6cb6a9 100644 --- a/demo/gdi_native_nuklear/main.c +++ b/demo/gdi_native_nuklear/main.c @@ -4,6 +4,9 @@ name='Microsoft.Windows.Common-Controls' version='6.0.0.0' \ processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") +/* Includes the default nuklear implementation + * Includes the modified GDI backend (No more global state to allow multiple hwnd's) + */ #define NK_INCLUDE_FIXED_TYPES #define NK_INCLUDE_STANDARD_IO #define NK_INCLUDE_STANDARD_VARARGS @@ -13,23 +16,88 @@ processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") #include "../../nuklear.h" #include "nuklear_gdi.h" +/* Include the window framework (the new fancy code of this demo) */ #define NKGDI_IMPLEMENT_WINDOW #include "window.h" +/* This callback will be called when the window is draw + * You will NOT need to call nk_begin(...) and nk_end(...) + * begin and end are handled by the parent code calling this + * callback + */ int drawCallback(struct nk_context* ctx) { - nk_label(ctx, "Label", NK_TEXT_ALIGN_CENTERED); - nk_button_label(ctx, "Test 1234"); + /* Code is from ../calculator.c */ + static int set = 0, prev = 0, op = 0; + static const char numbers[] = "789456123"; + static const char ops[] = "+-*/"; + static double a = 0, b = 0; + static double *current = &a; + + size_t i = 0; + int solve = 0; + {int len; char buffer[256]; + nk_layout_row_dynamic(ctx, 35, 1); + len = snprintf(buffer, 256, "%.2f", *current); + nk_edit_string(ctx, NK_EDIT_SIMPLE, buffer, &len, 255, nk_filter_float); + buffer[len] = 0; + *current = atof(buffer);} + + nk_layout_row_dynamic(ctx, 35, 4); + for (i = 0; i < 16; ++i) { + if (i >= 12 && i < 15) { + if (i > 12) continue; + if (nk_button_label(ctx, "C")) { + a = b = op = 0; current = &a; set = 0; + } if (nk_button_label(ctx, "0")) { + *current = *current*10.0f; set = 0; + } if (nk_button_label(ctx, "=")) { + solve = 1; prev = op; op = 0; + } + } else if (((i+1) % 4)) { + if (nk_button_text(ctx, &numbers[(i/4)*3+i%4], 1)) { + *current = *current * 10.0f + numbers[(i/4)*3+i%4] - '0'; + set = 0; + } + } else if (nk_button_text(ctx, &ops[i/4], 1)) { + if (!set) { + if (current != &b) { + current = &b; + } else { + prev = op; + solve = 1; + } + } + op = ops[i/4]; + set = 1; + } + } + if (solve) { + if (prev == '+') a = a + b; + if (prev == '-') a = a - b; + if (prev == '*') a = a * b; + if (prev == '/') a = a / b; + current = &a; + if (set) current = &b; + b = 0; set = 0; + } return 1; } +/* Main entry point (Windows wchar_t) */ INT WINAPI wWinMain(HINSTANCE _In_ hInstance, HINSTANCE _In_opt_ hPrevInstance, PWSTR _In_ cmdArgs, INT _In_ cmdShow) { + /* Call this first to setup all required prerequisites */ nkgdi_window_init(); + + /* Preparing two window contexts */ struct nkgdi_window w1, w2; memset(&w1, 0x0, sizeof(struct nkgdi_window)); memset(&w2, 0x0, sizeof(struct nkgdi_window)); + /* Configure and create window 1. + * Note: You can allways change the direct accesible parameters later as well! + */ w1.allow_sizing = 0; w1.allow_maximize = 0; w1.allow_move = 0; @@ -37,6 +105,7 @@ INT WINAPI wWinMain(HINSTANCE _In_ hInstance, HINSTANCE _In_opt_ hPrevInstance, w1.cb_on_draw = &drawCallback; nkgdi_window_create(&w1, 500, 500, "F1", 10, 10); + /* Configure and create window 2 */ w2.allow_sizing = 1; w2.allow_maximize = 1; w2.allow_move = 1; @@ -44,11 +113,14 @@ INT WINAPI wWinMain(HINSTANCE _In_ hInstance, HINSTANCE _In_opt_ hPrevInstance, w2.cb_on_draw = &drawCallback; nkgdi_window_create(&w2, 500, 500, "F2", 520, 10); + /* As long as both windows are valid (nkgdi_window_update returning 1) */ while (nkgdi_window_update(&w1) && nkgdi_window_update(&w2)) Sleep(20); + /* Destroy both windows context */ nkgdi_window_destroy(&w1); nkgdi_window_destroy(&w2); + /* Call nkgdi_window_shutdown to properly shutdown the gdi window framework */ nkgdi_window_shutdown(); return 0; } diff --git a/demo/gdi_native_nuklear/nuklear_gdi.h b/demo/gdi_native_nuklear/nuklear_gdi.h index aef6452..5c2f1f8 100644 --- a/demo/gdi_native_nuklear/nuklear_gdi.h +++ b/demo/gdi_native_nuklear/nuklear_gdi.h @@ -2,6 +2,11 @@ * Nuklear - 1.32.0 - public domain * no warrenty implied; use at your own risk. * authored from 2015-2016 by Micha Mettke + * + * Modified GDI backend 2022 + * Now based on a context that is required for each API function call. + * Removes the global state --> you can have multiple windows :-) + * */ /* * ============================================================== diff --git a/demo/gdi_native_nuklear/window.h b/demo/gdi_native_nuklear/window.h index ee1b5de..0db572f 100644 --- a/demo/gdi_native_nuklear/window.h +++ b/demo/gdi_native_nuklear/window.h @@ -6,40 +6,45 @@ #include /* Functin pointer types for window callbacks */ -typedef void(*nkgdi_window_func_update)(void); typedef int(*nkgdi_window_func_close)(void); typedef int(*nkgdi_window_func_draw)(struct nk_context*); /* Window container / context */ struct nkgdi_window { - /* Properties */ + /* The window can be sized */ int allow_sizing; + /* The window can be maximized by double clicking the titlebar */ int allow_maximize; + /* The window is allowed to be moved by the user */ int allow_move; + /* The window will render it's title bar */ int has_titlebar; /* Callbacks */ - nkgdi_window_func_update cb_on_update; + /* Called when the user or os requests a window close (return 1 to accept the reqest)*/ nkgdi_window_func_close cb_on_close; + /* Called each time the window content should be drawn. Here you will do your nuklear drawing code + * but WITHOUT nk_begin and nk_end. Return 1 to keep the window open. + */ nkgdi_window_func_draw cb_on_draw; /* Internal Data */ struct { - // Window handle + /* Window handle */ HWND window_handle; - // Nuklear context + /* Nuklear & GDI context */ nk_gdi_ctx nk_gdi_ctx; struct nk_context* nk_ctx; - // Nuklear objects + /* GDI required objects */ GdiFont* gdi_font; HDC window_dc; - // Window runtime features - int is_open; + /* Internally used state variables */ + int is_open; int is_draggin; int ws_override; int is_maximized; @@ -50,20 +55,28 @@ struct nkgdi_window }; /* API */ +/* This function will init all resources used by the implementation */ void nkgdi_window_init(void); +/* This function will free all globally used resources */ void nkgdi_window_shutdown(void); +/* Creates a new window (for the wnd context) */ void nkgdi_window_create(struct nkgdi_window* wnd, unsigned int width, unsigned int height, const char* name, int posX, int posY); +/* Updates the window (Windows message loop, nuklear loop and drawing). Returns one as long as the window is valid and open */ int nkgdi_window_update(struct nkgdi_window* wnd); +/* Destroys the window context wnd */ void nkgdi_window_destroy(struct nkgdi_window* wnd); #ifdef NKGDI_IMPLEMENT_WINDOW +/* Predeclare the windows window message procs */ +/* This proc will setup the pointer to the window context */ LRESULT nkgdi_window_proc_setup(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam); +/* This proc will take the window context pointer and performs operations on it*/ LRESULT nkgdi_window_proc_run(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam); void nkgdi_window_init(void) { - // Describe class + /* Describe the window class */ WNDCLASSEXW cls; cls.cbSize = sizeof(WNDCLASSEXW); cls.style = CS_OWNDC | CS_DBLCLKS; @@ -78,12 +91,13 @@ void nkgdi_window_init(void) cls.lpszClassName = NK_GDI_WINDOW_CLS; cls.hIconSm = NULL; - // Register class + /* Register the window class */ RegisterClassExW(&cls); } void nkgdi_window_shutdown(void) { + /* Windows class no longer required, unregister it */ UnregisterClassW(NK_GDI_WINDOW_CLS, GetModuleHandle(NULL)); } @@ -92,7 +106,7 @@ void nkgdi_window_create(struct nkgdi_window* wnd, unsigned int width, unsigned DWORD styleEx = WS_EX_WINDOWEDGE; DWORD style = WS_POPUP; - // Compute window size + /* Adjust window size to fit selected window styles */ RECT cr; cr.left = 0; cr.top = 0; @@ -100,7 +114,7 @@ void nkgdi_window_create(struct nkgdi_window* wnd, unsigned int width, unsigned cr.bottom = height; AdjustWindowRectEx(&cr, style, FALSE, styleEx); - // Create the window + /* Create the new window */ wnd->_internal.window_handle = CreateWindowExW( styleEx, NK_GDI_WINDOW_CLS, @@ -113,17 +127,19 @@ void nkgdi_window_create(struct nkgdi_window* wnd, unsigned int width, unsigned wnd ); - // Rename window to user picked name + /* Give the window the ascii char name */ SetWindowTextA(wnd->_internal.window_handle, name); - // Get DC + /* Extract the window dc for gdi drawing */ wnd->_internal.window_dc = GetWindowDC(wnd->_internal.window_handle); - // Create font + /* Create the gdi font required to draw text */ wnd->_internal.gdi_font = nk_gdifont_create("Arial", 16); + + /* Init the gdi backend */ wnd->_internal.nk_ctx = nk_gdi_init(&wnd->_internal.nk_gdi_ctx, wnd->_internal.gdi_font, wnd->_internal.window_dc, width, height); - // Setup internal data + /* Bring all internal variables to a defined and valid initial state */ wnd->_internal.is_open = 1; wnd->_internal.is_draggin = 0; wnd->_internal.ws_override = 0; @@ -136,25 +152,19 @@ void nkgdi_window_create(struct nkgdi_window* wnd, unsigned int width, unsigned void nkgdi_window_destroy(struct nkgdi_window* wnd) { - // Destroy GDI context + /* Destroy all objects in reverse order */ if (wnd->_internal.nk_gdi_ctx) { nk_gdi_shutdown(wnd->_internal.nk_gdi_ctx); } - - // Destroy font if (wnd->_internal.gdi_font) { nk_gdifont_del(wnd->_internal.gdi_font); } - - // Close DC if (wnd->_internal.window_dc) { ReleaseDC(wnd->_internal.window_handle, wnd->_internal.window_dc); } - - // Destroy window if (wnd->_internal.window_handle) { CloseWindow(wnd->_internal.window_handle); @@ -164,10 +174,10 @@ void nkgdi_window_destroy(struct nkgdi_window* wnd) int nkgdi_window_update(struct nkgdi_window* wnd) { - // Only process events while window is open + /* The window will only be updated when it is open / valid */ if (wnd->_internal.is_open) { - // Windows event loop + /* First all pending window events will be processed */ MSG msg; nk_input_begin(wnd->_internal.nk_ctx); while (PeekMessage(&msg, wnd->_internal.window_handle, 0, 0, PM_REMOVE)) @@ -177,41 +187,46 @@ int nkgdi_window_update(struct nkgdi_window* wnd) } nk_input_end(wnd->_internal.nk_ctx); - // Get title + /* To setup the nuklear window we need the windows title */ char title[1024]; GetWindowTextA(wnd->_internal.window_handle, title, 1024); - // Window flags + /* The nk window flags are beeing create based on the context setup */ nk_flags window_flags = NK_WINDOW_BORDER; if(wnd->has_titlebar) window_flags |= NK_WINDOW_CLOSABLE | NK_WINDOW_TITLE; if(!wnd->_internal.is_maximized && wnd->allow_sizing) window_flags |= NK_WINDOW_SCALABLE; - // Window body + /* Override the nuklear windows size when required */ if (wnd->_internal.ws_override) nk_window_set_bounds(wnd->_internal.nk_ctx, title, nk_rect(0, 0, wnd->_internal.width, wnd->_internal.height)); + + /* Start the nuklear window */ if (nk_begin(wnd->_internal.nk_ctx, title, nk_rect(0, 0, wnd->_internal.width, wnd->_internal.height), window_flags)) { + /* Call user drawing callback */ if(wnd->cb_on_draw && !wnd->cb_on_draw(wnd->_internal.nk_ctx)) wnd->_internal.is_open = 0; - // Update window size + /* Update the windows window to reflect the nuklear windows size */ struct nk_rect bounds = nk_window_get_bounds(wnd->_internal.nk_ctx); if(bounds.w != wnd->_internal.width || bounds.h != wnd->_internal.height) SetWindowPos(wnd->_internal.window_handle, NULL, 0, 0, bounds.w, bounds.h, SWP_NOMOVE | SWP_NOOWNERZORDER); } else { - // Handle window closing + /* Nuklear window was closed. Handle close internally */ if(!wnd->cb_on_close || wnd->cb_on_close()) wnd->_internal.is_open = 0; } nk_end(wnd->_internal.nk_ctx); + + /* We no longer need the window size override flag to be set */ wnd->_internal.ws_override = 0; - // Final render pass - nk_gdi_render(wnd->_internal.nk_gdi_ctx, nk_rgb(30, 30, 30)); + /* Pass context to the nuklear gdi renderer */ + nk_gdi_render(wnd->_internal.nk_gdi_ctx, nk_rgb(0, 0, 0)); } return wnd->_internal.is_open; @@ -219,42 +234,44 @@ int nkgdi_window_update(struct nkgdi_window* wnd) LRESULT nkgdi_window_proc_setup(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) { - // Wait for setup message + /* Waiting to receive the NCCREATE message with the custom window data */ if (msg == WM_NCCREATE) { - // Get creation parameters & window pointer + /* Extracting the window context from message parameters */ CREATESTRUCT* ptrCr = (CREATESTRUCT*)lParam; struct nkgdi_window* nkgdi_wnd = (struct nkgdi_window*)ptrCr->lpCreateParams; - // Store pointer and new proc in window + /* Store the context in the window and redirect any further message to the run window proc*/ SetWindowLongPtr(wnd, GWLP_USERDATA, (LONG_PTR)nkgdi_wnd); SetWindowLongPtr(wnd, GWLP_WNDPROC, (LONG_PTR)&nkgdi_window_proc_run); - // Handled by window + /* Already call the run proc so that it gets the chance to handle NCCREATE as well */ return nkgdi_window_proc_run(wnd, msg, wParam, lParam); } - // Default handler + /* Until we get WM_NCCREATE windows is going to handle the messages */ return DefWindowProc(wnd, msg, wParam, lParam); } LRESULT nkgdi_window_proc_run(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) { - // Get window pointer + /* The window context is extracted from the window data */ struct nkgdi_window* nkwnd = (struct nkgdi_window*)GetWindowLongPtrW(wnd, GWLP_USERDATA); - // Switch on supplied message code + /* Switch on the message code to handle all required messages */ switch (msg) { - // Close event + /* Window close event */ case WM_CLOSE: + /* Call custom close callback */ if(!nkwnd->cb_on_close || nkwnd->cb_on_close()) nkwnd->_internal.is_open = 0; - return 0; // Will always be handled internaly + return 0; /* No default behaviour. We do it our own way */ - // While sizing + /* Window sizing event (is currently beeing sized) */ case WM_SIZING: { + /* Size of the client / active are is extracted and stored */ RECT cr; GetClientRect(wnd, &cr); nkwnd->_internal.width = cr.right - cr.left; @@ -262,30 +279,33 @@ LRESULT nkgdi_window_proc_run(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) } break; - // When sized + /* Window size event (done sizing, maximize, minimize, ...) */ case WM_SIZE: { - // Adjust maximize properties + /* Window was maximized */ if (wParam == SIZE_MAXIMIZED) { + /* Get the nearest monitor and retrive its details */ HMONITOR monitor = MonitorFromWindow(wnd, MONITOR_DEFAULTTOPRIMARY); MONITORINFO monitorInfo; monitorInfo.cbSize = sizeof(MONITORINFO); if (GetMonitorInfoW(monitor, &monitorInfo)) { + /* Adjust the window size and position by the monitor working area (without taskbar) */ nkwnd->_internal.height = monitorInfo.rcWork.bottom - monitorInfo.rcWork.top; nkwnd->_internal.width = monitorInfo.rcWork.right - monitorInfo.rcWork.left; - nkwnd->_internal.ws_override = 1; + nkwnd->_internal.ws_override = 1; /* Sizing was done without nuklear beeing aware. So we need to override it */ nkwnd->_internal.is_maximized = 1; SetWindowPos(wnd, NULL, 0, 0, nkwnd->_internal.width, nkwnd->_internal.height, SWP_NOMOVE | SWP_NOZORDER); } } + /* Window was restored (no longer maximized) */ else if (wParam == SIZE_RESTORED) { nkwnd->_internal.is_maximized = 0; } - // Compute new bounds + /* Always get the new bounds of the window */ RECT cr; GetClientRect(wnd, &cr); nkwnd->_internal.width = cr.right - cr.left; @@ -293,12 +313,13 @@ LRESULT nkgdi_window_proc_run(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) } break; - // When mouse start l-press (drag window) + /* Mouse started left click */ case WM_LBUTTONDOWN: { - if (HIWORD(lParam) <= 30 && nkwnd->allow_move) + /* Handle dragging when allowed, has titlebar and mouse is in titlebar (Y <= 30) */ + if (HIWORD(lParam) <= 30 && nkwnd->allow_move && nkwnd->has_titlebar) { - // Start dragging + /* Mark dragging internally and store mouse click offset */ nkwnd->_internal.is_draggin = 1; nkwnd->_internal.drag_offset.x = LOWORD(lParam); nkwnd->_internal.drag_offset.y = HIWORD(lParam); @@ -306,52 +327,59 @@ LRESULT nkgdi_window_proc_run(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) } break; - // When mouse stops l-press (drag window) + /* Mouse stoped left click */ case WM_LBUTTONUP: + /* No longer dragging the window */ nkwnd->_internal.is_draggin = 0; break; - // Mouse movement (dragging) + /* Mouse is moving on the window */ case WM_MOUSEMOVE: { + /* When we are dragging and are not maximized process dragging */ if (nkwnd->_internal.is_draggin && !nkwnd->_internal.is_maximized) { - // Get mouse postion and substract offset + /* Get the current global position of the mouse */ POINT cursorPos; GetCursorPos(&cursorPos); + /* Substract the internal offset */ cursorPos.x -= nkwnd->_internal.drag_offset.x; cursorPos.y -= nkwnd->_internal.drag_offset.y; - // Use as new position + /* Update position of out window and make sure window is in a movable state (= Restored) */ ShowWindow(wnd, SW_RESTORE); SetWindowPos(wnd, NULL, cursorPos.x, cursorPos.y, 0, 0, SWP_NOSIZE | SWP_NOZORDER); } } break; - // On mouse doubble click (maximize) + /* Mouse double clicked */ case WM_LBUTTONDBLCLK: { - if (HIWORD(lParam) <= 30 && nkwnd->allow_maximize) + /* Will only affect window when on the titlebar */ + if (HIWORD(lParam) <= 30 && nkwnd->allow_maximize && nkwnd->has_titlebar) { + /* When the window is already maximized restore it */ if (nkwnd->_internal.is_maximized) { ShowWindow(wnd, SW_RESTORE); } + /* Else we gonna do maximize it*/ else { ShowWindow(wnd, SW_MAXIMIZE); } + /* We overrideed the window size, make sure to affect the nk window as well */ nkwnd->_internal.ws_override = 1; } } break; } - // Send to nuklear + /* Allow nuklear to handle the message as well */ if (nkwnd->_internal.nk_gdi_ctx && nk_gdi_handle_event(nkwnd->_internal.nk_gdi_ctx, wnd, msg, wParam, lParam)) return 0; - // In case this is ever reached: Run default behaviour + /* In case we reach this line our code and nuklear did not respond to the message. Allow windows to handle it s*/ return DefWindowProc(wnd, msg, wParam, lParam); } From 5a75b319e47f328a928308cb634a6bf08eb66f9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wladislav=20=E3=83=B4=E3=83=A9=E3=83=89=20Artsimovich?= Date: Fri, 15 Apr 2022 13:19:10 +0900 Subject: [PATCH 005/106] Added nk_rule_horizontal() widget --- nuklear.h | 24 ++++++++++++++++++++++++ src/CHANGELOG | 1 + src/nuklear.h | 13 +++++++++++++ src/nuklear_window.c | 10 ++++++++++ 4 files changed, 48 insertions(+) diff --git a/nuklear.h b/nuklear.h index 9a33488..933da31 100644 --- a/nuklear.h +++ b/nuklear.h @@ -2003,6 +2003,19 @@ NK_API void nk_window_show(struct nk_context*, const char *name, enum nk_show_st /// __cond__ | condition that has to be met to actually commit the visbility state change */ NK_API void nk_window_show_if(struct nk_context*, const char *name, enum nk_show_states, int cond); +/*/// #### nk_window_show_if +/// Line for visual seperation. Draws a line with thickness determined by the current row height. +/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c +/// void nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, NK_BOOL rounding) +/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +/// +/// Parameter | Description +/// ----------------|------------------------------------------------------- +/// __ctx__ | Must point to an previously initialized `nk_context` struct +/// __color__ | Color of the horizontal line +/// __rounding__ | Whether or not to make the line round +*/ +NK_API void nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, NK_BOOL rounding) /* ============================================================================= * * LAYOUT @@ -20688,6 +20701,16 @@ nk_window_set_focus(struct nk_context *ctx, const char *name) ctx->active = win; } +NK_API void +nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, NK_BOOL rounding) +{ + struct nk_rect space; + enum nk_widget_layout_states state = nk_widget(&space, ctx); + struct nk_command_buffer *canvas = nk_window_get_canvas(ctx); + if (!state) return; + nk_fill_rect(canvas, space, rounding && space.h > 1.5f ? space.h / 2.0f : 0, color); +} + @@ -29629,6 +29652,7 @@ nk_tooltipfv(struct nk_context *ctx, const char *fmt, va_list args) /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// +/// - 2022/02/03 (4.9.7) - Added nk_rule_horizontal() widget /// - 2022/02/03 (4.9.6) - Allow overriding the NK_INV_SQRT function, similar to NK_SIN and NK_COS /// - 2021/12/22 (4.9.5) - Revert layout bounds not accounting for padding due to regressions /// - 2021/12/22 (4.9.4) - Fix checking hovering when window is minimized diff --git a/src/CHANGELOG b/src/CHANGELOG index 4be9f04..95c0879 100644 --- a/src/CHANGELOG +++ b/src/CHANGELOG @@ -7,6 +7,7 @@ /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// +/// - 2022/04/15 (4.9.7) - Added nk_rule_horizontal() widget /// - 2022/02/03 (4.9.6) - Allow overriding the NK_INV_SQRT function, similar to NK_SIN and NK_COS /// - 2021/12/22 (4.9.5) - Revert layout bounds not accounting for padding due to regressions /// - 2021/12/22 (4.9.4) - Fix checking hovering when window is minimized diff --git a/src/nuklear.h b/src/nuklear.h index b97c95c..d9bd435 100644 --- a/src/nuklear.h +++ b/src/nuklear.h @@ -1782,6 +1782,19 @@ NK_API void nk_window_show(struct nk_context*, const char *name, enum nk_show_st /// __cond__ | condition that has to be met to actually commit the visbility state change */ NK_API void nk_window_show_if(struct nk_context*, const char *name, enum nk_show_states, int cond); +/*/// #### nk_window_show_if +/// Line for visual seperation. Draws a line with thickness determined by the current row height. +/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c +/// void nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, NK_BOOL rounding) +/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +/// +/// Parameter | Description +/// ----------------|------------------------------------------------------- +/// __ctx__ | Must point to an previously initialized `nk_context` struct +/// __color__ | Color of the horizontal line +/// __rounding__ | Whether or not to make the line round +*/ +NK_API void nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, NK_BOOL rounding) /* ============================================================================= * * LAYOUT diff --git a/src/nuklear_window.c b/src/nuklear_window.c index 486b912..e5e90b7 100644 --- a/src/nuklear_window.c +++ b/src/nuklear_window.c @@ -669,3 +669,13 @@ nk_window_set_focus(struct nk_context *ctx, const char *name) } ctx->active = win; } + +NK_API void +nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, NK_BOOL rounding) +{ + struct nk_rect space; + enum nk_widget_layout_states state = nk_widget(&space, ctx); + struct nk_command_buffer *canvas = nk_window_get_canvas(ctx); + if (!state) return; + nk_fill_rect(canvas, space, rounding && space.h > 1.5f ? space.h / 2.0f : 0, color); +} From 398e338bff91e4f7a50c842ad6a2d02371c100d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wladislav=20=E3=83=B4=E3=83=A9=E3=83=89=20Artsimovich?= Date: Fri, 15 Apr 2022 13:27:39 +0900 Subject: [PATCH 006/106] Forgot to regenerate nuklear.h --- nuklear.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nuklear.h b/nuklear.h index 933da31..b3c9528 100644 --- a/nuklear.h +++ b/nuklear.h @@ -29652,7 +29652,7 @@ nk_tooltipfv(struct nk_context *ctx, const char *fmt, va_list args) /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// -/// - 2022/02/03 (4.9.7) - Added nk_rule_horizontal() widget +/// - 2022/04/15 (4.9.7) - Added nk_rule_horizontal() widget /// - 2022/02/03 (4.9.6) - Allow overriding the NK_INV_SQRT function, similar to NK_SIN and NK_COS /// - 2021/12/22 (4.9.5) - Revert layout bounds not accounting for padding due to regressions /// - 2021/12/22 (4.9.4) - Fix checking hovering when window is minimized From cb0e05beeaf665f26172e35e3ef29fd3bd5e59fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wladislav=20=E3=83=B4=E3=83=A9=E3=83=89=20Artsimovich?= Date: Fri, 15 Apr 2022 13:35:13 +0900 Subject: [PATCH 007/106] Forgot the semicolon in nuklear.h --- nuklear.h | 5 ++--- src/nuklear.h | 2 +- src/nuklear_window.c | 3 +-- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/nuklear.h b/nuklear.h index b3c9528..e58e3d6 100644 --- a/nuklear.h +++ b/nuklear.h @@ -2015,7 +2015,7 @@ NK_API void nk_window_show_if(struct nk_context*, const char *name, enum nk_show /// __color__ | Color of the horizontal line /// __rounding__ | Whether or not to make the line round */ -NK_API void nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, NK_BOOL rounding) +NK_API void nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, nk_bool rounding); /* ============================================================================= * * LAYOUT @@ -20700,9 +20700,8 @@ nk_window_set_focus(struct nk_context *ctx, const char *name) } ctx->active = win; } - NK_API void -nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, NK_BOOL rounding) +nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, nk_bool rounding) { struct nk_rect space; enum nk_widget_layout_states state = nk_widget(&space, ctx); diff --git a/src/nuklear.h b/src/nuklear.h index d9bd435..615feeb 100644 --- a/src/nuklear.h +++ b/src/nuklear.h @@ -1794,7 +1794,7 @@ NK_API void nk_window_show_if(struct nk_context*, const char *name, enum nk_show /// __color__ | Color of the horizontal line /// __rounding__ | Whether or not to make the line round */ -NK_API void nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, NK_BOOL rounding) +NK_API void nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, nk_bool rounding); /* ============================================================================= * * LAYOUT diff --git a/src/nuklear_window.c b/src/nuklear_window.c index e5e90b7..e69ad39 100644 --- a/src/nuklear_window.c +++ b/src/nuklear_window.c @@ -669,9 +669,8 @@ nk_window_set_focus(struct nk_context *ctx, const char *name) } ctx->active = win; } - NK_API void -nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, NK_BOOL rounding) +nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, nk_bool rounding) { struct nk_rect space; enum nk_widget_layout_states state = nk_widget(&space, ctx); From 50277a1c39e3077aaf42bf814f5d5363a7dbc1a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ludwig=20F=C3=BCchsl?= Date: Sun, 29 May 2022 01:47:00 +0200 Subject: [PATCH 008/106] Changed windows include to lowercase --- demo/gdi_native_nuklear/main.c | 2 +- demo/gdi_native_nuklear/window.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/demo/gdi_native_nuklear/main.c b/demo/gdi_native_nuklear/main.c index b6cb6a9..349adea 100644 --- a/demo/gdi_native_nuklear/main.c +++ b/demo/gdi_native_nuklear/main.c @@ -1,4 +1,4 @@ -#include +#include #pragma comment(linker,"\"/manifestdependency:type='win32' \ name='Microsoft.Windows.Common-Controls' version='6.0.0.0' \ diff --git a/demo/gdi_native_nuklear/window.h b/demo/gdi_native_nuklear/window.h index 0db572f..f78d574 100644 --- a/demo/gdi_native_nuklear/window.h +++ b/demo/gdi_native_nuklear/window.h @@ -3,7 +3,7 @@ #define NK_GDI_WINDOW_CLS L"WNDCLS_NkGdi" -#include +#include /* Functin pointer types for window callbacks */ typedef int(*nkgdi_window_func_close)(void); From adeb2a720fd4836b5e69e075e277866f3c3e80c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ludwig=20F=C3=BCchsl?= Date: Mon, 30 May 2022 22:49:12 +0200 Subject: [PATCH 009/106] Added wWinMain comment --- demo/gdi_native_nuklear/main.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/demo/gdi_native_nuklear/main.c b/demo/gdi_native_nuklear/main.c index 349adea..d12f972 100644 --- a/demo/gdi_native_nuklear/main.c +++ b/demo/gdi_native_nuklear/main.c @@ -84,17 +84,19 @@ int drawCallback(struct nk_context* ctx) return 1; } -/* Main entry point (Windows wchar_t) */ +/* Main entry point - wWinMain used for UNICODE + * (You can also use _tWinMain(...) to automaticaly use the ASCII or WIDE char entry point base on your build) + */ INT WINAPI wWinMain(HINSTANCE _In_ hInstance, HINSTANCE _In_opt_ hPrevInstance, PWSTR _In_ cmdArgs, INT _In_ cmdShow) { /* Call this first to setup all required prerequisites */ nkgdi_window_init(); - + /* Preparing two window contexts */ struct nkgdi_window w1, w2; memset(&w1, 0x0, sizeof(struct nkgdi_window)); memset(&w2, 0x0, sizeof(struct nkgdi_window)); - + /* Configure and create window 1. * Note: You can allways change the direct accesible parameters later as well! */ From ed3ff76d0eb8c2db2e9127075ad666c829f14bdf Mon Sep 17 00:00:00 2001 From: ryuukk Date: Mon, 27 Jun 2022 00:15:14 +0200 Subject: [PATCH 010/106] rename null texture field to tex_null --- src/nuklear.h | 4 ++-- src/nuklear_vertex.c | 26 +++++++++++++------------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/nuklear.h b/src/nuklear.h index 67b2aa9..4ced6b9 100644 --- a/src/nuklear.h +++ b/src/nuklear.h @@ -906,7 +906,7 @@ NK_API void nk_input_end(struct nk_context*); /// cfg.curve_segment_count = 22; /// cfg.arc_segment_count = 22; /// cfg.global_alpha = 1.0f; -/// cfg.null = dev->null; +/// cfg.tex_null = dev->tex_null; /// // /// // setup buffers and convert /// struct nk_buffer cmds, verts, idx; @@ -956,7 +956,7 @@ struct nk_convert_config { unsigned circle_segment_count; /* number of segments used for circles: default to 22 */ unsigned arc_segment_count; /* number of segments used for arcs: default to 22 */ unsigned curve_segment_count; /* number of segments used for curves: default to 22 */ - struct nk_draw_null_texture null; /* handle to texture with a white pixel for shape drawing */ + struct nk_draw_null_texture tex_null; /* handle to texture with a white pixel for shape drawing */ const struct nk_draw_vertex_layout_element *vertex_layout; /* describes the vertex output format and packing */ nk_size vertex_size; /* sizeof one vertex for vertex packing */ nk_size vertex_alignment; /* vertex alignment: Can be obtained by NK_ALIGNOF */ diff --git a/src/nuklear_vertex.c b/src/nuklear_vertex.c index b98eb1e..ce1f94e 100644 --- a/src/nuklear_vertex.c +++ b/src/nuklear_vertex.c @@ -177,7 +177,7 @@ nk_draw_list_add_clip(struct nk_draw_list *list, struct nk_rect rect) NK_ASSERT(list); if (!list) return; if (!list->cmd_count) { - nk_draw_list_push_command(list, rect, list->config.null.texture); + nk_draw_list_push_command(list, rect, list->config.tex_null.texture); } else { struct nk_draw_command *prev = nk_draw_list_command_last(list); if (prev->elem_count == 0) @@ -532,7 +532,7 @@ nk_draw_list_stroke_poly_line(struct nk_draw_list *list, const struct nk_vec2 *p /* fill vertices */ for (i = 0; i < points_count; ++i) { - const struct nk_vec2 uv = list->config.null.uv; + const struct nk_vec2 uv = list->config.tex_null.uv; vtx = nk_draw_vertex(vtx, &list->config, points[i], uv, col); vtx = nk_draw_vertex(vtx, &list->config, temp[i*2+0], uv, col_trans); vtx = nk_draw_vertex(vtx, &list->config, temp[i*2+1], uv, col_trans); @@ -597,7 +597,7 @@ nk_draw_list_stroke_poly_line(struct nk_draw_list *list, const struct nk_vec2 *p /* add vertices */ for (i = 0; i < points_count; ++i) { - const struct nk_vec2 uv = list->config.null.uv; + const struct nk_vec2 uv = list->config.tex_null.uv; vtx = nk_draw_vertex(vtx, &list->config, temp[i*4+0], uv, col_trans); vtx = nk_draw_vertex(vtx, &list->config, temp[i*4+1], uv, col); vtx = nk_draw_vertex(vtx, &list->config, temp[i*4+2], uv, col); @@ -618,7 +618,7 @@ nk_draw_list_stroke_poly_line(struct nk_draw_list *list, const struct nk_vec2 *p for (i1 = 0; i1 < count; ++i1) { float dx, dy; - const struct nk_vec2 uv = list->config.null.uv; + const struct nk_vec2 uv = list->config.tex_null.uv; const nk_size i2 = ((i1+1) == points_count) ? 0 : i1 + 1; const struct nk_vec2 p1 = points[i1]; const struct nk_vec2 p2 = points[i2]; @@ -728,7 +728,7 @@ nk_draw_list_fill_poly_convex(struct nk_draw_list *list, /* add vertices + indexes */ for (i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) { - const struct nk_vec2 uv = list->config.null.uv; + const struct nk_vec2 uv = list->config.tex_null.uv; struct nk_vec2 n0 = normals[i0]; struct nk_vec2 n1 = normals[i1]; struct nk_vec2 dm = nk_vec2_muls(nk_vec2_add(n0, n1), 0.5f); @@ -765,7 +765,7 @@ nk_draw_list_fill_poly_convex(struct nk_draw_list *list, if (!vtx || !ids) return; for (i = 0; i < vtx_count; ++i) - vtx = nk_draw_vertex(vtx, &list->config, points[i], list->config.null.uv, col); + vtx = nk_draw_vertex(vtx, &list->config, points[i], list->config.tex_null.uv, col); for (i = 2; i < points_count; ++i) { ids[0] = (nk_draw_index)index; ids[1] = (nk_draw_index)(index+ i - 1); @@ -794,8 +794,8 @@ nk_draw_list_path_line_to(struct nk_draw_list *list, struct nk_vec2 pos) nk_draw_list_add_clip(list, nk_null_rect); cmd = nk_draw_list_command_last(list); - if (cmd && cmd->texture.ptr != list->config.null.texture.ptr) - nk_draw_list_push_image(list, list->config.null.texture); + if (cmd && cmd->texture.ptr != list->config.tex_null.texture.ptr) + nk_draw_list_push_image(list, list->config.tex_null.texture); points = nk_draw_list_alloc_path(list, 1); if (!points) return; @@ -997,7 +997,7 @@ nk_draw_list_fill_rect_multi_color(struct nk_draw_list *list, struct nk_rect rec NK_ASSERT(list); if (!list) return; - nk_draw_list_push_image(list, list->config.null.texture); + nk_draw_list_push_image(list, list->config.tex_null.texture); index = (nk_draw_index)list->vertex_count; vtx = nk_draw_list_alloc_vertices(list, 4); idx = nk_draw_list_alloc_elements(list, 6); @@ -1007,10 +1007,10 @@ nk_draw_list_fill_rect_multi_color(struct nk_draw_list *list, struct nk_rect rec idx[2] = (nk_draw_index)(index+2); idx[3] = (nk_draw_index)(index+0); idx[4] = (nk_draw_index)(index+2); idx[5] = (nk_draw_index)(index+3); - vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x, rect.y), list->config.null.uv, col_left); - vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x + rect.w, rect.y), list->config.null.uv, col_top); - vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x + rect.w, rect.y + rect.h), list->config.null.uv, col_right); - vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x, rect.y + rect.h), list->config.null.uv, col_bottom); + vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x, rect.y), list->config.tex_null.uv, col_left); + vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x + rect.w, rect.y), list->config.tex_null.uv, col_top); + vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x + rect.w, rect.y + rect.h), list->config.tex_null.uv, col_right); + vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x, rect.y + rect.h), list->config.tex_null.uv, col_bottom); } NK_API void nk_draw_list_fill_triangle(struct nk_draw_list *list, struct nk_vec2 a, From ec4acc7cf4e6e53d604d17e6cab5019233a221cc Mon Sep 17 00:00:00 2001 From: Rob Loach Date: Sat, 30 Jul 2022 17:38:10 -0400 Subject: [PATCH 011/106] Rename the null variable to tex_null --- demo/d3d11/nuklear_d3d11.h | 8 +++--- demo/d3d12/nuklear_d3d12.h | 24 ++++++++-------- demo/d3d9/nuklear_d3d9.h | 6 ++-- demo/glfw_opengl2/nuklear_glfw_gl2.h | 2 +- demo/glfw_opengl3/nuklear_glfw_gl3.h | 2 +- demo/glfw_opengl4/nuklear_glfw_gl4.h | 2 +- demo/sdl_opengl2/nuklear_sdl_gl2.h | 2 +- demo/sdl_opengl3/nuklear_sdl_gl3.h | 2 +- demo/sdl_opengles2/nuklear_sdl_gles2.h | 8 +++--- demo/sdl_renderer/nuklear_sdl_renderer.h | 2 +- demo/sfml_opengl2/nuklear_sfml_gl2.h | 4 +-- demo/sfml_opengl3/nuklear_sfml_gl3.h | 4 +-- demo/x11_opengl2/nuklear_xlib_gl2.h | 2 +- demo/x11_opengl3/nuklear_xlib_gl3.h | 2 +- example/canvas.c | 36 ++++++++++++------------ example/extended.c | 2 +- example/file_browser.c | 2 +- example/skinning.c | 2 +- nuklear.h | 31 ++++++++++---------- src/CHANGELOG | 1 + 20 files changed, 73 insertions(+), 71 deletions(-) diff --git a/demo/d3d11/nuklear_d3d11.h b/demo/d3d11/nuklear_d3d11.h index b716632..46c615d 100644 --- a/demo/d3d11/nuklear_d3d11.h +++ b/demo/d3d11/nuklear_d3d11.h @@ -137,7 +137,7 @@ nk_d3d11_render(ID3D11DeviceContext *context, enum nk_anti_aliasing AA) config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; - config.null = d3d11.null; + config.tex_null = d3d11.null; {/* setup buffers to load vertices and elements */ struct nk_buffer vbuf, ibuf; @@ -373,7 +373,7 @@ nk_d3d11_clipboard_paste(nk_handle usr, struct nk_text_edit *edit) (void)usr; if (IsClipboardFormatAvailable(CF_UNICODETEXT) && OpenClipboard(NULL)) { - HGLOBAL mem = GetClipboardData(CF_UNICODETEXT); + HGLOBAL mem = GetClipboardData(CF_UNICODETEXT); if (mem) { SIZE_T size = GlobalSize(mem) - 1; @@ -393,7 +393,7 @@ nk_d3d11_clipboard_paste(nk_handle usr, struct nk_text_edit *edit) free(utf8); } } - GlobalUnlock(mem); + GlobalUnlock(mem); } } } @@ -419,7 +419,7 @@ nk_d3d11_clipboard_copy(nk_handle usr, const char *text, int len) MultiByteToWideChar(CP_UTF8, 0, text, len, wstr, wsize); wstr[wsize] = 0; GlobalUnlock(mem); - SetClipboardData(CF_UNICODETEXT, mem); + SetClipboardData(CF_UNICODETEXT, mem); } } } diff --git a/demo/d3d12/nuklear_d3d12.h b/demo/d3d12/nuklear_d3d12.h index a235d69..1660d7b 100644 --- a/demo/d3d12/nuklear_d3d12.h +++ b/demo/d3d12/nuklear_d3d12.h @@ -2,7 +2,7 @@ * Nuklear - 1.32.0 - public domain * no warrenty implied; use at your own risk. * authored from 2015-2016 by Micha Mettke - * + * * D3D12 backend created by Ludwig Fuechsl (2022) */ /* @@ -30,7 +30,7 @@ NK_API struct nk_context *nk_d3d12_init(ID3D12Device *device, int width, int hei NK_API void nk_d3d12_font_stash_begin(struct nk_font_atlas **atlas); /* * USAGE: - * - Call this function after a call to nk_d3d12_font_stash_begin(...) when all fonts have been loaded and configured. + * - Call this function after a call to nk_d3d12_font_stash_begin(...) when all fonts have been loaded and configured. * - This function will place commands on the supplied ID3D12GraphicsCommandList. * - This function will allocate temporary data that is required until the command list has finish executing. The temporary data can be free by calling nk_d3d12_font_stash_cleanup(...) */ @@ -96,7 +96,7 @@ NK_API void nk_d3d12_shutdown(void); #include "nuklear_d3d12_vertex_shader.h" #include "nuklear_d3d12_pixel_shader.h" -struct nk_d3d12_vertex +struct nk_d3d12_vertex { float position[2]; float uv[2]; @@ -198,7 +198,7 @@ nk_d3d12_render(ID3D12GraphicsCommandList *command_list, enum nk_anti_aliasing A config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; - config.null = d3d12.null; + config.tex_null = d3d12.null; struct nk_buffer vbuf, ibuf; nk_buffer_init_fixed(&vbuf, &ptr_data[sizeof(float) * 4 * 4], (size_t)d3d12.max_vertex_buffer); @@ -505,7 +505,7 @@ nk_d3d12_clipboard_paste(nk_handle usr, struct nk_text_edit *edit) (void)usr; if (IsClipboardFormatAvailable(CF_UNICODETEXT) && OpenClipboard(NULL)) { - HGLOBAL mem = GetClipboardData(CF_UNICODETEXT); + HGLOBAL mem = GetClipboardData(CF_UNICODETEXT); if (mem) { SIZE_T size = GlobalSize(mem) - 1; @@ -525,7 +525,7 @@ nk_d3d12_clipboard_paste(nk_handle usr, struct nk_text_edit *edit) free(utf8); } } - GlobalUnlock(mem); + GlobalUnlock(mem); } } } @@ -551,7 +551,7 @@ nk_d3d12_clipboard_copy(nk_handle usr, const char *text, int len) MultiByteToWideChar(CP_UTF8, 0, text, len, wstr, wsize); wstr[wsize] = 0; GlobalUnlock(mem); - SetClipboardData(CF_UNICODETEXT, mem); + SetClipboardData(CF_UNICODETEXT, mem); } } } @@ -566,7 +566,7 @@ nk_d3d12_init(ID3D12Device *device, int width, int height, unsigned int max_vert D3D12_CONSTANT_BUFFER_VIEW_DESC cbv; D3D12_CPU_DESCRIPTOR_HANDLE cbv_handle; - /* Do plain object / ref copys */ + /* Do plain object / ref copys */ d3d12.max_vertex_buffer = max_vertex_buffer; d3d12.max_index_buffer = max_index_buffer; d3d12.max_user_textures = max_user_textures; @@ -679,7 +679,7 @@ nk_d3d12_init(ID3D12Device *device, int width, int height, unsigned int max_vert /* Get address of first handle (CPU and GPU) */ ID3D12DescriptorHeap_GetCPUDescriptorHandleForHeapStart(d3d12.desc_heap, &d3d12.cpu_descriptor_handle); ID3D12DescriptorHeap_GetGPUDescriptorHandleForHeapStart(d3d12.desc_heap, &d3d12.gpu_descriptor_handle); - + /* Get addresses of vertex & index buffers */ d3d12.gpu_vertex_buffer_address = ID3D12Resource_GetGPUVirtualAddress(d3d12.vertex_buffer); d3d12.gpu_index_buffer_address = ID3D12Resource_GetGPUVirtualAddress(d3d12.index_buffer); @@ -870,7 +870,7 @@ nk_d3d12_font_stash_end(ID3D12GraphicsCommandList *command_list) nk_style_set_font(&d3d12.ctx, &d3d12.atlas.default_font->handle); } -NK_API +NK_API void nk_d3d12_font_stash_cleanup() { if(d3d12.font_upload_buffer) @@ -880,7 +880,7 @@ void nk_d3d12_font_stash_cleanup() } } -NK_API +NK_API nk_bool nk_d3d12_set_user_texture(unsigned int index, ID3D12Resource* texture, const D3D12_SHADER_RESOURCE_VIEW_DESC* description, nk_handle* handle_out) { nk_bool result = nk_false; @@ -919,7 +919,7 @@ void nk_d3d12_shutdown(void) ID3D12Resource_Release(d3d12.const_buffer); ID3D12Resource_Release(d3d12.index_buffer); ID3D12Resource_Release(d3d12.vertex_buffer); - if(d3d12.font_texture) + if(d3d12.font_texture) ID3D12Resource_Release(d3d12.font_texture); if(d3d12.font_upload_buffer) ID3D12Resource_Release(d3d12.font_upload_buffer); diff --git a/demo/d3d9/nuklear_d3d9.h b/demo/d3d9/nuklear_d3d9.h index 9a6fe4c..1aee6ba 100644 --- a/demo/d3d9/nuklear_d3d9.h +++ b/demo/d3d9/nuklear_d3d9.h @@ -150,7 +150,7 @@ nk_d3d9_render(enum nk_anti_aliasing AA) config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; - config.null = d3d9.null; + config.tex_null = d3d9.null; /* convert shapes into vertexes */ nk_buffer_init_default(&vbuf); @@ -468,7 +468,7 @@ nk_d3d9_clipboard_paste(nk_handle usr, struct nk_text_edit *edit) } } - GlobalUnlock(mem); + GlobalUnlock(mem); CloseClipboard(); } @@ -491,7 +491,7 @@ nk_d3d9_clipboard_copy(nk_handle usr, const char *text, int len) MultiByteToWideChar(CP_UTF8, 0, text, len, wstr, wsize); wstr[wsize] = 0; GlobalUnlock(mem); - SetClipboardData(CF_UNICODETEXT, mem); + SetClipboardData(CF_UNICODETEXT, mem); } } } diff --git a/demo/glfw_opengl2/nuklear_glfw_gl2.h b/demo/glfw_opengl2/nuklear_glfw_gl2.h index 6eb43cb..97e3b6e 100644 --- a/demo/glfw_opengl2/nuklear_glfw_gl2.h +++ b/demo/glfw_opengl2/nuklear_glfw_gl2.h @@ -140,7 +140,7 @@ nk_glfw3_render(enum nk_anti_aliasing AA) config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_glfw_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_glfw_vertex); - config.null = dev->null; + config.tex_null = dev->null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/demo/glfw_opengl3/nuklear_glfw_gl3.h b/demo/glfw_opengl3/nuklear_glfw_gl3.h index fcc8335..573b76d 100644 --- a/demo/glfw_opengl3/nuklear_glfw_gl3.h +++ b/demo/glfw_opengl3/nuklear_glfw_gl3.h @@ -266,7 +266,7 @@ nk_glfw3_render(struct nk_glfw* glfw, enum nk_anti_aliasing AA, int max_vertex_b config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_glfw_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_glfw_vertex); - config.null = dev->null; + config.tex_null = dev->null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/demo/glfw_opengl4/nuklear_glfw_gl4.h b/demo/glfw_opengl4/nuklear_glfw_gl4.h index 6e77627..6f1e259 100644 --- a/demo/glfw_opengl4/nuklear_glfw_gl4.h +++ b/demo/glfw_opengl4/nuklear_glfw_gl4.h @@ -407,7 +407,7 @@ nk_glfw3_render(enum nk_anti_aliasing AA) config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_glfw_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_glfw_vertex); - config.null = dev->null; + config.tex_null = dev->null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/demo/sdl_opengl2/nuklear_sdl_gl2.h b/demo/sdl_opengl2/nuklear_sdl_gl2.h index 93ca705..7850d65 100644 --- a/demo/sdl_opengl2/nuklear_sdl_gl2.h +++ b/demo/sdl_opengl2/nuklear_sdl_gl2.h @@ -120,7 +120,7 @@ nk_sdl_render(enum nk_anti_aliasing AA) config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_sdl_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_sdl_vertex); - config.null = dev->null; + config.tex_null = dev->null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/demo/sdl_opengl3/nuklear_sdl_gl3.h b/demo/sdl_opengl3/nuklear_sdl_gl3.h index 5a89869..26036f1 100644 --- a/demo/sdl_opengl3/nuklear_sdl_gl3.h +++ b/demo/sdl_opengl3/nuklear_sdl_gl3.h @@ -247,7 +247,7 @@ nk_sdl_render(enum nk_anti_aliasing AA, int max_vertex_buffer, int max_element_b config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_sdl_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_sdl_vertex); - config.null = dev->null; + config.tex_null = dev->null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/demo/sdl_opengles2/nuklear_sdl_gles2.h b/demo/sdl_opengles2/nuklear_sdl_gles2.h index e2f297f..592e0db 100644 --- a/demo/sdl_opengles2/nuklear_sdl_gles2.h +++ b/demo/sdl_opengles2/nuklear_sdl_gles2.h @@ -103,7 +103,7 @@ nk_sdl_device_create(void) "}\n"; struct nk_sdl_device *dev = &sdl.ogl; - + nk_buffer_init_default(&dev->cmds); dev->prog = glCreateProgram(); dev->vert_shdr = glCreateShader(GL_VERTEX_SHADER); @@ -133,7 +133,7 @@ nk_sdl_device_create(void) dev->vp = offsetof(struct nk_sdl_vertex, position); dev->vt = offsetof(struct nk_sdl_vertex, uv); dev->vc = offsetof(struct nk_sdl_vertex, col); - + /* Allocate buffers */ glGenBuffers(1, &dev->vbo); glGenBuffers(1, &dev->ebo); @@ -214,7 +214,7 @@ nk_sdl_render(enum nk_anti_aliasing AA, int max_vertex_buffer, int max_element_b /* Bind buffers */ glBindBuffer(GL_ARRAY_BUFFER, dev->vbo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, dev->ebo); - + { /* buffer setup */ glEnableVertexAttribArray((GLuint)dev->attrib_pos); @@ -245,7 +245,7 @@ nk_sdl_render(enum nk_anti_aliasing AA, int max_vertex_buffer, int max_element_b config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_sdl_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_sdl_vertex); - config.null = dev->null; + config.tex_null = dev->null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/demo/sdl_renderer/nuklear_sdl_renderer.h b/demo/sdl_renderer/nuklear_sdl_renderer.h index bd85044..702d56c 100644 --- a/demo/sdl_renderer/nuklear_sdl_renderer.h +++ b/demo/sdl_renderer/nuklear_sdl_renderer.h @@ -113,7 +113,7 @@ nk_sdl_render(enum nk_anti_aliasing AA) config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_sdl_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_sdl_vertex); - config.null = dev->null; + config.tex_null = dev->null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/demo/sfml_opengl2/nuklear_sfml_gl2.h b/demo/sfml_opengl2/nuklear_sfml_gl2.h index 728d899..1f9fcd1 100644 --- a/demo/sfml_opengl2/nuklear_sfml_gl2.h +++ b/demo/sfml_opengl2/nuklear_sfml_gl2.h @@ -59,7 +59,7 @@ nk_sfml_device_upload_atlas(const void* image, int width, int height) glBindTexture(GL_TEXTURE_2D, dev->font_tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei)width, (GLsizei)height, 0, + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei)width, (GLsizei)height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image); } @@ -118,7 +118,7 @@ nk_sfml_render(enum nk_anti_aliasing AA) config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_sfml_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_sfml_vertex); - config.null = dev->null; + config.tex_null = dev->null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/demo/sfml_opengl3/nuklear_sfml_gl3.h b/demo/sfml_opengl3/nuklear_sfml_gl3.h index 27d7511..0038b34 100644 --- a/demo/sfml_opengl3/nuklear_sfml_gl3.h +++ b/demo/sfml_opengl3/nuklear_sfml_gl3.h @@ -248,7 +248,7 @@ nk_sfml_render(enum nk_anti_aliasing AA, int max_vertex_buffer, int max_element_ config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_sfml_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_sfml_vertex); - config.null = dev->null; + config.tex_null = dev->null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; @@ -451,7 +451,7 @@ nk_sfml_handle_event(sf::Event* evt) return 1; } else if(evt->type == sf::Event::TextEntered) { /* 8 ~ backspace */ - if (evt->text.unicode != 8) { + if (evt->text.unicode != 8) { nk_input_unicode(ctx, evt->text.unicode); } return 1; diff --git a/demo/x11_opengl2/nuklear_xlib_gl2.h b/demo/x11_opengl2/nuklear_xlib_gl2.h index de720f4..9e1382e 100644 --- a/demo/x11_opengl2/nuklear_xlib_gl2.h +++ b/demo/x11_opengl2/nuklear_xlib_gl2.h @@ -153,7 +153,7 @@ nk_x11_render(enum nk_anti_aliasing AA, int max_vertex_buffer, int max_element_b config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_x11_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_x11_vertex); - config.null = dev->null; + config.tex_null = dev->null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/demo/x11_opengl3/nuklear_xlib_gl3.h b/demo/x11_opengl3/nuklear_xlib_gl3.h index bc25109..85ff2ae 100644 --- a/demo/x11_opengl3/nuklear_xlib_gl3.h +++ b/demo/x11_opengl3/nuklear_xlib_gl3.h @@ -536,7 +536,7 @@ nk_x11_render(enum nk_anti_aliasing AA, int max_vertex_buffer, int max_element_b config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_x11_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_x11_vertex); - config.null = dev->null; + config.tex_null = dev->null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/example/canvas.c b/example/canvas.c index 5f651cc..d8a1534 100644 --- a/example/canvas.c +++ b/example/canvas.c @@ -78,24 +78,24 @@ die(const char *fmt, ...) exit(EXIT_FAILURE); } -static struct nk_image -icon_load(const char *filename) -{ - int x,y,n; - GLuint tex; - unsigned char *data = stbi_load(filename, &x, &y, &n, 0); - if (!data) die("[SDL]: failed to load image: %s", filename); +static struct nk_image +icon_load(const char *filename) +{ + int x,y,n; + GLuint tex; + unsigned char *data = stbi_load(filename, &x, &y, &n, 0); + if (!data) die("[SDL]: failed to load image: %s", filename); - glGenTextures(1, &tex); - glBindTexture(GL_TEXTURE_2D, tex); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_NEAREST); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, x, y, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); - glGenerateMipmap(GL_TEXTURE_2D); - stbi_image_free(data); - return nk_image_id((int)tex); + glGenTextures(1, &tex); + glBindTexture(GL_TEXTURE_2D, tex); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_NEAREST); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, x, y, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); + glGenerateMipmap(GL_TEXTURE_2D); + stbi_image_free(data); + return nk_image_id((int)tex); } */ @@ -262,7 +262,7 @@ device_draw(struct device *dev, struct nk_context *ctx, int width, int height, config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_glfw_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_glfw_vertex); - config.null = dev->null; + config.tex_null = dev->null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/example/extended.c b/example/extended.c index f1ae3c1..41f2fa2 100644 --- a/example/extended.c +++ b/example/extended.c @@ -685,7 +685,7 @@ device_draw(struct device *dev, struct nk_context *ctx, int width, int height, config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_glfw_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_glfw_vertex); - config.null = dev->null; + config.tex_null = dev->null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/example/file_browser.c b/example/file_browser.c index 7286d5f..60e6ac2 100644 --- a/example/file_browser.c +++ b/example/file_browser.c @@ -722,7 +722,7 @@ device_draw(struct device *dev, struct nk_context *ctx, int width, int height, config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_glfw_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_glfw_vertex); - config.null = dev->null; + config.tex_null = dev->null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/example/skinning.c b/example/skinning.c index 54f71e4..b54b03d 100644 --- a/example/skinning.c +++ b/example/skinning.c @@ -286,7 +286,7 @@ device_draw(struct device *dev, struct nk_context *ctx, int width, int height, config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_glfw_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_glfw_vertex); - config.null = dev->null; + config.tex_null = dev->null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/nuklear.h b/nuklear.h index aef8f7f..90d8b2d 100644 --- a/nuklear.h +++ b/nuklear.h @@ -1127,7 +1127,7 @@ NK_API void nk_input_end(struct nk_context*); /// cfg.curve_segment_count = 22; /// cfg.arc_segment_count = 22; /// cfg.global_alpha = 1.0f; -/// cfg.null = dev->null; +/// cfg.tex_null = dev->tex_null; /// // /// // setup buffers and convert /// struct nk_buffer cmds, verts, idx; @@ -1177,7 +1177,7 @@ struct nk_convert_config { unsigned circle_segment_count; /* number of segments used for circles: default to 22 */ unsigned arc_segment_count; /* number of segments used for arcs: default to 22 */ unsigned curve_segment_count; /* number of segments used for curves: default to 22 */ - struct nk_draw_null_texture null; /* handle to texture with a white pixel for shape drawing */ + struct nk_draw_null_texture tex_null; /* handle to texture with a white pixel for shape drawing */ const struct nk_draw_vertex_layout_element *vertex_layout; /* describes the vertex output format and packing */ nk_size vertex_size; /* sizeof one vertex for vertex packing */ nk_size vertex_alignment; /* vertex alignment: Can be obtained by NK_ALIGNOF */ @@ -9563,7 +9563,7 @@ nk_draw_list_add_clip(struct nk_draw_list *list, struct nk_rect rect) NK_ASSERT(list); if (!list) return; if (!list->cmd_count) { - nk_draw_list_push_command(list, rect, list->config.null.texture); + nk_draw_list_push_command(list, rect, list->config.tex_null.texture); } else { struct nk_draw_command *prev = nk_draw_list_command_last(list); if (prev->elem_count == 0) @@ -9918,7 +9918,7 @@ nk_draw_list_stroke_poly_line(struct nk_draw_list *list, const struct nk_vec2 *p /* fill vertices */ for (i = 0; i < points_count; ++i) { - const struct nk_vec2 uv = list->config.null.uv; + const struct nk_vec2 uv = list->config.tex_null.uv; vtx = nk_draw_vertex(vtx, &list->config, points[i], uv, col); vtx = nk_draw_vertex(vtx, &list->config, temp[i*2+0], uv, col_trans); vtx = nk_draw_vertex(vtx, &list->config, temp[i*2+1], uv, col_trans); @@ -9983,7 +9983,7 @@ nk_draw_list_stroke_poly_line(struct nk_draw_list *list, const struct nk_vec2 *p /* add vertices */ for (i = 0; i < points_count; ++i) { - const struct nk_vec2 uv = list->config.null.uv; + const struct nk_vec2 uv = list->config.tex_null.uv; vtx = nk_draw_vertex(vtx, &list->config, temp[i*4+0], uv, col_trans); vtx = nk_draw_vertex(vtx, &list->config, temp[i*4+1], uv, col); vtx = nk_draw_vertex(vtx, &list->config, temp[i*4+2], uv, col); @@ -10004,7 +10004,7 @@ nk_draw_list_stroke_poly_line(struct nk_draw_list *list, const struct nk_vec2 *p for (i1 = 0; i1 < count; ++i1) { float dx, dy; - const struct nk_vec2 uv = list->config.null.uv; + const struct nk_vec2 uv = list->config.tex_null.uv; const nk_size i2 = ((i1+1) == points_count) ? 0 : i1 + 1; const struct nk_vec2 p1 = points[i1]; const struct nk_vec2 p2 = points[i2]; @@ -10114,7 +10114,7 @@ nk_draw_list_fill_poly_convex(struct nk_draw_list *list, /* add vertices + indexes */ for (i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) { - const struct nk_vec2 uv = list->config.null.uv; + const struct nk_vec2 uv = list->config.tex_null.uv; struct nk_vec2 n0 = normals[i0]; struct nk_vec2 n1 = normals[i1]; struct nk_vec2 dm = nk_vec2_muls(nk_vec2_add(n0, n1), 0.5f); @@ -10151,7 +10151,7 @@ nk_draw_list_fill_poly_convex(struct nk_draw_list *list, if (!vtx || !ids) return; for (i = 0; i < vtx_count; ++i) - vtx = nk_draw_vertex(vtx, &list->config, points[i], list->config.null.uv, col); + vtx = nk_draw_vertex(vtx, &list->config, points[i], list->config.tex_null.uv, col); for (i = 2; i < points_count; ++i) { ids[0] = (nk_draw_index)index; ids[1] = (nk_draw_index)(index+ i - 1); @@ -10180,8 +10180,8 @@ nk_draw_list_path_line_to(struct nk_draw_list *list, struct nk_vec2 pos) nk_draw_list_add_clip(list, nk_null_rect); cmd = nk_draw_list_command_last(list); - if (cmd && cmd->texture.ptr != list->config.null.texture.ptr) - nk_draw_list_push_image(list, list->config.null.texture); + if (cmd && cmd->texture.ptr != list->config.tex_null.texture.ptr) + nk_draw_list_push_image(list, list->config.tex_null.texture); points = nk_draw_list_alloc_path(list, 1); if (!points) return; @@ -10383,7 +10383,7 @@ nk_draw_list_fill_rect_multi_color(struct nk_draw_list *list, struct nk_rect rec NK_ASSERT(list); if (!list) return; - nk_draw_list_push_image(list, list->config.null.texture); + nk_draw_list_push_image(list, list->config.tex_null.texture); index = (nk_draw_index)list->vertex_count; vtx = nk_draw_list_alloc_vertices(list, 4); idx = nk_draw_list_alloc_elements(list, 6); @@ -10393,10 +10393,10 @@ nk_draw_list_fill_rect_multi_color(struct nk_draw_list *list, struct nk_rect rec idx[2] = (nk_draw_index)(index+2); idx[3] = (nk_draw_index)(index+0); idx[4] = (nk_draw_index)(index+2); idx[5] = (nk_draw_index)(index+3); - vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x, rect.y), list->config.null.uv, col_left); - vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x + rect.w, rect.y), list->config.null.uv, col_top); - vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x + rect.w, rect.y + rect.h), list->config.null.uv, col_right); - vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x, rect.y + rect.h), list->config.null.uv, col_bottom); + vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x, rect.y), list->config.tex_null.uv, col_left); + vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x + rect.w, rect.y), list->config.tex_null.uv, col_top); + vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x + rect.w, rect.y + rect.h), list->config.tex_null.uv, col_right); + vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x, rect.y + rect.h), list->config.tex_null.uv, col_bottom); } NK_API void nk_draw_list_fill_triangle(struct nk_draw_list *list, struct nk_vec2 a, @@ -29656,6 +29656,7 @@ nk_tooltipfv(struct nk_context *ctx, const char *fmt, va_list args) /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// +/// - 2022/07/30 (4.10.1) - Renamed the `null` texture variable to `tex_null` /// - 2022/05/27 (4.10.0) - Add nk_input_has_mouse_click_in_button_rect() to fix window move bug /// - 2022/04/18 (4.9.7) - Change button behavior when NK_BUTTON_TRIGGER_ON_RELEASE is defined to /// only trigger when the mouse position was inside the same button on down diff --git a/src/CHANGELOG b/src/CHANGELOG index 44223af..619468c 100644 --- a/src/CHANGELOG +++ b/src/CHANGELOG @@ -7,6 +7,7 @@ /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// +/// - 2022/07/30 (4.10.1) - Renamed the `null` texture variable to `tex_null` /// - 2022/05/27 (4.10.0) - Add nk_input_has_mouse_click_in_button_rect() to fix window move bug /// - 2022/04/18 (4.9.7) - Change button behavior when NK_BUTTON_TRIGGER_ON_RELEASE is defined to /// only trigger when the mouse position was inside the same button on down From 54fd67bddd8aa82beed67cf29667ae403e319508 Mon Sep 17 00:00:00 2001 From: Rob Loach Date: Sat, 30 Jul 2022 17:43:46 -0400 Subject: [PATCH 012/106] Rename additional .null variables --- demo/d3d11/nuklear_d3d11.h | 6 +++--- demo/d3d12/nuklear_d3d12.h | 6 +++--- demo/d3d9/nuklear_d3d9.h | 6 +++--- demo/glfw_opengl2/nuklear_glfw_gl2.h | 4 ++-- demo/glfw_opengl3/nuklear_glfw_gl3.h | 4 ++-- demo/glfw_opengl4/nuklear_glfw_gl4.h | 4 ++-- demo/sdl_opengl2/nuklear_sdl_gl2.h | 4 ++-- demo/sdl_opengl3/nuklear_sdl_gl3.h | 4 ++-- demo/sdl_opengles2/nuklear_sdl_gles2.h | 4 ++-- demo/sdl_renderer/nuklear_sdl_renderer.h | 4 ++-- demo/sfml_opengl2/nuklear_sfml_gl2.h | 4 ++-- demo/sfml_opengl3/nuklear_sfml_gl3.h | 4 ++-- demo/x11_opengl2/nuklear_xlib_gl2.h | 4 ++-- demo/x11_opengl3/nuklear_xlib_gl3.h | 4 ++-- doc/index.html | 2 +- example/canvas.c | 4 ++-- example/extended.c | 4 ++-- example/file_browser.c | 4 ++-- example/skinning.c | 4 ++-- nuklear.h | 16 ++++++++-------- src/nuklear_font.c | 16 ++++++++-------- 21 files changed, 56 insertions(+), 56 deletions(-) diff --git a/demo/d3d11/nuklear_d3d11.h b/demo/d3d11/nuklear_d3d11.h index 46c615d..27fa2c1 100644 --- a/demo/d3d11/nuklear_d3d11.h +++ b/demo/d3d11/nuklear_d3d11.h @@ -61,7 +61,7 @@ static struct struct nk_font_atlas atlas; struct nk_buffer cmds; - struct nk_draw_null_texture null; + struct nk_draw_null_texture tex_null; unsigned int max_vertex_buffer; unsigned int max_index_buffer; @@ -137,7 +137,7 @@ nk_d3d11_render(ID3D11DeviceContext *context, enum nk_anti_aliasing AA) config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; - config.tex_null = d3d11.null; + config.tex_null = d3d11.tex_null; {/* setup buffers to load vertices and elements */ struct nk_buffer vbuf, ibuf; @@ -603,7 +603,7 @@ nk_d3d11_font_stash_end(void) assert(SUCCEEDED(hr));} ID3D11Texture2D_Release(font_texture);} - nk_font_atlas_end(&d3d11.atlas, nk_handle_ptr(d3d11.font_texture_view), &d3d11.null); + nk_font_atlas_end(&d3d11.atlas, nk_handle_ptr(d3d11.font_texture_view), &d3d11.tex_null); if (d3d11.atlas.default_font) nk_style_set_font(&d3d11.ctx, &d3d11.atlas.default_font->handle); } diff --git a/demo/d3d12/nuklear_d3d12.h b/demo/d3d12/nuklear_d3d12.h index 1660d7b..5b86ea1 100644 --- a/demo/d3d12/nuklear_d3d12.h +++ b/demo/d3d12/nuklear_d3d12.h @@ -109,7 +109,7 @@ static struct struct nk_font_atlas atlas; struct nk_buffer cmds; - struct nk_draw_null_texture null; + struct nk_draw_null_texture tex_null; unsigned int max_vertex_buffer; unsigned int max_index_buffer; unsigned int max_user_textures; @@ -198,7 +198,7 @@ nk_d3d12_render(ID3D12GraphicsCommandList *command_list, enum nk_anti_aliasing A config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; - config.tex_null = d3d12.null; + config.tex_null = d3d12.tex_null; struct nk_buffer vbuf, ibuf; nk_buffer_init_fixed(&vbuf, &ptr_data[sizeof(float) * 4 * 4], (size_t)d3d12.max_vertex_buffer); @@ -863,7 +863,7 @@ nk_d3d12_font_stash_end(ID3D12GraphicsCommandList *command_list) ID3D12Device_CreateShaderResourceView(d3d12.device, d3d12.font_texture, &srv_desc, srv_handle); /* Done with nk atlas data. Atlas will be served with texture id 0 */ - nk_font_atlas_end(&d3d12.atlas, nk_handle_id(0), &d3d12.null); + nk_font_atlas_end(&d3d12.atlas, nk_handle_id(0), &d3d12.tex_null); /* Setup default font */ if (d3d12.atlas.default_font) diff --git a/demo/d3d9/nuklear_d3d9.h b/demo/d3d9/nuklear_d3d9.h index 1aee6ba..f967678 100644 --- a/demo/d3d9/nuklear_d3d9.h +++ b/demo/d3d9/nuklear_d3d9.h @@ -58,7 +58,7 @@ static struct { struct nk_font_atlas atlas; struct nk_buffer cmds; - struct nk_draw_null_texture null; + struct nk_draw_null_texture tex_null; D3DVIEWPORT9 viewport; D3DMATRIX projection; @@ -150,7 +150,7 @@ nk_d3d9_render(enum nk_anti_aliasing AA) config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; - config.tex_null = d3d9.null; + config.tex_null = d3d9.tex_null; /* convert shapes into vertexes */ nk_buffer_init_default(&vbuf); @@ -248,7 +248,7 @@ nk_d3d9_create_font_texture() hr = IDirect3DTexture9_UnlockRect(d3d9.texture, 0); NK_ASSERT(SUCCEEDED(hr)); - nk_font_atlas_end(&d3d9.atlas, nk_handle_ptr(d3d9.texture), &d3d9.null); + nk_font_atlas_end(&d3d9.atlas, nk_handle_ptr(d3d9.texture), &d3d9.tex_null); } NK_API void diff --git a/demo/glfw_opengl2/nuklear_glfw_gl2.h b/demo/glfw_opengl2/nuklear_glfw_gl2.h index 97e3b6e..2706f11 100644 --- a/demo/glfw_opengl2/nuklear_glfw_gl2.h +++ b/demo/glfw_opengl2/nuklear_glfw_gl2.h @@ -53,7 +53,7 @@ NK_API void nk_gflw3_scroll_callback(GLFWwindow *win, double xof struct nk_glfw_device { struct nk_buffer cmds; - struct nk_draw_null_texture null; + struct nk_draw_null_texture tex_null; GLuint font_tex; }; @@ -288,7 +288,7 @@ nk_glfw3_font_stash_end(void) const void *image; int w, h; image = nk_font_atlas_bake(&glfw.atlas, &w, &h, NK_FONT_ATLAS_RGBA32); nk_glfw3_device_upload_atlas(image, w, h); - nk_font_atlas_end(&glfw.atlas, nk_handle_id((int)glfw.ogl.font_tex), &glfw.ogl.null); + nk_font_atlas_end(&glfw.atlas, nk_handle_id((int)glfw.ogl.font_tex), &glfw.ogl.tex_null); if (glfw.atlas.default_font) nk_style_set_font(&glfw.ctx, &glfw.atlas.default_font->handle); } diff --git a/demo/glfw_opengl3/nuklear_glfw_gl3.h b/demo/glfw_opengl3/nuklear_glfw_gl3.h index 573b76d..a1e5d6c 100644 --- a/demo/glfw_opengl3/nuklear_glfw_gl3.h +++ b/demo/glfw_opengl3/nuklear_glfw_gl3.h @@ -26,7 +26,7 @@ enum nk_glfw_init_state{ struct nk_glfw_device { struct nk_buffer cmds; - struct nk_draw_null_texture null; + struct nk_draw_null_texture tex_null; GLuint vbo, vao, ebo; GLuint prog; GLuint vert_shdr; @@ -403,7 +403,7 @@ nk_glfw3_font_stash_end(struct nk_glfw* glfw) const void *image; int w, h; image = nk_font_atlas_bake(&glfw->atlas, &w, &h, NK_FONT_ATLAS_RGBA32); nk_glfw3_device_upload_atlas(glfw, image, w, h); - nk_font_atlas_end(&glfw->atlas, nk_handle_id((int)glfw->ogl.font_tex), &glfw->ogl.null); + nk_font_atlas_end(&glfw->atlas, nk_handle_id((int)glfw->ogl.font_tex), &glfw->ogl.tex_null); if (glfw->atlas.default_font) nk_style_set_font(&glfw->ctx, &glfw->atlas.default_font->handle); } diff --git a/demo/glfw_opengl4/nuklear_glfw_gl4.h b/demo/glfw_opengl4/nuklear_glfw_gl4.h index 6f1e259..683da8c 100644 --- a/demo/glfw_opengl4/nuklear_glfw_gl4.h +++ b/demo/glfw_opengl4/nuklear_glfw_gl4.h @@ -72,7 +72,7 @@ struct nk_glfw_vertex { struct nk_glfw_device { struct nk_buffer cmds; - struct nk_draw_null_texture null; + struct nk_draw_null_texture tex_null; GLuint vbo, vao, ebo; GLuint prog; GLuint vert_shdr; @@ -553,7 +553,7 @@ nk_glfw3_font_stash_end(void) const void *image; int w, h; image = nk_font_atlas_bake(&glfw.atlas, &w, &h, NK_FONT_ATLAS_RGBA32); nk_glfw3_device_upload_atlas(image, w, h); - nk_font_atlas_end(&glfw.atlas, nk_handle_id((int)glfw.ogl.font_tex_index), &glfw.ogl.null); + nk_font_atlas_end(&glfw.atlas, nk_handle_id((int)glfw.ogl.font_tex_index), &glfw.ogl.tex_null); if (glfw.atlas.default_font) nk_style_set_font(&glfw.ctx, &glfw.atlas.default_font->handle); } diff --git a/demo/sdl_opengl2/nuklear_sdl_gl2.h b/demo/sdl_opengl2/nuklear_sdl_gl2.h index 7850d65..eaa00e5 100644 --- a/demo/sdl_opengl2/nuklear_sdl_gl2.h +++ b/demo/sdl_opengl2/nuklear_sdl_gl2.h @@ -33,7 +33,7 @@ NK_API void nk_sdl_shutdown(void); struct nk_sdl_device { struct nk_buffer cmds; - struct nk_draw_null_texture null; + struct nk_draw_null_texture tex_null; GLuint font_tex; }; @@ -226,7 +226,7 @@ nk_sdl_font_stash_end(void) const void *image; int w, h; image = nk_font_atlas_bake(&sdl.atlas, &w, &h, NK_FONT_ATLAS_RGBA32); nk_sdl_device_upload_atlas(image, w, h); - nk_font_atlas_end(&sdl.atlas, nk_handle_id((int)sdl.ogl.font_tex), &sdl.ogl.null); + nk_font_atlas_end(&sdl.atlas, nk_handle_id((int)sdl.ogl.font_tex), &sdl.ogl.tex_null); if (sdl.atlas.default_font) nk_style_set_font(&sdl.ctx, &sdl.atlas.default_font->handle); } diff --git a/demo/sdl_opengl3/nuklear_sdl_gl3.h b/demo/sdl_opengl3/nuklear_sdl_gl3.h index 26036f1..560ef69 100644 --- a/demo/sdl_opengl3/nuklear_sdl_gl3.h +++ b/demo/sdl_opengl3/nuklear_sdl_gl3.h @@ -40,7 +40,7 @@ NK_API void nk_sdl_device_create(void); struct nk_sdl_device { struct nk_buffer cmds; - struct nk_draw_null_texture null; + struct nk_draw_null_texture tex_null; GLuint vbo, vao, ebo; GLuint prog; GLuint vert_shdr; @@ -334,7 +334,7 @@ nk_sdl_font_stash_end(void) const void *image; int w, h; image = nk_font_atlas_bake(&sdl.atlas, &w, &h, NK_FONT_ATLAS_RGBA32); nk_sdl_device_upload_atlas(image, w, h); - nk_font_atlas_end(&sdl.atlas, nk_handle_id((int)sdl.ogl.font_tex), &sdl.ogl.null); + nk_font_atlas_end(&sdl.atlas, nk_handle_id((int)sdl.ogl.font_tex), &sdl.ogl.tex_null); if (sdl.atlas.default_font) nk_style_set_font(&sdl.ctx, &sdl.atlas.default_font->handle); diff --git a/demo/sdl_opengles2/nuklear_sdl_gles2.h b/demo/sdl_opengles2/nuklear_sdl_gles2.h index 592e0db..854c582 100644 --- a/demo/sdl_opengles2/nuklear_sdl_gles2.h +++ b/demo/sdl_opengles2/nuklear_sdl_gles2.h @@ -43,7 +43,7 @@ NK_API void nk_sdl_device_create(void); struct nk_sdl_device { struct nk_buffer cmds; - struct nk_draw_null_texture null; + struct nk_draw_null_texture tex_null; GLuint vbo, ebo; GLuint prog; GLuint vert_shdr; @@ -335,7 +335,7 @@ nk_sdl_font_stash_end(void) const void *image; int w, h; image = nk_font_atlas_bake(&sdl.atlas, &w, &h, NK_FONT_ATLAS_RGBA32); nk_sdl_device_upload_atlas(image, w, h); - nk_font_atlas_end(&sdl.atlas, nk_handle_id((int)sdl.ogl.font_tex), &sdl.ogl.null); + nk_font_atlas_end(&sdl.atlas, nk_handle_id((int)sdl.ogl.font_tex), &sdl.ogl.tex_null); if (sdl.atlas.default_font) nk_style_set_font(&sdl.ctx, &sdl.atlas.default_font->handle); diff --git a/demo/sdl_renderer/nuklear_sdl_renderer.h b/demo/sdl_renderer/nuklear_sdl_renderer.h index 702d56c..be6f0aa 100644 --- a/demo/sdl_renderer/nuklear_sdl_renderer.h +++ b/demo/sdl_renderer/nuklear_sdl_renderer.h @@ -44,7 +44,7 @@ NK_API void nk_sdl_shutdown(void); struct nk_sdl_device { struct nk_buffer cmds; - struct nk_draw_null_texture null; + struct nk_draw_null_texture tex_null; SDL_Texture *font_tex; }; @@ -259,7 +259,7 @@ nk_sdl_font_stash_end(void) const void *image; int w, h; image = nk_font_atlas_bake(&sdl.atlas, &w, &h, NK_FONT_ATLAS_RGBA32); nk_sdl_device_upload_atlas(image, w, h); - nk_font_atlas_end(&sdl.atlas, nk_handle_ptr(sdl.ogl.font_tex), &sdl.ogl.null); + nk_font_atlas_end(&sdl.atlas, nk_handle_ptr(sdl.ogl.font_tex), &sdl.ogl.tex_null); if (sdl.atlas.default_font) nk_style_set_font(&sdl.ctx, &sdl.atlas.default_font->handle); } diff --git a/demo/sfml_opengl2/nuklear_sfml_gl2.h b/demo/sfml_opengl2/nuklear_sfml_gl2.h index 1f9fcd1..a848d27 100644 --- a/demo/sfml_opengl2/nuklear_sfml_gl2.h +++ b/demo/sfml_opengl2/nuklear_sfml_gl2.h @@ -34,7 +34,7 @@ NK_API void nk_sfml_shutdown(void); struct nk_sfml_device { struct nk_buffer cmds; - struct nk_draw_null_texture null; + struct nk_draw_null_texture tex_null; GLuint font_tex; }; @@ -245,7 +245,7 @@ nk_sfml_font_stash_end() const void* img; img = nk_font_atlas_bake(&sfml.atlas, &w, &h, NK_FONT_ATLAS_RGBA32); nk_sfml_device_upload_atlas(img, w, h); - nk_font_atlas_end(&sfml.atlas, nk_handle_id((int)sfml.ogl.font_tex), &sfml.ogl.null); + nk_font_atlas_end(&sfml.atlas, nk_handle_id((int)sfml.ogl.font_tex), &sfml.ogl.tex_null); if(sfml.atlas.default_font) nk_style_set_font(&sfml.ctx, &sfml.atlas.default_font->handle); } diff --git a/demo/sfml_opengl3/nuklear_sfml_gl3.h b/demo/sfml_opengl3/nuklear_sfml_gl3.h index 0038b34..a601ce8 100644 --- a/demo/sfml_opengl3/nuklear_sfml_gl3.h +++ b/demo/sfml_opengl3/nuklear_sfml_gl3.h @@ -43,7 +43,7 @@ NK_API void nk_sfml_device_destroy(void); struct nk_sfml_device { struct nk_buffer cmds; - struct nk_draw_null_texture null; + struct nk_draw_null_texture tex_null; GLuint vbo, vao, ebo; GLuint prog; GLuint vert_shdr; @@ -353,7 +353,7 @@ nk_sfml_font_stash_end() int w, h; image = nk_font_atlas_bake(&sfml.atlas, &w, &h, NK_FONT_ATLAS_RGBA32); nk_sfml_device_upload_atlas(image, w, h); - nk_font_atlas_end(&sfml.atlas, nk_handle_id((int)sfml.ogl.font_tex), &sfml.ogl.null); + nk_font_atlas_end(&sfml.atlas, nk_handle_id((int)sfml.ogl.font_tex), &sfml.ogl.tex_null); if(sfml.atlas.default_font) nk_style_set_font(&sfml.ctx, &sfml.atlas.default_font->handle); } diff --git a/demo/x11_opengl2/nuklear_xlib_gl2.h b/demo/x11_opengl2/nuklear_xlib_gl2.h index 9e1382e..209fa79 100644 --- a/demo/x11_opengl2/nuklear_xlib_gl2.h +++ b/demo/x11_opengl2/nuklear_xlib_gl2.h @@ -60,7 +60,7 @@ struct nk_x11_vertex { struct nk_x11_device { struct nk_buffer cmds; - struct nk_draw_null_texture null; + struct nk_draw_null_texture tex_null; GLuint font_tex; }; @@ -226,7 +226,7 @@ nk_x11_font_stash_end(void) const void *image; int w, h; image = nk_font_atlas_bake(&x11.atlas, &w, &h, NK_FONT_ATLAS_RGBA32); nk_x11_device_upload_atlas(image, w, h); - nk_font_atlas_end(&x11.atlas, nk_handle_id((int)x11.ogl.font_tex), &x11.ogl.null); + nk_font_atlas_end(&x11.atlas, nk_handle_id((int)x11.ogl.font_tex), &x11.ogl.tex_null); if (x11.atlas.default_font) nk_style_set_font(&x11.ctx, &x11.atlas.default_font->handle); } diff --git a/demo/x11_opengl3/nuklear_xlib_gl3.h b/demo/x11_opengl3/nuklear_xlib_gl3.h index 85ff2ae..e9d1fcc 100644 --- a/demo/x11_opengl3/nuklear_xlib_gl3.h +++ b/demo/x11_opengl3/nuklear_xlib_gl3.h @@ -173,7 +173,7 @@ struct nk_x11_device { struct opengl_info info; #endif struct nk_buffer cmds; - struct nk_draw_null_texture null; + struct nk_draw_null_texture tex_null; GLuint vbo, vao, ebo; GLuint prog; GLuint vert_shdr; @@ -592,7 +592,7 @@ nk_x11_font_stash_end(void) const void *image; int w, h; image = nk_font_atlas_bake(&x11.atlas, &w, &h, NK_FONT_ATLAS_RGBA32); nk_x11_device_upload_atlas(image, w, h); - nk_font_atlas_end(&x11.atlas, nk_handle_id((int)x11.ogl.font_tex), &x11.ogl.null); + nk_font_atlas_end(&x11.atlas, nk_handle_id((int)x11.ogl.font_tex), &x11.ogl.tex_null); if (x11.atlas.default_font) nk_style_set_font(&x11.ctx, &x11.atlas.default_font->handle); } diff --git a/doc/index.html b/doc/index.html index bed7855..b967ac2 100644 --- a/doc/index.html +++ b/doc/index.html @@ -637,7 +637,7 @@ cfg.circle_segment_count = 22; cfg.curve_segment_count = 22; cfg.arc_segment_count = 22; cfg.global_alpha = 1.0f; -cfg.null = dev->null; +cfg.tex_null = dev->null; // // setup buffers and convert struct nk_buffer cmds, verts, idx; diff --git a/example/canvas.c b/example/canvas.c index d8a1534..d48e15c 100644 --- a/example/canvas.c +++ b/example/canvas.c @@ -52,7 +52,7 @@ struct nk_glfw_vertex { struct device { struct nk_buffer cmds; - struct nk_draw_null_texture null; + struct nk_draw_null_texture tex_null; GLuint vbo, vao, ebo; GLuint prog; GLuint vert_shdr; @@ -441,7 +441,7 @@ int main(int argc, char *argv[]) font = nk_font_atlas_add_default(&atlas, 13, 0); image = nk_font_atlas_bake(&atlas, &w, &h, NK_FONT_ATLAS_RGBA32); device_upload_atlas(&device, image, w, h); - nk_font_atlas_end(&atlas, nk_handle_id((int)device.font_tex), &device.null); + nk_font_atlas_end(&atlas, nk_handle_id((int)device.font_tex), &device.tex_null); nk_init_default(&ctx, &font->handle); glEnable(GL_TEXTURE_2D); diff --git a/example/extended.c b/example/extended.c index 41f2fa2..e12eef6 100644 --- a/example/extended.c +++ b/example/extended.c @@ -478,7 +478,7 @@ struct nk_glfw_vertex { struct device { struct nk_buffer cmds; - struct nk_draw_null_texture null; + struct nk_draw_null_texture tex_null; GLuint vbo, vao, ebo; GLuint prog; GLuint vert_shdr; @@ -795,7 +795,7 @@ int main(int argc, char *argv[]) media.font_22 = nk_font_atlas_add_from_file(&atlas, "../../extra_font/Roboto-Regular.ttf", 22.0f, &cfg); image = nk_font_atlas_bake(&atlas, &w, &h, NK_FONT_ATLAS_RGBA32); device_upload_atlas(&device, image, w, h); - nk_font_atlas_end(&atlas, nk_handle_id((int)device.font_tex), &device.null);} + nk_font_atlas_end(&atlas, nk_handle_id((int)device.font_tex), &device.tex_null);} nk_init_default(&ctx, &media.font_14->handle);} /* icons */ diff --git a/example/file_browser.c b/example/file_browser.c index 60e6ac2..cd21f09 100644 --- a/example/file_browser.c +++ b/example/file_browser.c @@ -527,7 +527,7 @@ struct nk_glfw_vertex { struct device { struct nk_buffer cmds; - struct nk_draw_null_texture null; + struct nk_draw_null_texture tex_null; GLuint vbo, vao, ebo; GLuint prog; GLuint vert_shdr; @@ -823,7 +823,7 @@ int main(int argc, char *argv[]) else font = nk_font_atlas_add_default(&atlas, 13.0f, NULL); image = nk_font_atlas_bake(&atlas, &w, &h, NK_FONT_ATLAS_RGBA32); device_upload_atlas(&device, image, w, h); - nk_font_atlas_end(&atlas, nk_handle_id((int)device.font_tex), &device.null);} + nk_font_atlas_end(&atlas, nk_handle_id((int)device.font_tex), &device.tex_null);} nk_init_default(&ctx, &font->handle);} /* icons */ diff --git a/example/skinning.c b/example/skinning.c index b54b03d..db365dc 100644 --- a/example/skinning.c +++ b/example/skinning.c @@ -79,7 +79,7 @@ struct nk_glfw_vertex { struct device { struct nk_buffer cmds; - struct nk_draw_null_texture null; + struct nk_draw_null_texture tex_null; GLuint vbo, vao, ebo; GLuint prog; GLuint vert_shdr; @@ -388,7 +388,7 @@ int main(int argc, char *argv[]) else font = nk_font_atlas_add_default(&atlas, 13.0f, NULL); image = nk_font_atlas_bake(&atlas, &w, &h, NK_FONT_ATLAS_RGBA32); device_upload_atlas(&device, image, w, h); - nk_font_atlas_end(&atlas, nk_handle_id((int)device.font_tex), &device.null);} + nk_font_atlas_end(&atlas, nk_handle_id((int)device.font_tex), &device.tex_null);} nk_init_default(&ctx, &font->handle);} { /* skin */ diff --git a/nuklear.h b/nuklear.h index 90d8b2d..901d3e5 100644 --- a/nuklear.h +++ b/nuklear.h @@ -17703,20 +17703,20 @@ failed: } NK_API void nk_font_atlas_end(struct nk_font_atlas *atlas, nk_handle texture, - struct nk_draw_null_texture *null) + struct nk_draw_null_texture *tex_null) { int i = 0; struct nk_font *font_iter; NK_ASSERT(atlas); if (!atlas) { - if (!null) return; - null->texture = texture; - null->uv = nk_vec2(0.5f,0.5f); + if (!tex_null) return; + tex_null->texture = texture; + tex_null->uv = nk_vec2(0.5f,0.5f); } - if (null) { - null->texture = texture; - null->uv.x = (atlas->custom.x + 0.5f)/(float)atlas->tex_width; - null->uv.y = (atlas->custom.y + 0.5f)/(float)atlas->tex_height; + if (tex_null) { + tex_null->texture = texture; + tex_null->uv.x = (atlas->custom.x + 0.5f)/(float)atlas->tex_width; + tex_null->uv.y = (atlas->custom.y + 0.5f)/(float)atlas->tex_height; } for (font_iter = atlas->fonts; font_iter; font_iter = font_iter->next) { font_iter->texture = texture; diff --git a/src/nuklear_font.c b/src/nuklear_font.c index 541bf48..e1ada96 100644 --- a/src/nuklear_font.c +++ b/src/nuklear_font.c @@ -1276,20 +1276,20 @@ failed: } NK_API void nk_font_atlas_end(struct nk_font_atlas *atlas, nk_handle texture, - struct nk_draw_null_texture *null) + struct nk_draw_null_texture *tex_null) { int i = 0; struct nk_font *font_iter; NK_ASSERT(atlas); if (!atlas) { - if (!null) return; - null->texture = texture; - null->uv = nk_vec2(0.5f,0.5f); + if (!tex_null) return; + tex_null->texture = texture; + tex_null->uv = nk_vec2(0.5f,0.5f); } - if (null) { - null->texture = texture; - null->uv.x = (atlas->custom.x + 0.5f)/(float)atlas->tex_width; - null->uv.y = (atlas->custom.y + 0.5f)/(float)atlas->tex_height; + if (tex_null) { + tex_null->texture = texture; + tex_null->uv.x = (atlas->custom.x + 0.5f)/(float)atlas->tex_width; + tex_null->uv.y = (atlas->custom.y + 0.5f)/(float)atlas->tex_height; } for (font_iter = atlas->fonts; font_iter; font_iter = font_iter->next) { font_iter->texture = texture; From ca49016428aace2b19c30b87f8d2418bdfc755ca Mon Sep 17 00:00:00 2001 From: Rob Loach Date: Sat, 30 Jul 2022 17:45:12 -0400 Subject: [PATCH 013/106] Rename more null variables to tex_null --- demo/glfw_opengl2/nuklear_glfw_gl2.h | 2 +- demo/glfw_opengl3/nuklear_glfw_gl3.h | 2 +- demo/glfw_opengl4/nuklear_glfw_gl4.h | 2 +- demo/sdl_opengl2/nuklear_sdl_gl2.h | 2 +- demo/sdl_opengl3/nuklear_sdl_gl3.h | 2 +- demo/sdl_opengles2/nuklear_sdl_gles2.h | 2 +- demo/sdl_renderer/nuklear_sdl_renderer.h | 2 +- demo/sfml_opengl2/nuklear_sfml_gl2.h | 2 +- demo/sfml_opengl3/nuklear_sfml_gl3.h | 2 +- demo/x11_opengl2/nuklear_xlib_gl2.h | 2 +- demo/x11_opengl3/nuklear_xlib_gl3.h | 2 +- doc/index.html | 2 +- example/canvas.c | 2 +- example/extended.c | 2 +- example/file_browser.c | 2 +- example/skinning.c | 2 +- 16 files changed, 16 insertions(+), 16 deletions(-) diff --git a/demo/glfw_opengl2/nuklear_glfw_gl2.h b/demo/glfw_opengl2/nuklear_glfw_gl2.h index 2706f11..fb8b31e 100644 --- a/demo/glfw_opengl2/nuklear_glfw_gl2.h +++ b/demo/glfw_opengl2/nuklear_glfw_gl2.h @@ -140,7 +140,7 @@ nk_glfw3_render(enum nk_anti_aliasing AA) config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_glfw_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_glfw_vertex); - config.tex_null = dev->null; + config.tex_null = dev->tex_null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/demo/glfw_opengl3/nuklear_glfw_gl3.h b/demo/glfw_opengl3/nuklear_glfw_gl3.h index a1e5d6c..663fa0b 100644 --- a/demo/glfw_opengl3/nuklear_glfw_gl3.h +++ b/demo/glfw_opengl3/nuklear_glfw_gl3.h @@ -266,7 +266,7 @@ nk_glfw3_render(struct nk_glfw* glfw, enum nk_anti_aliasing AA, int max_vertex_b config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_glfw_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_glfw_vertex); - config.tex_null = dev->null; + config.tex_null = dev->tex_null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/demo/glfw_opengl4/nuklear_glfw_gl4.h b/demo/glfw_opengl4/nuklear_glfw_gl4.h index 683da8c..781bfc3 100644 --- a/demo/glfw_opengl4/nuklear_glfw_gl4.h +++ b/demo/glfw_opengl4/nuklear_glfw_gl4.h @@ -407,7 +407,7 @@ nk_glfw3_render(enum nk_anti_aliasing AA) config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_glfw_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_glfw_vertex); - config.tex_null = dev->null; + config.tex_null = dev->tex_null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/demo/sdl_opengl2/nuklear_sdl_gl2.h b/demo/sdl_opengl2/nuklear_sdl_gl2.h index eaa00e5..0c6a2fb 100644 --- a/demo/sdl_opengl2/nuklear_sdl_gl2.h +++ b/demo/sdl_opengl2/nuklear_sdl_gl2.h @@ -120,7 +120,7 @@ nk_sdl_render(enum nk_anti_aliasing AA) config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_sdl_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_sdl_vertex); - config.tex_null = dev->null; + config.tex_null = dev->tex_null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/demo/sdl_opengl3/nuklear_sdl_gl3.h b/demo/sdl_opengl3/nuklear_sdl_gl3.h index 560ef69..cac8629 100644 --- a/demo/sdl_opengl3/nuklear_sdl_gl3.h +++ b/demo/sdl_opengl3/nuklear_sdl_gl3.h @@ -247,7 +247,7 @@ nk_sdl_render(enum nk_anti_aliasing AA, int max_vertex_buffer, int max_element_b config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_sdl_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_sdl_vertex); - config.tex_null = dev->null; + config.tex_null = dev->tex_null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/demo/sdl_opengles2/nuklear_sdl_gles2.h b/demo/sdl_opengles2/nuklear_sdl_gles2.h index 854c582..595d7a7 100644 --- a/demo/sdl_opengles2/nuklear_sdl_gles2.h +++ b/demo/sdl_opengles2/nuklear_sdl_gles2.h @@ -245,7 +245,7 @@ nk_sdl_render(enum nk_anti_aliasing AA, int max_vertex_buffer, int max_element_b config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_sdl_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_sdl_vertex); - config.tex_null = dev->null; + config.tex_null = dev->tex_null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/demo/sdl_renderer/nuklear_sdl_renderer.h b/demo/sdl_renderer/nuklear_sdl_renderer.h index be6f0aa..672b81b 100644 --- a/demo/sdl_renderer/nuklear_sdl_renderer.h +++ b/demo/sdl_renderer/nuklear_sdl_renderer.h @@ -113,7 +113,7 @@ nk_sdl_render(enum nk_anti_aliasing AA) config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_sdl_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_sdl_vertex); - config.tex_null = dev->null; + config.tex_null = dev->tex_null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/demo/sfml_opengl2/nuklear_sfml_gl2.h b/demo/sfml_opengl2/nuklear_sfml_gl2.h index a848d27..f168bab 100644 --- a/demo/sfml_opengl2/nuklear_sfml_gl2.h +++ b/demo/sfml_opengl2/nuklear_sfml_gl2.h @@ -118,7 +118,7 @@ nk_sfml_render(enum nk_anti_aliasing AA) config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_sfml_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_sfml_vertex); - config.tex_null = dev->null; + config.tex_null = dev->tex_null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/demo/sfml_opengl3/nuklear_sfml_gl3.h b/demo/sfml_opengl3/nuklear_sfml_gl3.h index a601ce8..286cfc1 100644 --- a/demo/sfml_opengl3/nuklear_sfml_gl3.h +++ b/demo/sfml_opengl3/nuklear_sfml_gl3.h @@ -248,7 +248,7 @@ nk_sfml_render(enum nk_anti_aliasing AA, int max_vertex_buffer, int max_element_ config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_sfml_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_sfml_vertex); - config.tex_null = dev->null; + config.tex_null = dev->tex_null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/demo/x11_opengl2/nuklear_xlib_gl2.h b/demo/x11_opengl2/nuklear_xlib_gl2.h index 209fa79..2ad2648 100644 --- a/demo/x11_opengl2/nuklear_xlib_gl2.h +++ b/demo/x11_opengl2/nuklear_xlib_gl2.h @@ -153,7 +153,7 @@ nk_x11_render(enum nk_anti_aliasing AA, int max_vertex_buffer, int max_element_b config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_x11_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_x11_vertex); - config.tex_null = dev->null; + config.tex_null = dev->tex_null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/demo/x11_opengl3/nuklear_xlib_gl3.h b/demo/x11_opengl3/nuklear_xlib_gl3.h index e9d1fcc..9dd0181 100644 --- a/demo/x11_opengl3/nuklear_xlib_gl3.h +++ b/demo/x11_opengl3/nuklear_xlib_gl3.h @@ -536,7 +536,7 @@ nk_x11_render(enum nk_anti_aliasing AA, int max_vertex_buffer, int max_element_b config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_x11_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_x11_vertex); - config.tex_null = dev->null; + config.tex_null = dev->tex_null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/doc/index.html b/doc/index.html index b967ac2..0312be3 100644 --- a/doc/index.html +++ b/doc/index.html @@ -637,7 +637,7 @@ cfg.circle_segment_count = 22; cfg.curve_segment_count = 22; cfg.arc_segment_count = 22; cfg.global_alpha = 1.0f; -cfg.tex_null = dev->null; +cfg.tex_null = dev->tex_null; // // setup buffers and convert struct nk_buffer cmds, verts, idx; diff --git a/example/canvas.c b/example/canvas.c index d48e15c..2456927 100644 --- a/example/canvas.c +++ b/example/canvas.c @@ -262,7 +262,7 @@ device_draw(struct device *dev, struct nk_context *ctx, int width, int height, config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_glfw_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_glfw_vertex); - config.tex_null = dev->null; + config.tex_null = dev->tex_null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/example/extended.c b/example/extended.c index e12eef6..4e1211b 100644 --- a/example/extended.c +++ b/example/extended.c @@ -685,7 +685,7 @@ device_draw(struct device *dev, struct nk_context *ctx, int width, int height, config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_glfw_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_glfw_vertex); - config.tex_null = dev->null; + config.tex_null = dev->tex_null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/example/file_browser.c b/example/file_browser.c index cd21f09..6bf23c2 100644 --- a/example/file_browser.c +++ b/example/file_browser.c @@ -722,7 +722,7 @@ device_draw(struct device *dev, struct nk_context *ctx, int width, int height, config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_glfw_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_glfw_vertex); - config.tex_null = dev->null; + config.tex_null = dev->tex_null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; diff --git a/example/skinning.c b/example/skinning.c index db365dc..fab9ce3 100644 --- a/example/skinning.c +++ b/example/skinning.c @@ -286,7 +286,7 @@ device_draw(struct device *dev, struct nk_context *ctx, int width, int height, config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_glfw_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_glfw_vertex); - config.tex_null = dev->null; + config.tex_null = dev->tex_null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; From ce1c94d84bdf0e5de68ec8a06c8372ad56c3b16c Mon Sep 17 00:00:00 2001 From: Rob Loach Date: Sun, 11 Sep 2022 13:53:59 -0400 Subject: [PATCH 014/106] Fix Apple Silicon with incorrect NK_SITE_TYPE and NK_POINTER_TYPE --- nuklear.h | 5 +++-- src/CHANGELOG | 1 + src/nuklear.h | 4 ++-- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/nuklear.h b/nuklear.h index 7af8bb1..bb5917c 100644 --- a/nuklear.h +++ b/nuklear.h @@ -372,7 +372,7 @@ extern "C" { #elif (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER) #define NK_SIZE_TYPE unsigned __int32 #elif defined(__GNUC__) || defined(__clang__) - #if defined(__x86_64__) || defined(__ppc64__) + #if defined(__x86_64__) || defined(__ppc64__) || defined(__aarch64__) #define NK_SIZE_TYPE unsigned long #else #define NK_SIZE_TYPE unsigned int @@ -387,7 +387,7 @@ extern "C" { #elif (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER) #define NK_POINTER_TYPE unsigned __int32 #elif defined(__GNUC__) || defined(__clang__) - #if defined(__x86_64__) || defined(__ppc64__) + #if defined(__x86_64__) || defined(__ppc64__) || defined(__aarch64__) #define NK_POINTER_TYPE unsigned long #else #define NK_POINTER_TYPE unsigned int @@ -29656,6 +29656,7 @@ nk_tooltipfv(struct nk_context *ctx, const char *fmt, va_list args) /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// +/// - 2022/08/01 (4.10.2) - Fix Apple Silicon with incorrect NK_SITE_TYPE and NK_POINTER_TYPE /// - 2022/08/01 (4.10.1) - Fix cursor jumping back to beginning of text when typing more than /// nk_edit_xxx limit /// - 2022/05/27 (4.10.0) - Add nk_input_has_mouse_click_in_button_rect() to fix window move bug diff --git a/src/CHANGELOG b/src/CHANGELOG index 00ee208..2ddafe1 100644 --- a/src/CHANGELOG +++ b/src/CHANGELOG @@ -7,6 +7,7 @@ /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// +/// - 2022/08/01 (4.10.2) - Fix Apple Silicon with incorrect NK_SITE_TYPE and NK_POINTER_TYPE /// - 2022/08/01 (4.10.1) - Fix cursor jumping back to beginning of text when typing more than /// nk_edit_xxx limit /// - 2022/05/27 (4.10.0) - Add nk_input_has_mouse_click_in_button_rect() to fix window move bug diff --git a/src/nuklear.h b/src/nuklear.h index 67b2aa9..03f7514 100644 --- a/src/nuklear.h +++ b/src/nuklear.h @@ -151,7 +151,7 @@ extern "C" { #elif (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER) #define NK_SIZE_TYPE unsigned __int32 #elif defined(__GNUC__) || defined(__clang__) - #if defined(__x86_64__) || defined(__ppc64__) + #if defined(__x86_64__) || defined(__ppc64__) || defined(__aarch64__) #define NK_SIZE_TYPE unsigned long #else #define NK_SIZE_TYPE unsigned int @@ -166,7 +166,7 @@ extern "C" { #elif (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER) #define NK_POINTER_TYPE unsigned __int32 #elif defined(__GNUC__) || defined(__clang__) - #if defined(__x86_64__) || defined(__ppc64__) + #if defined(__x86_64__) || defined(__ppc64__) || defined(__aarch64__) #define NK_POINTER_TYPE unsigned long #else #define NK_POINTER_TYPE unsigned int From a74061af6d5d697c1262cd26d88b8458b761d139 Mon Sep 17 00:00:00 2001 From: dczheng Date: Fri, 23 Sep 2022 00:27:48 +0800 Subject: [PATCH 015/106] Fix typo --- nuklear.h | 2 +- src/nuklear_font.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nuklear.h b/nuklear.h index bb5917c..72a423d 100644 --- a/nuklear.h +++ b/nuklear.h @@ -16512,7 +16512,7 @@ nk_font_chinese_glyph_ranges(void) 0x3000, 0x30FF, 0x31F0, 0x31FF, 0xFF00, 0xFFEF, - 0x4e00, 0x9FAF, + 0x4E00, 0x9FAF, 0 }; return ranges; diff --git a/src/nuklear_font.c b/src/nuklear_font.c index 541bf48..073971c 100644 --- a/src/nuklear_font.c +++ b/src/nuklear_font.c @@ -85,7 +85,7 @@ nk_font_chinese_glyph_ranges(void) 0x3000, 0x30FF, 0x31F0, 0x31FF, 0xFF00, 0xFFEF, - 0x4e00, 0x9FAF, + 0x4E00, 0x9FAF, 0 }; return ranges; From 6a429eca62ceec9009b3df9f45d08ba67d05476d Mon Sep 17 00:00:00 2001 From: Richard Gill Date: Mon, 3 Oct 2022 21:11:12 +0200 Subject: [PATCH 016/106] cleanup xlib text drawing fixes #502 --- demo/x11/nuklear_xlib.h | 39 ++++++++++++++++--------------------- demo/x11_xft/nuklear_xlib.h | 13 ++++--------- 2 files changed, 21 insertions(+), 31 deletions(-) diff --git a/demo/x11/nuklear_xlib.h b/demo/x11/nuklear_xlib.h index 772ac56..0d71dee 100644 --- a/demo/x11/nuklear_xlib.h +++ b/demo/x11/nuklear_xlib.h @@ -385,15 +385,12 @@ nk_xsurf_stroke_curve(XSurface *surf, struct nk_vec2i p1, } NK_INTERN void -nk_xsurf_draw_text(XSurface *surf, short x, short y, unsigned short w, unsigned short h, - const char *text, int len, XFont *font, struct nk_color cbg, struct nk_color cfg) +nk_xsurf_draw_text(XSurface *surf, short x, short y, const char *text, int len, + XFont *font, struct nk_color cfg) { int tx, ty; - unsigned long bg = nk_color_from_byte(&cbg.r); unsigned long fg = nk_color_from_byte(&cfg.r); - XSetForeground(surf->dpy, surf->gc, bg); - XFillRectangle(surf->dpy, surf->drawable, surf->gc, (int)x, (int)y, (unsigned)w, (unsigned)h); if(!text || !font || !len) return; tx = (int)x; @@ -413,10 +410,10 @@ nk_stbi_image_to_xsurf(unsigned char *data, int width, int height, int channels) int bpl = channels; long i, isize = width*height*channels; XImageWithAlpha *aimage = (XImageWithAlpha*)calloc( 1, sizeof(XImageWithAlpha) ); - int depth = DefaultDepth(surf->dpy, surf->screen); + int depth = DefaultDepth(surf->dpy, surf->screen); if (data == NULL) return nk_image_id(0); if (aimage == NULL) return nk_image_id(0); - + switch (depth){ case 24: bpl = 4; @@ -429,7 +426,7 @@ nk_stbi_image_to_xsurf(unsigned char *data, int width, int height, int channels) bpl = 1; break; } - + /* rgba to bgra */ if (channels >= 3){ for (i=0; i < isize; i += channels) { @@ -441,9 +438,9 @@ nk_stbi_image_to_xsurf(unsigned char *data, int width, int height, int channels) } if (channels == 4){ - const unsigned alpha_treshold = 127; + const unsigned alpha_treshold = 127; aimage->clipMask = XCreatePixmap(surf->dpy, surf->drawable, width, height, 1); - + if( aimage->clipMask ){ aimage->clipMaskGC = XCreateGC(surf->dpy, aimage->clipMask, 0, 0); XSetForeground(surf->dpy, aimage->clipMaskGC, BlackPixel(surf->dpy, surf->screen)); @@ -460,13 +457,13 @@ nk_stbi_image_to_xsurf(unsigned char *data, int width, int height, int channels) } } } - - aimage->ximage = XCreateImage(surf->dpy, - CopyFromParent, depth, - ZPixmap, 0, - (char*)data, - width, height, - bpl*8, bpl * width); + + aimage->ximage = XCreateImage(surf->dpy, + CopyFromParent, depth, + ZPixmap, 0, + (char*)data, + width, height, + bpl*8, bpl * width); img = nk_image_ptr( (void*)aimage); img.h = height; img.w = width; @@ -503,7 +500,7 @@ nk_xsurf_draw_image(XSurface *surf, short x, short y, unsigned short w, unsigned if (aimage){ if (aimage->clipMask){ XSetClipMask(surf->dpy, surf->gc, aimage->clipMask); - XSetClipOrigin(surf->dpy, surf->gc, x, y); + XSetClipOrigin(surf->dpy, surf->gc, x, y); } XPutImage(surf->dpy, surf->drawable, surf->gc, aimage->ximage, 0, 0, x, y, w, h); XSetClipMask(surf->dpy, surf->gc, None); @@ -939,10 +936,8 @@ nk_xlib_render(Drawable screen, struct nk_color clear) } break; case NK_COMMAND_TEXT: { const struct nk_command_text *t = (const struct nk_command_text*)cmd; - nk_xsurf_draw_text(surf, t->x, t->y, t->w, t->h, - (const char*)t->string, t->length, - (XFont*)t->font->userdata.ptr, - t->background, t->foreground); + nk_xsurf_draw_text(surf, t->x, t->y, (const char*)t->string, t->length, + (XFont*)t->font->userdata.ptr, t->foreground); } break; case NK_COMMAND_CURVE: { const struct nk_command_curve *q = (const struct nk_command_curve *)cmd; diff --git a/demo/x11_xft/nuklear_xlib.h b/demo/x11_xft/nuklear_xlib.h index 7fbcd47..5728e8f 100644 --- a/demo/x11_xft/nuklear_xlib.h +++ b/demo/x11_xft/nuklear_xlib.h @@ -417,8 +417,8 @@ nk_xsurf_stroke_curve(XSurface *surf, struct nk_vec2i p1, } NK_INTERN void -nk_xsurf_draw_text(XSurface *surf, short x, short y, unsigned short w, unsigned short h, - const char *text, int len, XFont *font, struct nk_color cbg, struct nk_color cfg) +nk_xsurf_draw_text(XSurface *surf, short x, short y, const char *text, int len, + XFont *font, struct nk_color cfg) { #ifdef NK_XLIB_USE_XFT XRenderColor xrc; @@ -426,11 +426,8 @@ nk_xsurf_draw_text(XSurface *surf, short x, short y, unsigned short w, unsigned #else unsigned long fg = nk_color_from_byte(&cfg.r); #endif - unsigned long bg = nk_color_from_byte(&cbg.r); int tx, ty; - XSetForeground(surf->dpy, surf->gc, bg); - XFillRectangle(surf->dpy, surf->drawable, surf->gc, (int)x, (int)y, (unsigned)w, (unsigned)h); if(!text || !font || !len) return; tx = (int)x; @@ -1024,10 +1021,8 @@ nk_xlib_render(Drawable screen, struct nk_color clear) } break; case NK_COMMAND_TEXT: { const struct nk_command_text *t = (const struct nk_command_text*)cmd; - nk_xsurf_draw_text(surf, t->x, t->y, t->w, t->h, - (const char*)t->string, t->length, - (XFont*)t->font->userdata.ptr, - t->background, t->foreground); + nk_xsurf_draw_text(surf, t->x, t->y, (const char*)t->string, t->length, + (XFont*)t->font->userdata.ptr, t->foreground); } break; case NK_COMMAND_CURVE: { const struct nk_command_curve *q = (const struct nk_command_curve *)cmd; From fc5ce1c495d88a920c0c475dc48f5370aed71138 Mon Sep 17 00:00:00 2001 From: Richard Gill Date: Wed, 12 Oct 2022 21:19:45 +0200 Subject: [PATCH 017/106] demos: set style with defines To avoid having to modify the demo code, conditionnally include a predefined style --- demo/allegro5/main.c | 15 +++++++++++---- demo/d3d11/main.c | 13 +++++++++---- demo/d3d12/main.c | 17 +++++++++++------ demo/d3d9/main.c | 13 +++++++++---- demo/gdi/main.c | 13 +++++++++---- demo/gdip/main.c | 13 +++++++++---- demo/glfw_opengl2/main.c | 23 ++++++++++++++--------- demo/glfw_opengl3/main.c | 13 +++++++++---- demo/glfw_opengl4/main.c | 13 +++++++++---- demo/sdl_opengl2/main.c | 13 +++++++++---- demo/sdl_opengl3/main.c | 13 +++++++++---- demo/sdl_opengles2/main.c | 13 +++++++++---- demo/sdl_renderer/main.c | 13 +++++++++---- demo/sfml_opengl2/main.cpp | 13 +++++++++---- demo/sfml_opengl3/main.cpp | 13 +++++++++---- demo/x11/main.c | 13 +++++++++---- demo/x11_opengl2/main.c | 13 +++++++++---- demo/x11_opengl3/main.c | 13 +++++++++---- demo/x11_rawfb/main.c | 13 +++++++++---- demo/x11_xft/main.c | 13 +++++++++---- 20 files changed, 189 insertions(+), 87 deletions(-) diff --git a/demo/allegro5/main.c b/demo/allegro5/main.c index 24a27ba..0c0f88c 100644 --- a/demo/allegro5/main.c +++ b/demo/allegro5/main.c @@ -115,10 +115,17 @@ int main(void) ctx = nk_allegro5_init(font, display, WINDOW_WIDTH, WINDOW_HEIGHT); /* style.c */ - /*set_style(ctx, THEME_WHITE);*/ - /*set_style(ctx, THEME_RED);*/ - /*set_style(ctx, THEME_BLUE);*/ - /*set_style(ctx, THEME_DARK);*/ + #ifdef INCLUDE_STYLE + #ifdef STYLE_WHITE + set_style(ctx, THEME_WHITE); + #elif defined(STYLE_RED) + set_style(ctx, THEME_RED); + #elif defined(STYLE_BLUE) + set_style(ctx, THEME_BLUE); + #elif defined(STYLE_DARK) + set_style(ctx, THEME_DARK); + #endif + #endif while(1) { diff --git a/demo/d3d11/main.c b/demo/d3d11/main.c index e890150..f059ea0 100644 --- a/demo/d3d11/main.c +++ b/demo/d3d11/main.c @@ -210,10 +210,15 @@ int main(void) /* style.c */ #ifdef INCLUDE_STYLE - /*set_style(ctx, THEME_WHITE);*/ - /*set_style(ctx, THEME_RED);*/ - /*set_style(ctx, THEME_BLUE);*/ - /*set_style(ctx, THEME_DARK);*/ + #ifdef STYLE_WHITE + set_style(ctx, THEME_WHITE); + #elif defined(STYLE_RED) + set_style(ctx, THEME_RED); + #elif defined(STYLE_BLUE) + set_style(ctx, THEME_BLUE); + #elif defined(STYLE_DARK) + set_style(ctx, THEME_DARK); + #endif #endif bg.r = 0.10f, bg.g = 0.18f, bg.b = 0.24f, bg.a = 1.0f; diff --git a/demo/d3d12/main.c b/demo/d3d12/main.c index d8bb406..005ce10 100644 --- a/demo/d3d12/main.c +++ b/demo/d3d12/main.c @@ -191,7 +191,7 @@ WindowProc(HWND wnd, UINT msg, WPARAM wparam, LPARAM lparam) } int main(void) -{ +{ struct nk_context *ctx; struct nk_colorf bg; @@ -278,7 +278,7 @@ int main(void) /* GUI */ ctx = nk_d3d12_init(device, WINDOW_WIDTH, WINDOW_HEIGHT, MAX_VERTEX_BUFFER, MAX_INDEX_BUFFER, USER_TEXTURES); - + /* Load Fonts: if none of these are loaded a default font will be used */ /* Load Cursor: if you uncomment cursor loading please hide the cursor */ { @@ -302,10 +302,15 @@ int main(void) /* style.c */ #ifdef INCLUDE_STYLE - /*set_style(ctx, THEME_WHITE);*/ - /*set_style(ctx, THEME_RED);*/ - /*set_style(ctx, THEME_BLUE);*/ - /*set_style(ctx, THEME_DARK);*/ + #ifdef STYLE_WHITE + set_style(ctx, THEME_WHITE); + #elif defined(STYLE_RED) + set_style(ctx, THEME_RED); + #elif defined(STYLE_BLUE) + set_style(ctx, THEME_BLUE); + #elif defined(STYLE_DARK) + set_style(ctx, THEME_DARK); + #endif #endif bg.r = 0.10f, bg.g = 0.18f, bg.b = 0.24f, bg.a = 1.0f; diff --git a/demo/d3d9/main.c b/demo/d3d9/main.c index de85e92..762ee02 100644 --- a/demo/d3d9/main.c +++ b/demo/d3d9/main.c @@ -216,10 +216,15 @@ int main(void) /* style.c */ #ifdef INCLUDE_STYLE - /*set_style(ctx, THEME_WHITE);*/ - /*set_style(ctx, THEME_RED);*/ - /*set_style(ctx, THEME_BLUE);*/ - /*set_style(ctx, THEME_DARK);*/ + #ifdef STYLE_WHITE + set_style(ctx, THEME_WHITE); + #elif defined(STYLE_RED) + set_style(ctx, THEME_RED); + #elif defined(STYLE_BLUE) + set_style(ctx, THEME_BLUE); + #elif defined(STYLE_DARK) + set_style(ctx, THEME_DARK); + #endif #endif bg.r = 0.10f, bg.g = 0.18f, bg.b = 0.24f, bg.a = 1.0f; diff --git a/demo/gdi/main.c b/demo/gdi/main.c index 1451323..0c08c39 100644 --- a/demo/gdi/main.c +++ b/demo/gdi/main.c @@ -115,10 +115,15 @@ int main(void) /* style.c */ #ifdef INCLUDE_STYLE - /*set_style(ctx, THEME_WHITE);*/ - /*set_style(ctx, THEME_RED);*/ - /*set_style(ctx, THEME_BLUE);*/ - /*set_style(ctx, THEME_DARK);*/ + #ifdef STYLE_WHITE + set_style(ctx, THEME_WHITE); + #elif defined(STYLE_RED) + set_style(ctx, THEME_RED); + #elif defined(STYLE_BLUE) + set_style(ctx, THEME_BLUE); + #elif defined(STYLE_DARK) + set_style(ctx, THEME_DARK); + #endif #endif while (running) diff --git a/demo/gdip/main.c b/demo/gdip/main.c index 69bd83a..11f5aa3 100644 --- a/demo/gdip/main.c +++ b/demo/gdip/main.c @@ -111,10 +111,15 @@ int main(void) /* style.c */ #ifdef INCLUDE_STYLE - /*set_style(ctx, THEME_WHITE);*/ - /*set_style(ctx, THEME_RED);*/ - /*set_style(ctx, THEME_BLUE);*/ - /*set_style(ctx, THEME_DARK);*/ + #ifdef STYLE_WHITE + set_style(ctx, THEME_WHITE); + #elif defined(STYLE_RED) + set_style(ctx, THEME_RED); + #elif defined(STYLE_BLUE) + set_style(ctx, THEME_BLUE); + #elif defined(STYLE_DARK) + set_style(ctx, THEME_DARK); + #endif #endif while (running) diff --git a/demo/glfw_opengl2/main.c b/demo/glfw_opengl2/main.c index 6a89e4b..0401626 100644 --- a/demo/glfw_opengl2/main.c +++ b/demo/glfw_opengl2/main.c @@ -85,7 +85,7 @@ int main(void) /* Platform */ static GLFWwindow *win; int width = 0, height = 0; - + /* GUI */ struct nk_context *ctx; struct nk_colorf bg; @@ -121,14 +121,19 @@ int main(void) /*nk_style_set_font(ctx, &droid->handle);*/} #ifdef INCLUDE_STYLE - /*set_style(ctx, THEME_WHITE);*/ - /*set_style(ctx, THEME_RED);*/ - /*set_style(ctx, THEME_BLUE);*/ - /*set_style(ctx, THEME_DARK);*/ + #ifdef STYLE_WHITE + set_style(ctx, THEME_WHITE); + #elif defined(STYLE_RED) + set_style(ctx, THEME_RED); + #elif defined(STYLE_BLUE) + set_style(ctx, THEME_BLUE); + #elif defined(STYLE_DARK) + set_style(ctx, THEME_DARK); + #endif #endif bg.r = 0.10f, bg.g = 0.18f, bg.b = 0.24f, bg.a = 1.0f; - + #ifdef INCLUDE_FILE_BROWSER /* icons */ glEnable(GL_TEXTURE_2D); @@ -219,7 +224,7 @@ int main(void) glfwSwapBuffers(win); } - #ifdef INCLUDE_FILE_BROWSER + #ifdef INCLUDE_FILE_BROWSER glDeleteTextures(1,(const GLuint*)&media.icons.home.handle.id); glDeleteTextures(1,(const GLuint*)&media.icons.directory.handle.id); glDeleteTextures(1,(const GLuint*)&media.icons.computer.handle.id); @@ -232,8 +237,8 @@ int main(void) glDeleteTextures(1,(const GLuint*)&media.icons.movie_file.handle.id); file_browser_free(&browser); - #endif - + #endif + nk_glfw3_shutdown(); glfwTerminate(); return 0; diff --git a/demo/glfw_opengl3/main.c b/demo/glfw_opengl3/main.c index d8eda87..a4346d9 100644 --- a/demo/glfw_opengl3/main.c +++ b/demo/glfw_opengl3/main.c @@ -126,10 +126,15 @@ int main(void) /*nk_style_set_font(ctx, &droid->handle);*/} #ifdef INCLUDE_STYLE - /*set_style(ctx, THEME_WHITE);*/ - /*set_style(ctx, THEME_RED);*/ - /*set_style(ctx, THEME_BLUE);*/ - /*set_style(ctx, THEME_DARK);*/ + #ifdef STYLE_WHITE + set_style(ctx, THEME_WHITE); + #elif defined(STYLE_RED) + set_style(ctx, THEME_RED); + #elif defined(STYLE_BLUE) + set_style(ctx, THEME_BLUE); + #elif defined(STYLE_DARK) + set_style(ctx, THEME_DARK); + #endif #endif bg.r = 0.10f, bg.g = 0.18f, bg.b = 0.24f, bg.a = 1.0f; diff --git a/demo/glfw_opengl4/main.c b/demo/glfw_opengl4/main.c index 75783bd..7b7c093 100644 --- a/demo/glfw_opengl4/main.c +++ b/demo/glfw_opengl4/main.c @@ -126,10 +126,15 @@ int main(void) /*nk_style_set_font(ctx, &droid->handle);*/} #ifdef INCLUDE_STYLE - /*set_style(ctx, THEME_WHITE);*/ - /*set_style(ctx, THEME_RED);*/ - /*set_style(ctx, THEME_BLUE);*/ - /*set_style(ctx, THEME_DARK);*/ + #ifdef STYLE_WHITE + set_style(ctx, THEME_WHITE); + #elif defined(STYLE_RED) + set_style(ctx, THEME_RED); + #elif defined(STYLE_BLUE) + set_style(ctx, THEME_BLUE); + #elif defined(STYLE_DARK) + set_style(ctx, THEME_DARK); + #endif #endif /* Create bindless texture. diff --git a/demo/sdl_opengl2/main.c b/demo/sdl_opengl2/main.c index cd1071e..eb09427c 100644 --- a/demo/sdl_opengl2/main.c +++ b/demo/sdl_opengl2/main.c @@ -117,10 +117,15 @@ main(int argc, char *argv[]) /*nk_style_set_font(ctx, &roboto->handle)*/;} #ifdef INCLUDE_STYLE - /*set_style(ctx, THEME_WHITE);*/ - /*set_style(ctx, THEME_RED);*/ - /*set_style(ctx, THEME_BLUE);*/ - /*set_style(ctx, THEME_DARK);*/ + #ifdef STYLE_WHITE + set_style(ctx, THEME_WHITE); + #elif defined(STYLE_RED) + set_style(ctx, THEME_RED); + #elif defined(STYLE_BLUE) + set_style(ctx, THEME_BLUE); + #elif defined(STYLE_DARK) + set_style(ctx, THEME_DARK); + #endif #endif bg.r = 0.10f, bg.g = 0.18f, bg.b = 0.24f, bg.a = 1.0f; diff --git a/demo/sdl_opengl3/main.c b/demo/sdl_opengl3/main.c index 97351f5..cc9388b 100644 --- a/demo/sdl_opengl3/main.c +++ b/demo/sdl_opengl3/main.c @@ -128,10 +128,15 @@ int main(int argc, char *argv[]) /* style.c */ #ifdef INCLUDE_STYLE - /*set_style(ctx, THEME_WHITE);*/ - /*set_style(ctx, THEME_RED);*/ - /*set_style(ctx, THEME_BLUE);*/ - /*set_style(ctx, THEME_DARK);*/ + #ifdef STYLE_WHITE + set_style(ctx, THEME_WHITE); + #elif defined(STYLE_RED) + set_style(ctx, THEME_RED); + #elif defined(STYLE_BLUE) + set_style(ctx, THEME_BLUE); + #elif defined(STYLE_DARK) + set_style(ctx, THEME_DARK); + #endif #endif bg.r = 0.10f, bg.g = 0.18f, bg.b = 0.24f, bg.a = 1.0f; diff --git a/demo/sdl_opengles2/main.c b/demo/sdl_opengles2/main.c index 80a4285..4048381 100644 --- a/demo/sdl_opengles2/main.c +++ b/demo/sdl_opengles2/main.c @@ -209,10 +209,15 @@ int main(int argc, char* argv[]) /*nk_style_set_font(ctx, &roboto->handle)*/;} /* style.c */ - /*set_style(ctx, THEME_WHITE);*/ - /*set_style(ctx, THEME_RED);*/ - /*set_style(ctx, THEME_BLUE);*/ - /*set_style(ctx, THEME_DARK);*/ + #ifdef STYLE_WHITE + set_style(ctx, THEME_WHITE); + #elif defined(STYLE_RED) + set_style(ctx, THEME_RED); + #elif defined(STYLE_BLUE) + set_style(ctx, THEME_BLUE); + #elif defined(STYLE_DARK) + set_style(ctx, THEME_DARK); + #endif #if defined(__EMSCRIPTEN__) #include diff --git a/demo/sdl_renderer/main.c b/demo/sdl_renderer/main.c index d50f16c..09cc83b 100644 --- a/demo/sdl_renderer/main.c +++ b/demo/sdl_renderer/main.c @@ -155,10 +155,15 @@ main(int argc, char *argv[]) } #ifdef INCLUDE_STYLE - /*set_style(ctx, THEME_WHITE);*/ - /*set_style(ctx, THEME_RED);*/ - /*set_style(ctx, THEME_BLUE);*/ - /*set_style(ctx, THEME_DARK);*/ + #ifdef STYLE_WHITE + set_style(ctx, THEME_WHITE); + #elif defined(STYLE_RED) + set_style(ctx, THEME_RED); + #elif defined(STYLE_BLUE) + set_style(ctx, THEME_BLUE); + #elif defined(STYLE_DARK) + set_style(ctx, THEME_DARK); + #endif #endif bg.r = 0.10f, bg.g = 0.18f, bg.b = 0.24f, bg.a = 1.0f; diff --git a/demo/sfml_opengl2/main.cpp b/demo/sfml_opengl2/main.cpp index e8ebaba..ca5ecd2 100644 --- a/demo/sfml_opengl2/main.cpp +++ b/demo/sfml_opengl2/main.cpp @@ -98,10 +98,15 @@ int main(void) /* style.c */ #ifdef INCLUDE_STYLE - /*set_style(ctx, THEME_WHITE);*/ - /*set_style(ctx, THEME_RED);*/ - /*set_style(ctx, THEME_BLUE);*/ - /*set_style(ctx, THEME_DARK);*/ + #ifdef STYLE_WHITE + set_style(ctx, THEME_WHITE); + #elif defined(STYLE_RED) + set_style(ctx, THEME_RED); + #elif defined(STYLE_BLUE) + set_style(ctx, THEME_BLUE); + #elif defined(STYLE_DARK) + set_style(ctx, THEME_DARK); + #endif #endif struct nk_colorf bg; diff --git a/demo/sfml_opengl3/main.cpp b/demo/sfml_opengl3/main.cpp index b2568e7..f772057 100644 --- a/demo/sfml_opengl3/main.cpp +++ b/demo/sfml_opengl3/main.cpp @@ -104,10 +104,15 @@ int main(void) /* style.c */ #ifdef INCLUDE_STYLE - /*set_style(ctx, THEME_WHITE);*/ - /*set_style(ctx, THEME_RED);*/ - /*set_style(ctx, THEME_BLUE);*/ - /*set_style(ctx, THEME_DARK);*/ + #ifdef STYLE_WHITE + set_style(ctx, THEME_WHITE); + #elif defined(STYLE_RED) + set_style(ctx, THEME_RED); + #elif defined(STYLE_BLUE) + set_style(ctx, THEME_BLUE); + #elif defined(STYLE_DARK) + set_style(ctx, THEME_DARK); + #endif #endif struct nk_colorf bg; diff --git a/demo/x11/main.c b/demo/x11/main.c index 16bf043..c93ae78 100644 --- a/demo/x11/main.c +++ b/demo/x11/main.c @@ -153,10 +153,15 @@ main(void) ctx = nk_xlib_init(xw.font, xw.dpy, xw.screen, xw.win, xw.width, xw.height); #ifdef INCLUDE_STYLE - /*set_style(ctx, THEME_WHITE);*/ - /*set_style(ctx, THEME_RED);*/ - /*set_style(ctx, THEME_BLUE);*/ - /*set_style(ctx, THEME_DARK);*/ + #ifdef STYLE_WHITE + set_style(ctx, THEME_WHITE); + #elif defined(STYLE_RED) + set_style(ctx, THEME_RED); + #elif defined(STYLE_BLUE) + set_style(ctx, THEME_BLUE); + #elif defined(STYLE_DARK) + set_style(ctx, THEME_DARK); + #endif #endif while (running) diff --git a/demo/x11_opengl2/main.c b/demo/x11_opengl2/main.c index 5145c3b..06c2ee0 100644 --- a/demo/x11_opengl2/main.c +++ b/demo/x11_opengl2/main.c @@ -257,10 +257,15 @@ int main(void) /*nk_style_set_font(ctx, &droid->handle);*/} #ifdef INCLUDE_STYLE - /*set_style(ctx, THEME_WHITE);*/ - /*set_style(ctx, THEME_RED);*/ - /*set_style(ctx, THEME_BLUE);*/ - /*set_style(ctx, THEME_DARK);*/ + #ifdef STYLE_WHITE + set_style(ctx, THEME_WHITE); + #elif defined(STYLE_RED) + set_style(ctx, THEME_RED); + #elif defined(STYLE_BLUE) + set_style(ctx, THEME_BLUE); + #elif defined(STYLE_DARK) + set_style(ctx, THEME_DARK); + #endif #endif bg.r = 0.10f, bg.g = 0.18f, bg.b = 0.24f, bg.a = 1.0f; diff --git a/demo/x11_opengl3/main.c b/demo/x11_opengl3/main.c index faaad12..5609d24 100644 --- a/demo/x11_opengl3/main.c +++ b/demo/x11_opengl3/main.c @@ -254,10 +254,15 @@ int main(void) /*nk_style_set_font(ctx, &droid->handle);*/} #ifdef INCLUDE_STYLE - /*set_style(ctx, THEME_WHITE);*/ - /*set_style(ctx, THEME_RED);*/ - /*set_style(ctx, THEME_BLUE);*/ - /*set_style(ctx, THEME_DARK);*/ + #ifdef STYLE_WHITE + set_style(ctx, THEME_WHITE); + #elif defined(STYLE_RED) + set_style(ctx, THEME_RED); + #elif defined(STYLE_BLUE) + set_style(ctx, THEME_BLUE); + #elif defined(STYLE_DARK) + set_style(ctx, THEME_DARK); + #endif #endif bg.r = 0.10f, bg.g = 0.18f, bg.b = 0.24f, bg.a = 1.0f; diff --git a/demo/x11_rawfb/main.c b/demo/x11_rawfb/main.c index ea51c1e..1e72c1e 100644 --- a/demo/x11_rawfb/main.c +++ b/demo/x11_rawfb/main.c @@ -194,10 +194,15 @@ main(void) if (!rawfb) running = 0; #ifdef INCLUDE_STYLE - /*set_style(&rawfb->ctx, THEME_WHITE);*/ - /*set_style(&rawfb->ctx, THEME_RED);*/ - /*set_style(&rawfb->ctx, THEME_BLUE);*/ - /*set_style(&rawfb->ctx, THEME_DARK);*/ + #ifdef STYLE_WHITE + set_style(&rawfb->ctx, THEME_WHITE); + #elif defined(STYLE_RED) + set_style(&rawfb->ctx, THEME_RED); + #elif defined(STYLE_BLUE) + set_style(&rawfb->ctx, THEME_BLUE); + #elif defined(STYLE_DARK) + set_style(&rawfb->ctx, THEME_DARK); + #endif #endif while (running) { diff --git a/demo/x11_xft/main.c b/demo/x11_xft/main.c index 8b2a146..e069622 100644 --- a/demo/x11_xft/main.c +++ b/demo/x11_xft/main.c @@ -157,10 +157,15 @@ main(void) xw.width, xw.height); #ifdef INCLUDE_STYLE - /*set_style(ctx, THEME_WHITE);*/ - /*set_style(ctx, THEME_RED);*/ - /*set_style(ctx, THEME_BLUE);*/ - /*set_style(ctx, THEME_DARK);*/ + #ifdef STYLE_WHITE + set_style(ctx, THEME_WHITE); + #elif defined(STYLE_RED) + set_style(ctx, THEME_RED); + #elif defined(STYLE_BLUE) + set_style(ctx, THEME_BLUE); + #elif defined(STYLE_DARK) + set_style(ctx, THEME_DARK); + #endif #endif while (running) From d63f106334f3b3a23445464cf768165bbe8709c9 Mon Sep 17 00:00:00 2001 From: Richard Gill Date: Wed, 12 Oct 2022 22:08:08 +0200 Subject: [PATCH 018/106] xlib backend: implemented arc commands --- demo/x11/nuklear_xlib.h | 33 +++++++++++++++++++++++++++++++-- demo/x11_xft/nuklear_xlib.h | 33 +++++++++++++++++++++++++++++++-- 2 files changed, 62 insertions(+), 4 deletions(-) diff --git a/demo/x11/nuklear_xlib.h b/demo/x11/nuklear_xlib.h index 0d71dee..9b3a861 100644 --- a/demo/x11/nuklear_xlib.h +++ b/demo/x11/nuklear_xlib.h @@ -357,6 +357,29 @@ nk_xsurf_stroke_circle(XSurface *surf, short x, short y, unsigned short w, XSetLineAttributes(surf->dpy, surf->gc, 1, LineSolid, CapButt, JoinMiter); } +NK_INTERN void +nk_xsurf_stroke_arc(XSurface *surf, short cx, short cy, unsigned short radius, + float a_min, float a_max, unsigned short line_thickness, struct nk_color col) +{ + unsigned long c = nk_color_from_byte(&col.r); + XSetLineAttributes(surf->dpy, surf->gc, line_thickness, LineSolid, CapButt, JoinMiter); + XSetForeground(surf->dpy, surf->gc, c); + XDrawArc(surf->dpy, surf->drawable, surf->gc, (int)(cx - radius), (int)(cy - radius), + (unsigned)(radius * 2), (unsigned)(radius * 2), + (int)(a_min * 180 * 64 / NK_PI), (int)(a_max * 180 * 64 / NK_PI)); +} + +NK_INTERN void +nk_xsurf_fill_arc(XSurface *surf, short cx, short cy, unsigned short radius, + float a_min, float a_max, struct nk_color col) +{ + unsigned long c = nk_color_from_byte(&col.r); + XSetForeground(surf->dpy, surf->gc, c); + XFillArc(surf->dpy, surf->drawable, surf->gc, (int)(cx - radius), (int)(cy - radius), + (unsigned)(radius * 2), (unsigned)(radius * 2), + (int)(a_min * 180 * 64 / NK_PI), (int)(a_max * 180 * 64 / NK_PI)); +} + NK_INTERN void nk_xsurf_stroke_curve(XSurface *surf, struct nk_vec2i p1, struct nk_vec2i p2, struct nk_vec2i p3, struct nk_vec2i p4, @@ -912,6 +935,14 @@ nk_xlib_render(Drawable screen, struct nk_color clear) const struct nk_command_circle_filled *c = (const struct nk_command_circle_filled *)cmd; nk_xsurf_fill_circle(surf, c->x, c->y, c->w, c->h, c->color); } break; + case NK_COMMAND_ARC: { + const struct nk_command_arc *a = (const struct nk_command_arc *)cmd; + nk_xsurf_stroke_arc(surf, a->cx, a->cy, a->r, a->a[0], a->a[1], a->line_thickness, a->color); + } break; + case NK_COMMAND_ARC_FILLED: { + const struct nk_command_arc_filled *a = (const struct nk_command_arc_filled *)cmd; + nk_xsurf_fill_arc(surf, a->cx, a->cy, a->r, a->a[0], a->a[1], a->color); + } break; case NK_COMMAND_TRIANGLE: { const struct nk_command_triangle*t = (const struct nk_command_triangle*)cmd; nk_xsurf_stroke_triangle(surf, t->a.x, t->a.y, t->b.x, t->b.y, @@ -949,8 +980,6 @@ nk_xlib_render(Drawable screen, struct nk_color clear) nk_xsurf_draw_image(surf, i->x, i->y, i->w, i->h, i->img, i->col); } break; case NK_COMMAND_RECT_MULTI_COLOR: - case NK_COMMAND_ARC: - case NK_COMMAND_ARC_FILLED: case NK_COMMAND_CUSTOM: default: break; } diff --git a/demo/x11_xft/nuklear_xlib.h b/demo/x11_xft/nuklear_xlib.h index 5728e8f..9526e3e 100644 --- a/demo/x11_xft/nuklear_xlib.h +++ b/demo/x11_xft/nuklear_xlib.h @@ -389,6 +389,29 @@ nk_xsurf_stroke_circle(XSurface *surf, short x, short y, unsigned short w, XSetLineAttributes(surf->dpy, surf->gc, 1, LineSolid, CapButt, JoinMiter); } +NK_INTERN void +nk_xsurf_stroke_arc(XSurface *surf, short cx, short cy, unsigned short radius, + float a_min, float a_max, unsigned short line_thickness, struct nk_color col) +{ + unsigned long c = nk_color_from_byte(&col.r); + XSetLineAttributes(surf->dpy, surf->gc, line_thickness, LineSolid, CapButt, JoinMiter); + XSetForeground(surf->dpy, surf->gc, c); + XDrawArc(surf->dpy, surf->drawable, surf->gc, (int)(cx - radius), (int)(cy - radius), + (unsigned)(radius * 2), (unsigned)(radius * 2), + (int)(a_min * 180 * 64 / NK_PI), (int)(a_max * 180 * 64 / NK_PI)); +} + +NK_INTERN void +nk_xsurf_fill_arc(XSurface *surf, short cx, short cy, unsigned short radius, + float a_min, float a_max, struct nk_color col) +{ + unsigned long c = nk_color_from_byte(&col.r); + XSetForeground(surf->dpy, surf->gc, c); + XFillArc(surf->dpy, surf->drawable, surf->gc, (int)(cx - radius), (int)(cy - radius), + (unsigned)(radius * 2), (unsigned)(radius * 2), + (int)(a_min * 180 * 64 / NK_PI), (int)(a_max * 180 * 64 / NK_PI)); +} + NK_INTERN void nk_xsurf_stroke_curve(XSurface *surf, struct nk_vec2i p1, struct nk_vec2i p2, struct nk_vec2i p3, struct nk_vec2i p4, @@ -997,6 +1020,14 @@ nk_xlib_render(Drawable screen, struct nk_color clear) const struct nk_command_circle_filled *c = (const struct nk_command_circle_filled *)cmd; nk_xsurf_fill_circle(surf, c->x, c->y, c->w, c->h, c->color); } break; + case NK_COMMAND_ARC: { + const struct nk_command_arc *a = (const struct nk_command_arc *)cmd; + nk_xsurf_stroke_arc(surf, a->cx, a->cy, a->r, a->a[0], a->a[1], a->line_thickness, a->color); + } break; + case NK_COMMAND_ARC_FILLED: { + const struct nk_command_arc_filled *a = (const struct nk_command_arc_filled *)cmd; + nk_xsurf_fill_arc(surf, a->cx, a->cy, a->r, a->a[0], a->a[1], a->color); + } break; case NK_COMMAND_TRIANGLE: { const struct nk_command_triangle*t = (const struct nk_command_triangle*)cmd; nk_xsurf_stroke_triangle(surf, t->a.x, t->a.y, t->b.x, t->b.y, @@ -1034,8 +1065,6 @@ nk_xlib_render(Drawable screen, struct nk_color clear) nk_xsurf_draw_image(surf, i->x, i->y, i->w, i->h, i->img, i->col); } break; case NK_COMMAND_RECT_MULTI_COLOR: - case NK_COMMAND_ARC: - case NK_COMMAND_ARC_FILLED: case NK_COMMAND_CUSTOM: default: break; } From 54cd692d17d1cf22e452c31c18b8f5921fdf1610 Mon Sep 17 00:00:00 2001 From: Richard Gill Date: Thu, 13 Oct 2022 11:51:50 +0200 Subject: [PATCH 019/106] added comment on ifdefs to use styles in demos --- demo/allegro5/main.c | 1 + demo/d3d11/main.c | 1 + demo/d3d12/main.c | 1 + demo/d3d9/main.c | 1 + demo/gdi/main.c | 1 + demo/gdip/main.c | 1 + demo/glfw_opengl2/main.c | 1 + demo/glfw_opengl3/main.c | 1 + demo/glfw_opengl4/main.c | 1 + demo/sdl_opengl2/main.c | 1 + demo/sdl_opengl3/main.c | 1 + demo/sdl_opengles2/main.c | 3 +++ demo/sdl_renderer/main.c | 1 + demo/sfml_opengl2/main.cpp | 1 + demo/sfml_opengl3/main.cpp | 1 + demo/x11/main.c | 1 + demo/x11_opengl2/main.c | 1 + demo/x11_opengl3/main.c | 1 + demo/x11_rawfb/main.c | 1 + demo/x11_xft/main.c | 1 + 20 files changed, 22 insertions(+) diff --git a/demo/allegro5/main.c b/demo/allegro5/main.c index 0c0f88c..ee01de7 100644 --- a/demo/allegro5/main.c +++ b/demo/allegro5/main.c @@ -116,6 +116,7 @@ int main(void) /* style.c */ #ifdef INCLUDE_STYLE + /* ease regression testing during Nuklear release process; not needed for anything else */ #ifdef STYLE_WHITE set_style(ctx, THEME_WHITE); #elif defined(STYLE_RED) diff --git a/demo/d3d11/main.c b/demo/d3d11/main.c index f059ea0..ff2ac95 100644 --- a/demo/d3d11/main.c +++ b/demo/d3d11/main.c @@ -210,6 +210,7 @@ int main(void) /* style.c */ #ifdef INCLUDE_STYLE + /* ease regression testing during Nuklear release process; not needed for anything else */ #ifdef STYLE_WHITE set_style(ctx, THEME_WHITE); #elif defined(STYLE_RED) diff --git a/demo/d3d12/main.c b/demo/d3d12/main.c index 005ce10..f6891e5 100644 --- a/demo/d3d12/main.c +++ b/demo/d3d12/main.c @@ -302,6 +302,7 @@ int main(void) /* style.c */ #ifdef INCLUDE_STYLE + /* ease regression testing during Nuklear release process; not needed for anything else */ #ifdef STYLE_WHITE set_style(ctx, THEME_WHITE); #elif defined(STYLE_RED) diff --git a/demo/d3d9/main.c b/demo/d3d9/main.c index 762ee02..c6b8a5d 100644 --- a/demo/d3d9/main.c +++ b/demo/d3d9/main.c @@ -216,6 +216,7 @@ int main(void) /* style.c */ #ifdef INCLUDE_STYLE + /* ease regression testing during Nuklear release process; not needed for anything else */ #ifdef STYLE_WHITE set_style(ctx, THEME_WHITE); #elif defined(STYLE_RED) diff --git a/demo/gdi/main.c b/demo/gdi/main.c index 0c08c39..f588c07 100644 --- a/demo/gdi/main.c +++ b/demo/gdi/main.c @@ -115,6 +115,7 @@ int main(void) /* style.c */ #ifdef INCLUDE_STYLE + /* ease regression testing during Nuklear release process; not needed for anything else */ #ifdef STYLE_WHITE set_style(ctx, THEME_WHITE); #elif defined(STYLE_RED) diff --git a/demo/gdip/main.c b/demo/gdip/main.c index 11f5aa3..8f132f5 100644 --- a/demo/gdip/main.c +++ b/demo/gdip/main.c @@ -111,6 +111,7 @@ int main(void) /* style.c */ #ifdef INCLUDE_STYLE + /* ease regression testing during Nuklear release process; not needed for anything else */ #ifdef STYLE_WHITE set_style(ctx, THEME_WHITE); #elif defined(STYLE_RED) diff --git a/demo/glfw_opengl2/main.c b/demo/glfw_opengl2/main.c index 0401626..8d97773 100644 --- a/demo/glfw_opengl2/main.c +++ b/demo/glfw_opengl2/main.c @@ -121,6 +121,7 @@ int main(void) /*nk_style_set_font(ctx, &droid->handle);*/} #ifdef INCLUDE_STYLE + /* ease regression testing during Nuklear release process; not needed for anything else */ #ifdef STYLE_WHITE set_style(ctx, THEME_WHITE); #elif defined(STYLE_RED) diff --git a/demo/glfw_opengl3/main.c b/demo/glfw_opengl3/main.c index a4346d9..8eb749d 100644 --- a/demo/glfw_opengl3/main.c +++ b/demo/glfw_opengl3/main.c @@ -126,6 +126,7 @@ int main(void) /*nk_style_set_font(ctx, &droid->handle);*/} #ifdef INCLUDE_STYLE + /* ease regression testing during Nuklear release process; not needed for anything else */ #ifdef STYLE_WHITE set_style(ctx, THEME_WHITE); #elif defined(STYLE_RED) diff --git a/demo/glfw_opengl4/main.c b/demo/glfw_opengl4/main.c index 7b7c093..176a1ef 100644 --- a/demo/glfw_opengl4/main.c +++ b/demo/glfw_opengl4/main.c @@ -126,6 +126,7 @@ int main(void) /*nk_style_set_font(ctx, &droid->handle);*/} #ifdef INCLUDE_STYLE + /* ease regression testing during Nuklear release process; not needed for anything else */ #ifdef STYLE_WHITE set_style(ctx, THEME_WHITE); #elif defined(STYLE_RED) diff --git a/demo/sdl_opengl2/main.c b/demo/sdl_opengl2/main.c index eb09427c..45c51d2 100644 --- a/demo/sdl_opengl2/main.c +++ b/demo/sdl_opengl2/main.c @@ -117,6 +117,7 @@ main(int argc, char *argv[]) /*nk_style_set_font(ctx, &roboto->handle)*/;} #ifdef INCLUDE_STYLE + /* ease regression testing during Nuklear release process; not needed for anything else */ #ifdef STYLE_WHITE set_style(ctx, THEME_WHITE); #elif defined(STYLE_RED) diff --git a/demo/sdl_opengl3/main.c b/demo/sdl_opengl3/main.c index cc9388b..e039a2f 100644 --- a/demo/sdl_opengl3/main.c +++ b/demo/sdl_opengl3/main.c @@ -128,6 +128,7 @@ int main(int argc, char *argv[]) /* style.c */ #ifdef INCLUDE_STYLE + /* ease regression testing during Nuklear release process; not needed for anything else */ #ifdef STYLE_WHITE set_style(ctx, THEME_WHITE); #elif defined(STYLE_RED) diff --git a/demo/sdl_opengles2/main.c b/demo/sdl_opengles2/main.c index 4048381..b114159 100644 --- a/demo/sdl_opengles2/main.c +++ b/demo/sdl_opengles2/main.c @@ -209,6 +209,8 @@ int main(int argc, char* argv[]) /*nk_style_set_font(ctx, &roboto->handle)*/;} /* style.c */ + #ifdef INCLUDE_STYLE + /* ease regression testing during Nuklear release process; not needed for anything else */ #ifdef STYLE_WHITE set_style(ctx, THEME_WHITE); #elif defined(STYLE_RED) @@ -218,6 +220,7 @@ int main(int argc, char* argv[]) #elif defined(STYLE_DARK) set_style(ctx, THEME_DARK); #endif + #endif #if defined(__EMSCRIPTEN__) #include diff --git a/demo/sdl_renderer/main.c b/demo/sdl_renderer/main.c index 09cc83b..940ea84 100644 --- a/demo/sdl_renderer/main.c +++ b/demo/sdl_renderer/main.c @@ -155,6 +155,7 @@ main(int argc, char *argv[]) } #ifdef INCLUDE_STYLE + /* ease regression testing during Nuklear release process; not needed for anything else */ #ifdef STYLE_WHITE set_style(ctx, THEME_WHITE); #elif defined(STYLE_RED) diff --git a/demo/sfml_opengl2/main.cpp b/demo/sfml_opengl2/main.cpp index ca5ecd2..82f8e0f 100644 --- a/demo/sfml_opengl2/main.cpp +++ b/demo/sfml_opengl2/main.cpp @@ -98,6 +98,7 @@ int main(void) /* style.c */ #ifdef INCLUDE_STYLE + /* ease regression testing during Nuklear release process; not needed for anything else */ #ifdef STYLE_WHITE set_style(ctx, THEME_WHITE); #elif defined(STYLE_RED) diff --git a/demo/sfml_opengl3/main.cpp b/demo/sfml_opengl3/main.cpp index f772057..22aafcc 100644 --- a/demo/sfml_opengl3/main.cpp +++ b/demo/sfml_opengl3/main.cpp @@ -104,6 +104,7 @@ int main(void) /* style.c */ #ifdef INCLUDE_STYLE + /* ease regression testing during Nuklear release process; not needed for anything else */ #ifdef STYLE_WHITE set_style(ctx, THEME_WHITE); #elif defined(STYLE_RED) diff --git a/demo/x11/main.c b/demo/x11/main.c index c93ae78..0d02ad7 100644 --- a/demo/x11/main.c +++ b/demo/x11/main.c @@ -153,6 +153,7 @@ main(void) ctx = nk_xlib_init(xw.font, xw.dpy, xw.screen, xw.win, xw.width, xw.height); #ifdef INCLUDE_STYLE + /* ease regression testing during Nuklear release process; not needed for anything else */ #ifdef STYLE_WHITE set_style(ctx, THEME_WHITE); #elif defined(STYLE_RED) diff --git a/demo/x11_opengl2/main.c b/demo/x11_opengl2/main.c index 06c2ee0..2dc845e 100644 --- a/demo/x11_opengl2/main.c +++ b/demo/x11_opengl2/main.c @@ -257,6 +257,7 @@ int main(void) /*nk_style_set_font(ctx, &droid->handle);*/} #ifdef INCLUDE_STYLE + /* ease regression testing during Nuklear release process; not needed for anything else */ #ifdef STYLE_WHITE set_style(ctx, THEME_WHITE); #elif defined(STYLE_RED) diff --git a/demo/x11_opengl3/main.c b/demo/x11_opengl3/main.c index 5609d24..a4a3008 100644 --- a/demo/x11_opengl3/main.c +++ b/demo/x11_opengl3/main.c @@ -254,6 +254,7 @@ int main(void) /*nk_style_set_font(ctx, &droid->handle);*/} #ifdef INCLUDE_STYLE + /* ease regression testing during Nuklear release process; not needed for anything else */ #ifdef STYLE_WHITE set_style(ctx, THEME_WHITE); #elif defined(STYLE_RED) diff --git a/demo/x11_rawfb/main.c b/demo/x11_rawfb/main.c index 1e72c1e..52a1c93 100644 --- a/demo/x11_rawfb/main.c +++ b/demo/x11_rawfb/main.c @@ -194,6 +194,7 @@ main(void) if (!rawfb) running = 0; #ifdef INCLUDE_STYLE + /* ease regression testing during Nuklear release process; not needed for anything else */ #ifdef STYLE_WHITE set_style(&rawfb->ctx, THEME_WHITE); #elif defined(STYLE_RED) diff --git a/demo/x11_xft/main.c b/demo/x11_xft/main.c index e069622..263f43b 100644 --- a/demo/x11_xft/main.c +++ b/demo/x11_xft/main.c @@ -157,6 +157,7 @@ main(void) xw.width, xw.height); #ifdef INCLUDE_STYLE + /* ease regression testing during Nuklear release process; not needed for anything else */ #ifdef STYLE_WHITE set_style(ctx, THEME_WHITE); #elif defined(STYLE_RED) From da5198ccdcae3b49cab99cfd0b1195de4369d505 Mon Sep 17 00:00:00 2001 From: loli Date: Mon, 24 Oct 2022 10:40:48 +0200 Subject: [PATCH 020/106] Fix nk_str_{append,insert}_str_utf8 always returning 0 --- nuklear.h | 9 ++++----- src/CHANGELOG | 1 + src/nuklear_string.c | 6 ++---- 3 files changed, 7 insertions(+), 9 deletions(-) diff --git a/nuklear.h b/nuklear.h index 5e645db..d115913 100644 --- a/nuklear.h +++ b/nuklear.h @@ -8439,7 +8439,6 @@ nk_str_append_text_utf8(struct nk_str *str, const char *text, int len) NK_API int nk_str_append_str_utf8(struct nk_str *str, const char *text) { - int runes = 0; int byte_len = 0; int num_runes = 0; int glyph_len = 0; @@ -8453,7 +8452,7 @@ nk_str_append_str_utf8(struct nk_str *str, const char *text) num_runes++; } nk_str_append_text_char(str, text, byte_len); - return runes; + return num_runes; } NK_API int nk_str_append_text_runes(struct nk_str *str, const nk_rune *text, int len) @@ -8568,7 +8567,6 @@ nk_str_insert_text_utf8(struct nk_str *str, int pos, const char *text, int len) NK_API int nk_str_insert_str_utf8(struct nk_str *str, int pos, const char *text) { - int runes = 0; int byte_len = 0; int num_runes = 0; int glyph_len = 0; @@ -8582,7 +8580,7 @@ nk_str_insert_str_utf8(struct nk_str *str, int pos, const char *text) num_runes++; } nk_str_insert_at_rune(str, pos, text, byte_len); - return runes; + return num_runes; } NK_API int nk_str_insert_text_runes(struct nk_str *str, int pos, const nk_rune *runes, int len) @@ -29656,7 +29654,8 @@ nk_tooltipfv(struct nk_context *ctx, const char *fmt, va_list args) /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// -/// - 2022/08/28 (4.10.3) - Renamed the `null` texture variable to `tex_null` +/// - 2022/10/24 (4.10.4) - Fix nk_str_{append,insert}_str_utf8 always returning 0 +/// - 2022/09/03 (4.10.3) - Renamed the `null` texture variable to `tex_null` /// - 2022/08/01 (4.10.2) - Fix Apple Silicon with incorrect NK_SITE_TYPE and NK_POINTER_TYPE /// - 2022/08/01 (4.10.1) - Fix cursor jumping back to beginning of text when typing more than /// nk_edit_xxx limit diff --git a/src/CHANGELOG b/src/CHANGELOG index da6fd2d..62db3f1 100644 --- a/src/CHANGELOG +++ b/src/CHANGELOG @@ -7,6 +7,7 @@ /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// +/// - 2022/10/24 (4.10.4) - Fix nk_str_{append,insert}_str_utf8 always returning 0 /// - 2022/09/03 (4.10.3) - Renamed the `null` texture variable to `tex_null` /// - 2022/08/01 (4.10.2) - Fix Apple Silicon with incorrect NK_SITE_TYPE and NK_POINTER_TYPE /// - 2022/08/01 (4.10.1) - Fix cursor jumping back to beginning of text when typing more than diff --git a/src/nuklear_string.c b/src/nuklear_string.c index 6ba249f..01a8de5 100644 --- a/src/nuklear_string.c +++ b/src/nuklear_string.c @@ -64,7 +64,6 @@ nk_str_append_text_utf8(struct nk_str *str, const char *text, int len) NK_API int nk_str_append_str_utf8(struct nk_str *str, const char *text) { - int runes = 0; int byte_len = 0; int num_runes = 0; int glyph_len = 0; @@ -78,7 +77,7 @@ nk_str_append_str_utf8(struct nk_str *str, const char *text) num_runes++; } nk_str_append_text_char(str, text, byte_len); - return runes; + return num_runes; } NK_API int nk_str_append_text_runes(struct nk_str *str, const nk_rune *text, int len) @@ -193,7 +192,6 @@ nk_str_insert_text_utf8(struct nk_str *str, int pos, const char *text, int len) NK_API int nk_str_insert_str_utf8(struct nk_str *str, int pos, const char *text) { - int runes = 0; int byte_len = 0; int num_runes = 0; int glyph_len = 0; @@ -207,7 +205,7 @@ nk_str_insert_str_utf8(struct nk_str *str, int pos, const char *text) num_runes++; } nk_str_insert_at_rune(str, pos, text, byte_len); - return runes; + return num_runes; } NK_API int nk_str_insert_text_runes(struct nk_str *str, int pos, const nk_rune *runes, int len) From 637b5e198dbc8ca407cb6e9e260e7a89d8e31638 Mon Sep 17 00:00:00 2001 From: Th3T3chn0G1t Date: Thu, 24 Nov 2022 10:21:37 +0000 Subject: [PATCH 021/106] Fixed UBSan trip in GLFW OpenGL3 demo backend This resolves a false UBSan trip caused by treating the element offset in `glDrawElements` as a pointer This parameter is effectively an offset but is taken as a `void*` By not storing the offset as a pointer, UBSan no longer tools the offset to check for null pointer overflow --- demo/glfw_opengl3/nuklear_glfw_gl3.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/demo/glfw_opengl3/nuklear_glfw_gl3.h b/demo/glfw_opengl3/nuklear_glfw_gl3.h index 663fa0b..cef59e5 100644 --- a/demo/glfw_opengl3/nuklear_glfw_gl3.h +++ b/demo/glfw_opengl3/nuklear_glfw_gl3.h @@ -240,7 +240,7 @@ nk_glfw3_render(struct nk_glfw* glfw, enum nk_anti_aliasing AA, int max_vertex_b /* convert from command queue into draw list and draw to screen */ const struct nk_draw_command *cmd; void *vertices, *elements; - const nk_draw_index *offset = NULL; + nk_size offset = 0; /* allocate vertex and element buffer */ glBindVertexArray(dev->vao); @@ -292,8 +292,8 @@ nk_glfw3_render(struct nk_glfw* glfw, enum nk_anti_aliasing AA, int max_vertex_b (GLint)((glfw->height - (GLint)(cmd->clip_rect.y + cmd->clip_rect.h)) * glfw->fb_scale.y), (GLint)(cmd->clip_rect.w * glfw->fb_scale.x), (GLint)(cmd->clip_rect.h * glfw->fb_scale.y)); - glDrawElements(GL_TRIANGLES, (GLsizei)cmd->elem_count, GL_UNSIGNED_SHORT, offset); - offset += cmd->elem_count; + glDrawElements(GL_TRIANGLES, (GLsizei)cmd->elem_count, GL_UNSIGNED_SHORT, (const void*) offset); + offset += cmd->elem_count * sizeof(nk_draw_index); } nk_clear(&glfw->ctx); nk_buffer_clear(&dev->cmds); From b98732fbc8247b0a1af734179724b7f2e04cef95 Mon Sep 17 00:00:00 2001 From: Mark Jansen Date: Wed, 30 Nov 2022 18:46:56 +0100 Subject: [PATCH 022/106] gdi_native: Fix calling convention problem The calling convention of a WNDPROC is specified as being 'CALLBACK'. --- demo/gdi_native_nuklear/window.h | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/demo/gdi_native_nuklear/window.h b/demo/gdi_native_nuklear/window.h index f78d574..0e8eba2 100644 --- a/demo/gdi_native_nuklear/window.h +++ b/demo/gdi_native_nuklear/window.h @@ -44,7 +44,7 @@ struct nkgdi_window HDC window_dc; /* Internally used state variables */ - int is_open; + int is_open; int is_draggin; int ws_override; int is_maximized; @@ -70,9 +70,9 @@ void nkgdi_window_destroy(struct nkgdi_window* wnd); /* Predeclare the windows window message procs */ /* This proc will setup the pointer to the window context */ -LRESULT nkgdi_window_proc_setup(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam); -/* This proc will take the window context pointer and performs operations on it*/ -LRESULT nkgdi_window_proc_run(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam); +LRESULT CALLBACK nkgdi_window_proc_setup(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam); +/* This proc will take the window context pointer and performs operations on it*/ +LRESULT CALLBACK nkgdi_window_proc_run(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam); void nkgdi_window_init(void) { @@ -126,7 +126,7 @@ void nkgdi_window_create(struct nkgdi_window* wnd, unsigned int width, unsigned GetModuleHandleW(NULL), wnd ); - + /* Give the window the ascii char name */ SetWindowTextA(wnd->_internal.window_handle, name); @@ -232,7 +232,7 @@ int nkgdi_window_update(struct nkgdi_window* wnd) return wnd->_internal.is_open; } -LRESULT nkgdi_window_proc_setup(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) +LRESULT CALLBACK nkgdi_window_proc_setup(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) { /* Waiting to receive the NCCREATE message with the custom window data */ if (msg == WM_NCCREATE) @@ -253,11 +253,11 @@ LRESULT nkgdi_window_proc_setup(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam return DefWindowProc(wnd, msg, wParam, lParam); } -LRESULT nkgdi_window_proc_run(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) +LRESULT CALLBACK nkgdi_window_proc_run(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) { /* The window context is extracted from the window data */ struct nkgdi_window* nkwnd = (struct nkgdi_window*)GetWindowLongPtrW(wnd, GWLP_USERDATA); - + /* Switch on the message code to handle all required messages */ switch (msg) { @@ -267,7 +267,7 @@ LRESULT nkgdi_window_proc_run(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) if(!nkwnd->cb_on_close || nkwnd->cb_on_close()) nkwnd->_internal.is_open = 0; return 0; /* No default behaviour. We do it our own way */ - + /* Window sizing event (is currently beeing sized) */ case WM_SIZING: { From 0b7547b710d7574901ef4a957f830cc2a6a81172 Mon Sep 17 00:00:00 2001 From: Mark Jansen Date: Fri, 2 Dec 2022 00:18:30 +0100 Subject: [PATCH 023/106] demo/win32: Add the renderer name to the window title --- demo/d3d11/main.c | 2 +- demo/d3d12/main.c | 2 +- demo/d3d9/main.c | 2 +- demo/gdi/main.c | 2 +- demo/gdip/main.c | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/demo/d3d11/main.c b/demo/d3d11/main.c index ff2ac95..338dde2 100644 --- a/demo/d3d11/main.c +++ b/demo/d3d11/main.c @@ -161,7 +161,7 @@ int main(void) AdjustWindowRectEx(&rect, style, FALSE, exstyle); - wnd = CreateWindowExW(exstyle, wc.lpszClassName, L"Nuklear Demo", + wnd = CreateWindowExW(exstyle, wc.lpszClassName, L"Nuklear Direct3D 11 Demo", style | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, wc.hInstance, NULL); diff --git a/demo/d3d12/main.c b/demo/d3d12/main.c index f6891e5..57e7bc3 100644 --- a/demo/d3d12/main.c +++ b/demo/d3d12/main.c @@ -219,7 +219,7 @@ int main(void) AdjustWindowRectEx(&rect, style, FALSE, exstyle); - wnd = CreateWindowExW(exstyle, wc.lpszClassName, L"Nuklear Demo", + wnd = CreateWindowExW(exstyle, wc.lpszClassName, L"Nuklear Direct3D 12 Demo", style | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, wc.hInstance, NULL); diff --git a/demo/d3d9/main.c b/demo/d3d9/main.c index c6b8a5d..638c584 100644 --- a/demo/d3d9/main.c +++ b/demo/d3d9/main.c @@ -191,7 +191,7 @@ int main(void) AdjustWindowRectEx(&rect, style, FALSE, exstyle); - wnd = CreateWindowExW(exstyle, wc.lpszClassName, L"Nuklear Demo", + wnd = CreateWindowExW(exstyle, wc.lpszClassName, L"Nuklear Direct3D 9 Demo", style | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, wc.hInstance, NULL); diff --git a/demo/gdi/main.c b/demo/gdi/main.c index f588c07..281f82b 100644 --- a/demo/gdi/main.c +++ b/demo/gdi/main.c @@ -103,7 +103,7 @@ int main(void) atom = RegisterClassW(&wc); AdjustWindowRectEx(&rect, style, FALSE, exstyle); - wnd = CreateWindowExW(exstyle, wc.lpszClassName, L"Nuklear Demo", + wnd = CreateWindowExW(exstyle, wc.lpszClassName, L"Nuklear GDI Demo", style | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, wc.hInstance, NULL); diff --git a/demo/gdip/main.c b/demo/gdip/main.c index 8f132f5..7151964 100644 --- a/demo/gdip/main.c +++ b/demo/gdip/main.c @@ -99,7 +99,7 @@ int main(void) AdjustWindowRectEx(&rect, style, FALSE, exstyle); - wnd = CreateWindowExW(exstyle, wc.lpszClassName, L"Nuklear Demo", + wnd = CreateWindowExW(exstyle, wc.lpszClassName, L"Nuklear GDI+ Demo", style | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, wc.hInstance, NULL); From da9d3866e24c40d4246b4b0b8f0c48523c236652 Mon Sep 17 00:00:00 2001 From: Mark Jansen Date: Fri, 2 Dec 2022 00:19:04 +0100 Subject: [PATCH 024/106] utils: Add .yml indent_size to .editorconfig --- .editorconfig | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.editorconfig b/.editorconfig index 4ce28c3..25319b3 100644 --- a/.editorconfig +++ b/.editorconfig @@ -12,3 +12,6 @@ trim_trailing_whitespace = true [clib.json] indent_size = 2 + +[*.yml] +indent_size = 2 From 607e4716cc851d8aaa7fb51db4b5d5bd2b41b201 Mon Sep 17 00:00:00 2001 From: Mark Jansen Date: Sat, 3 Dec 2022 21:57:14 +0100 Subject: [PATCH 025/106] Add link from the documentation to the code Fixes #515 --- src/HEADER | 1 + 1 file changed, 1 insertion(+) diff --git a/src/HEADER b/src/HEADER index 3a5bffe..477d244 100644 --- a/src/HEADER +++ b/src/HEADER @@ -47,6 +47,7 @@ /// - No global or hidden state /// - Customizable library modules (you can compile and use only what you need) /// - Optional font baker and vertex buffer output +/// - [Code available on github](https://github.com/Immediate-Mode-UI/Nuklear/) /// /// ## Features /// - Absolutely no platform dependent code From 1dad328fe9839d57f8282129b3cb9c6a9b75f9c2 Mon Sep 17 00:00:00 2001 From: Jai <814683@qq.com> Date: Fri, 16 Dec 2022 12:20:03 +0800 Subject: [PATCH 026/106] Fix the problem that nk_font_bake_pack uses ttc font offset incorrectly (#456) --- nuklear.h | 2 +- src/nuklear_font.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nuklear.h b/nuklear.h index d115913..c76926a 100644 --- a/nuklear.h +++ b/nuklear.h @@ -16619,7 +16619,7 @@ nk_font_bake_pack(struct nk_font_baker *baker, struct stbtt_fontinfo *font_info = &baker->build[i++].info; font_info->userdata = alloc; - if (!stbtt_InitFont(font_info, (const unsigned char*)it->ttf_blob, 0)) + if (!stbtt_InitFont(font_info, (const unsigned char*)it->ttf_blob, stbtt_GetFontOffsetForIndex((const unsigned char*)it->ttf_blob, 0))) return nk_false; } while ((it = it->n) != config_iter); } diff --git a/src/nuklear_font.c b/src/nuklear_font.c index 49df38e..431ed80 100644 --- a/src/nuklear_font.c +++ b/src/nuklear_font.c @@ -194,7 +194,7 @@ nk_font_bake_pack(struct nk_font_baker *baker, struct stbtt_fontinfo *font_info = &baker->build[i++].info; font_info->userdata = alloc; - if (!stbtt_InitFont(font_info, (const unsigned char*)it->ttf_blob, 0)) + if (!stbtt_InitFont(font_info, (const unsigned char*)it->ttf_blob, stbtt_GetFontOffsetForIndex((const unsigned char*)it->ttf_blob, 0))) return nk_false; } while ((it = it->n) != config_iter); } From f78acb43335aa451c60ee24dc7a8b6ce24a00fa1 Mon Sep 17 00:00:00 2001 From: Rob Loach Date: Sat, 17 Dec 2022 14:00:26 -0500 Subject: [PATCH 027/106] Remove .gitmodules as it's not used anymore --- .gitmodules | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .gitmodules diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index e69de29..0000000 From 743dd0105feda03ed39415c4877d087bd1651de8 Mon Sep 17 00:00:00 2001 From: Rob Loach Date: Sat, 17 Dec 2022 14:01:12 -0500 Subject: [PATCH 028/106] Update version for 4.10.5 --- clib.json | 2 +- nuklear.h | 1 + src/CHANGELOG | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/clib.json b/clib.json index 3fe7d63..6ae79d6 100644 --- a/clib.json +++ b/clib.json @@ -1,6 +1,6 @@ { "name": "nuklear", - "version": "4.10.1", + "version": "4.10.5", "repo": "Immediate-Mode-UI/Nuklear", "description": "A small ANSI C gui toolkit", "keywords": ["gl", "ui", "toolkit"], diff --git a/nuklear.h b/nuklear.h index c76926a..febee39 100644 --- a/nuklear.h +++ b/nuklear.h @@ -29654,6 +29654,7 @@ nk_tooltipfv(struct nk_context *ctx, const char *fmt, va_list args) /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// +/// - 2022/12/17 (4.10.5) - Fix nk_font_bake_pack() using TTC font offset incorrectly /// - 2022/10/24 (4.10.4) - Fix nk_str_{append,insert}_str_utf8 always returning 0 /// - 2022/09/03 (4.10.3) - Renamed the `null` texture variable to `tex_null` /// - 2022/08/01 (4.10.2) - Fix Apple Silicon with incorrect NK_SITE_TYPE and NK_POINTER_TYPE diff --git a/src/CHANGELOG b/src/CHANGELOG index 62db3f1..be54e55 100644 --- a/src/CHANGELOG +++ b/src/CHANGELOG @@ -7,6 +7,7 @@ /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// +/// - 2022/12/17 (4.10.5) - Fix nk_font_bake_pack() using TTC font offset incorrectly /// - 2022/10/24 (4.10.4) - Fix nk_str_{append,insert}_str_utf8 always returning 0 /// - 2022/09/03 (4.10.3) - Renamed the `null` texture variable to `tex_null` /// - 2022/08/01 (4.10.2) - Fix Apple Silicon with incorrect NK_SITE_TYPE and NK_POINTER_TYPE From 8d9f46a6a5d0f8278ae220187fac7671e08e5660 Mon Sep 17 00:00:00 2001 From: Rob Loach Date: Sat, 17 Dec 2022 14:10:43 -0500 Subject: [PATCH 029/106] utils: Apply indent_size 2 to all JSON and YAML files --- .editorconfig | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/.editorconfig b/.editorconfig index 25319b3..5012ad1 100644 --- a/.editorconfig +++ b/.editorconfig @@ -10,8 +10,5 @@ indent_size = 4 insert_final_newline = true trim_trailing_whitespace = true -[clib.json] -indent_size = 2 - -[*.yml] +[**.{json,yml}] indent_size = 2 From 23cb43f5ebc820bf62ded25b5843c8395fee4f83 Mon Sep 17 00:00:00 2001 From: Jai <814683@qq.com> Date: Fri, 23 Dec 2022 01:58:40 +0800 Subject: [PATCH 030/106] Fix incorrect glyph index in nk_font_bake --- clib.json | 2 +- nuklear.h | 2 +- src/CHANGELOG | 1 + src/nuklear_font.c | 1 - 4 files changed, 3 insertions(+), 3 deletions(-) diff --git a/clib.json b/clib.json index 6ae79d6..cf690c7 100644 --- a/clib.json +++ b/clib.json @@ -1,6 +1,6 @@ { "name": "nuklear", - "version": "4.10.5", + "version": "4.10.6", "repo": "Immediate-Mode-UI/Nuklear", "description": "A small ANSI C gui toolkit", "keywords": ["gl", "ui", "toolkit"], diff --git a/nuklear.h b/nuklear.h index febee39..115317b 100644 --- a/nuklear.h +++ b/nuklear.h @@ -16779,7 +16779,6 @@ nk_font_bake(struct nk_font_baker *baker, void *image_memory, int width, int hei /* query glyph bounds from stb_truetype */ const stbtt_packedchar *pc = &range->chardata_for_range[char_idx]; - if (!pc->x0 && !pc->x1 && !pc->y0 && !pc->y1) continue; codepoint = (nk_rune)(range->first_unicode_codepoint_in_range + char_idx); stbtt_GetPackedQuad(range->chardata_for_range, (int)width, (int)height, char_idx, &dummy_x, &dummy_y, &q, 0); @@ -29654,6 +29653,7 @@ nk_tooltipfv(struct nk_context *ctx, const char *fmt, va_list args) /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// +/// - 2022/12/23 (4.10.6) - Fix incorrect glyph index in nk_font_bake() /// - 2022/12/17 (4.10.5) - Fix nk_font_bake_pack() using TTC font offset incorrectly /// - 2022/10/24 (4.10.4) - Fix nk_str_{append,insert}_str_utf8 always returning 0 /// - 2022/09/03 (4.10.3) - Renamed the `null` texture variable to `tex_null` diff --git a/src/CHANGELOG b/src/CHANGELOG index be54e55..4bcdfdb 100644 --- a/src/CHANGELOG +++ b/src/CHANGELOG @@ -7,6 +7,7 @@ /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// +/// - 2022/12/23 (4.10.6) - Fix incorrect glyph index in nk_font_bake() /// - 2022/12/17 (4.10.5) - Fix nk_font_bake_pack() using TTC font offset incorrectly /// - 2022/10/24 (4.10.4) - Fix nk_str_{append,insert}_str_utf8 always returning 0 /// - 2022/09/03 (4.10.3) - Renamed the `null` texture variable to `tex_null` diff --git a/src/nuklear_font.c b/src/nuklear_font.c index 431ed80..836584f 100644 --- a/src/nuklear_font.c +++ b/src/nuklear_font.c @@ -354,7 +354,6 @@ nk_font_bake(struct nk_font_baker *baker, void *image_memory, int width, int hei /* query glyph bounds from stb_truetype */ const stbtt_packedchar *pc = &range->chardata_for_range[char_idx]; - if (!pc->x0 && !pc->x1 && !pc->y0 && !pc->y1) continue; codepoint = (nk_rune)(range->first_unicode_codepoint_in_range + char_idx); stbtt_GetPackedQuad(range->chardata_for_range, (int)width, (int)height, char_idx, &dummy_x, &dummy_y, &q, 0); From 7c84c3cc1830baaf4f12ebf9d9494bb887f4faa3 Mon Sep 17 00:00:00 2001 From: LonerDan Date: Fri, 13 Jan 2023 12:33:12 +0100 Subject: [PATCH 031/106] Remove link to no longer existing tool The link to the online single header packer (https://apoorvaj.io/single-header-packer.html) no longer works (returns 404), so remove it. --- src/Readme.md | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Readme.md b/src/Readme.md index eb4de92..e4d9ad3 100644 --- a/src/Readme.md +++ b/src/Readme.md @@ -1,5 +1,4 @@ File Packer: ------------ -- [Click to generate nuklear.h](http://apoorvaj.io/single-header-packer.html?macro=NK&pre=https://raw.githubusercontent.com/vurtun/nuklear/master/src/HEADER&pub=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear.h&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_internal.h&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_math.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_util.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_color.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_utf8.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_buffer.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_string.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_draw.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_vertex.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_font.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_input.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_style.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_context.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_pool.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_page_element.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_table.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_panel.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_window.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_popup.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_contextual.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_menu.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_layout.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_tree.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_group.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_list_view.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_widget.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_text.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_image.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_button.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_toggle.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_selectable.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_slider.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_progress.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_scrollbar.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_text_editor.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_edit.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_property.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_chart.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_color_picker.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_combo.c&priv=https://raw.githubusercontent.com/vurtun/nuklear/master/src/nuklear_tooltip.c&post=https://raw.githubusercontent.com/vurtun/nuklear/master/src/LICENSE&post=https://raw.githubusercontent.com/vurtun/nuklear/master/src/CHANGELOG&post=https://raw.githubusercontent.com/vurtun/nuklear/master/src/CREDITS) - On Linux/Mac just run ./paq.sh > ../nuklear.h - On Windows just run paq.bat From cb6132f1714ca54bca26e647028cbaf65391c59e Mon Sep 17 00:00:00 2001 From: Rongcui Dong Date: Tue, 17 Jan 2023 15:19:05 -0500 Subject: [PATCH 032/106] Update docs --- doc/doc | Bin 0 -> 33632 bytes doc/index.html | 416 ++++++++++++++++++++++++++++--- index.html | 0 nuklear.h | 603 +++++++++++++++++++++++---------------------- src/nuklear.h | 549 +++++++++++++++++++++-------------------- src/nuklear_math.c | 53 ++-- 6 files changed, 999 insertions(+), 622 deletions(-) create mode 100755 doc/doc create mode 100644 index.html diff --git a/doc/doc b/doc/doc new file mode 100755 index 0000000000000000000000000000000000000000..906b2cc19faa9e40ab935b2e401968269fa40f9e GIT binary patch literal 33632 zcmeI5eQZ-z6u{4GhrocXz#IcLJdCV}v=#Xjw$ZUIFcCJ#j8%+}(!Q?G^=o~vj(zBg z2IB`1j3kiw1tvsCkO&$i0kyv`%h>1~{CJ_8%i3uofGU_?+y>49*3DG~#Nlx!M z=bn4sxxd%`d2hcN=({!^KmZgA>O@pA4`4HhXaP(`U5P45^_44Xo~UW4qv%M{7mo~G z=TV)PFj0~kYdno3r}g#jkufm+Q5Yu0mUNLMP2Q-P4i35XQf0vfhzpMt}5X)YW2ID8w`Q&JHr(cy07qSN zMk@wMscjpoBsE2|Uc(LRWw?RcSdU9}xeY%v@00?=-?N8n*Q~0kuFZT$k~w{$PqLnx zL7{$3l)673AW8kvTc&-^GyPrYQ!m7(1obrfV{qKK37{Uwai}zA3+0khuQ!rw}t%ZliYzyeFR@9u@y~U`1+B1Vx?NT;q3=7CZY(H;Qo_%jlQd%=FzwyByNb}n~fU&;nO z2}*IG`X`eHpLNfC(@GCcp%k025#WOn?b60Vco%m;e)C0!)AjFaajO1egF5U;<2l2`~XB zzyz286JP>NfC(^xAp!$UN4x)&gzi5cvvgmsvvv=5?YQv%H2ZG(D>KSjBdjNEl(L$YD8qZ;d0Vg2R!oXYNjrW5a{tkRjO zI5!2g7?sxEUJRa+ykx^@fFg>~+=HWGB0UF>52hO_e;>|weFiP5e0O^CTG{T#~MW~`@YQXcJ%@~&Xs zDa<=(ffkBUt@RcU_Ept>Wy;QJlye;C@vP{FwtRO#Sf-!R?Sd?OQkGq8*kxf^^NPNp zH?GQBxjmr;9E!gRn6s%DgLO>=~LBZ zR8{rGm6%qM$*PNKN;IODcW6=HT6)Y9dsy}>iLm|IrDZNN8Omlj9O7!~4+}359gYgK zj;O|cx71DMxz4Z>aXw8g4L`*=AABbml0DK{Upfnn=b&}Or!&Ok@eHs{KT!<$ zvjFo5wk;{(9G>h=8fS%VN#l66Eomg!l5_?iC8>Y%2NPfdOn?b60Vco%m;e)C0!)Aj zFaajO1egF5U;<2l2`~XBzyz286JP>NfC(@GCcp%k025#WOn?b60Vco%m;e)C0!)Aj zFaajO1egF5U;<2l2`~XBzyz286JP>NfC(@GCh)%#5V2xCY7mwF>)f~t01XuLf&ks7 z{}RuLZo4ttorxIh1iU~%C`O%wikDaj)u>clk|b60E0LIKMH3pD0XZ4~sY%v+AjJ~q zr%ELS3C8M|5m=;fP?9&wzJw-ALD}n<<1i}hRU$Cc3aK{p@fm}b6bg9L1Pbi~TS4Er z6M=lXD*;C`b)o+|&-Ul$_=|G<@*KY^$0uHNR|0XwyFm2+UZ=Yha^oUmxPD)fzOP$F zh2@82;OzJm?r1v(GJ7n-7`>HFuwWM!y`?8{-eWEr3$W?5Xwm cD(caGJlWe?d+q9$FFv`jZTDB7Tb9=T4GB_2tpET3 literal 0 HcmV?d00001 diff --git a/doc/index.html b/doc/index.html index 0312be3..919cd95 100644 --- a/doc/index.html +++ b/doc/index.html @@ -1,6 +1,5 @@ -Nuklear # Nuklear ![](https://cloud.githubusercontent.com/assets/8057201/11761525/ae06f0ca-a0c6-11e5-819d-5610b25f6ef4.gif) ## Contents @@ -47,6 +46,7 @@ render backends it only focuses on the actual UI. - No global or hidden state - Customizable library modules (you can compile and use only what you need) - Optional font baker and vertex buffer output +- [Code available on github](https://github.com/Immediate-Mode-UI/Nuklear/) ## Features - Absolutely no platform dependent code - Memory management control ranging from/to @@ -90,7 +90,8 @@ NK_PRIVATE | If defined declares all functions as static, s NK_INCLUDE_FIXED_TYPES | If defined it will include header `` for fixed sized types otherwise nuklear tries to select the correct type. If that fails it will throw a compiler error and you have to select the correct types yourself. NK_INCLUDE_DEFAULT_ALLOCATOR | If defined it will include header `` and provide additional functions to use this library without caring for memory allocation control and therefore ease memory management. NK_INCLUDE_STANDARD_IO | If defined it will include header `` and provide additional functions depending on file loading. -NK_INCLUDE_STANDARD_VARARGS | If defined it will include header and provide additional functions depending on file loading. +NK_INCLUDE_STANDARD_VARARGS | If defined it will include header and provide additional functions depending on file loading. +NK_INCLUDE_STANDARD_BOOL | If defined it will include header `` for nk_bool otherwise nuklear defines nk_bool as int. NK_INCLUDE_VERTEX_BUFFER_OUTPUT | Defining this adds a vertex draw command list backend to this library, which allows you to convert queue commands into vertex draw commands. This is mainly if you need a hardware accessible format for OpenGL, DirectX, Vulkan, Metal,... NK_INCLUDE_FONT_BAKING | Defining this adds `stb_truetype` and `stb_rect_pack` implementation to this library and provides font baking and rendering. If you already have font handling or do not want to use this font handler you don't have to define it. NK_INCLUDE_DEFAULT_FONT | Defining this adds the default font: ProggyClean.ttf into this library which can be loaded into a font atlas and allows using this library without having a truetype font @@ -109,6 +110,7 @@ NK_KEYSTATE_BASED_INPUT | Define this if your backend uses key state for - NK_INCLUDE_FIXED_TYPES - NK_INCLUDE_DEFAULT_ALLOCATOR - NK_INCLUDE_STANDARD_VARARGS + - NK_INCLUDE_STANDARD_BOOL - NK_INCLUDE_VERTEX_BUFFER_OUTPUT - NK_INCLUDE_FONT_BAKING - NK_INCLUDE_DEFAULT_FONT @@ -132,7 +134,7 @@ Function | Description NK_ASSERT | If you don't define this, nuklear will use with assert(). NK_MEMSET | You can define this to 'memset' or your own memset implementation replacement. If not nuklear will use its own version. NK_MEMCPY | You can define this to 'memcpy' or your own memcpy implementation replacement. If not nuklear will use its own version. -NK_SQRT | You can define this to 'sqrt' or your own sqrt implementation replacement. If not nuklear will use its own slow and not highly accurate version. +NK_INV_SQRT | You can define this to your own inverse sqrt implementation replacement. If not nuklear will use its own slow and not highly accurate version. NK_SIN | You can define this to 'sinf' or your own sine implementation replacement. If not nuklear will use its own approximation implementation. NK_COS | You can define this to 'cosf' or your own cosine implementation replacement. If not nuklear will use its own approximation implementation. NK_STRTOD | You can define this to `strtod` or your own string to double conversion implementation replacement. If not defined nuklear will use its own imprecise and possibly unsafe version (does not handle nan or infinity!). @@ -221,7 +223,7 @@ __nk_set_user_data__| Utility function to pass user data to draw command Initializes a `nk_context` struct with a default standard library allocator. Should be used if you don't want to be bothered with memory management in nuklear. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -int nk_init_default(struct nk_context *ctx, const struct nk_user_font *font); +nk_bool nk_init_default(struct nk_context *ctx, const struct nk_user_font *font); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter | Description ------------|--------------------------------------------------------------- @@ -235,7 +237,7 @@ Especially recommended for system with little memory or systems with virtual mem For the later case you can just allocate for example 16MB of virtual memory and only the required amount of memory will actually be committed. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -int nk_init_fixed(struct nk_context *ctx, void *memory, nk_size size, const struct nk_user_font *font); +nk_bool nk_init_fixed(struct nk_context *ctx, void *memory, nk_size size, const struct nk_user_font *font); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! Warning make sure the passed memory block is aligned correctly for `nk_draw_commands`. @@ -251,7 +253,7 @@ Initializes a `nk_context` struct with memory allocation callbacks for nuklear t memory from. Used internally for `nk_init_default` and provides a kitchen sink allocation interface to nuklear. Can be useful for cases like monitoring memory consumption. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -int nk_init(struct nk_context *ctx, struct nk_allocator *alloc, const struct nk_user_font *font); +nk_bool nk_init(struct nk_context *ctx, struct nk_allocator *alloc, const struct nk_user_font *font); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter | Description ------------|--------------------------------------------------------------- @@ -264,7 +266,7 @@ Initializes a `nk_context` struct from two different either fixed or growing buffers. The first buffer is for allocating draw commands while the second buffer is used for allocating windows, panels and state tables. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -int nk_init_custom(struct nk_context *ctx, struct nk_buffer *cmds, struct nk_buffer *pool, const struct nk_user_font *font); +nk_bool nk_init_custom(struct nk_context *ctx, struct nk_buffer *cmds, struct nk_buffer *pool, const struct nk_user_font *font); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter | Description ------------|--------------------------------------------------------------- @@ -379,7 +381,7 @@ __y__ | Must hold an integer describing the current mouse cursor y-positio #### nk_input_key Mirrors the state of a specific key to nuklear ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -void nk_input_key(struct nk_context*, enum nk_keys key, int down); +void nk_input_key(struct nk_context*, enum nk_keys key, nk_bool down); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter | Description ------------|----------------------------------------------------------- @@ -389,7 +391,7 @@ __down__ | Must be 0 for key is up and 1 for key is down #### nk_input_button Mirrors the state of a specific mouse button to nuklear ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -void nk_input_button(struct nk_context *ctx, enum nk_buttons btn, int x, int y, int down); +void nk_input_button(struct nk_context *ctx, enum nk_buttons btn, int x, int y, nk_bool down); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter | Description ------------|----------------------------------------------------------- @@ -891,7 +893,7 @@ __NK_MAXIMIZED__| UI section is extended and visible until minimized Starts a new window; needs to be called every frame for every window (unless hidden) or otherwise the window gets removed ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -int nk_begin(struct nk_context *ctx, const char *title, struct nk_rect bounds, nk_flags flags); +nk_bool nk_begin(struct nk_context *ctx, const char *title, struct nk_rect bounds, nk_flags flags); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter | Description ------------|----------------------------------------------------------- @@ -905,7 +907,7 @@ until `nk_end` or `false(0)` otherwise for example if minimized Extended window start with separated title and identifier to allow multiple windows with same title but not name ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -int nk_begin_titled(struct nk_context *ctx, const char *name, const char *title, struct nk_rect bounds, nk_flags flags); +nk_bool nk_begin_titled(struct nk_context *ctx, const char *name, const char *title, struct nk_rect bounds, nk_flags flags); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter | Description ------------|----------------------------------------------------------- @@ -1086,7 +1088,7 @@ Returns if the currently processed window is currently active !!! WARNING Only call this function between calls `nk_begin_xxx` and `nk_end` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -int nk_window_has_focus(const struct nk_context *ctx); +nk_bool nk_window_has_focus(const struct nk_context *ctx); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter | Description ------------|----------------------------------------------------------- @@ -1097,7 +1099,7 @@ Return if the current window is being hovered !!! WARNING Only call this function between calls `nk_begin_xxx` and `nk_end` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -int nk_window_is_hovered(struct nk_context *ctx); +nk_bool nk_window_is_hovered(struct nk_context *ctx); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter | Description ------------|----------------------------------------------------------- @@ -1106,7 +1108,7 @@ Returns `true(1)` if current window is hovered or `false(0)` otherwise #### nk_window_is_collapsed Returns if the window with given name is currently minimized/collapsed ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -int nk_window_is_collapsed(struct nk_context *ctx, const char *name); +nk_bool nk_window_is_collapsed(struct nk_context *ctx, const char *name); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter | Description ------------|----------------------------------------------------------- @@ -1117,7 +1119,7 @@ found or is not minimized #### nk_window_is_closed Returns if the window with given name was closed by calling `nk_close` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -int nk_window_is_closed(struct nk_context *ctx, const char *name); +nk_bool nk_window_is_closed(struct nk_context *ctx, const char *name); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter | Description ------------|----------------------------------------------------------- @@ -1127,7 +1129,7 @@ Returns `true(1)` if current window was closed or `false(0)` window not found or #### nk_window_is_hidden Returns if the window with given name is hidden ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -int nk_window_is_hidden(struct nk_context *ctx, const char *name); +nk_bool nk_window_is_hidden(struct nk_context *ctx, const char *name); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter | Description ------------|----------------------------------------------------------- @@ -1137,7 +1139,7 @@ Returns `true(1)` if current window is hidden or `false(0)` window not found or #### nk_window_is_active Same as nk_window_has_focus for some reason ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -int nk_window_is_active(struct nk_context *ctx, const char *name); +nk_bool nk_window_is_active(struct nk_context *ctx, const char *name); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter | Description ------------|----------------------------------------------------------- @@ -1147,7 +1149,7 @@ Returns `true(1)` if current window is active or `false(0)` window not found or #### nk_window_is_any_hovered Returns if the any window is being hovered ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -int nk_window_is_any_hovered(struct nk_context*); +nk_bool nk_window_is_any_hovered(struct nk_context*); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter | Description ------------|----------------------------------------------------------- @@ -1158,7 +1160,7 @@ Returns if the any window is being hovered or any widget is currently active. Can be used to decide if input should be processed by UI or your specific input handling. Example could be UI and 3D camera to move inside a 3D space. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -int nk_item_is_any_active(struct nk_context*); +nk_bool nk_item_is_any_active(struct nk_context*); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter | Description ------------|----------------------------------------------------------- @@ -1731,6 +1733,14 @@ Parameter | Description __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_layout_space_begin` __bounds__ | Rectangle to convert from layout space into screen space Returns transformed `nk_rect` in layout space coordinates +#### nk_spacer +Spacer is a dummy widget that consumes space as usual but doesn't draw anything +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c +void nk_spacer(struct nk_context* ); +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Parameter | Description +------------|----------------------------------------------------------- +__ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_layout_space_begin` ### Groups Groups are basically windows inside windows. They allow to subdivide space in a window to layout widgets as a group. Almost all more complex widget @@ -1812,7 +1822,7 @@ nk_group_set_scroll | Sets the scroll offset for the given group #### nk_group_begin Starts a new widget group. Requires a previous layouting function to specify a pos/size. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -int nk_group_begin(struct nk_context*, const char *title, nk_flags); +nk_bool nk_group_begin(struct nk_context*, const char *title, nk_flags); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter | Description ------------|----------------------------------------------------------- @@ -1823,7 +1833,7 @@ Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise #### nk_group_begin_titled Starts a new widget group. Requires a previous layouting function to specify a pos/size. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -int nk_group_begin_titled(struct nk_context*, const char *name, const char *title, nk_flags); +nk_bool nk_group_begin_titled(struct nk_context*, const char *name, const char *title, nk_flags); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter | Description ------------|----------------------------------------------------------- @@ -1844,7 +1854,7 @@ __ctx__ | Must point to an previously initialized `nk_context` struct starts a new widget group. requires a previous layouting function to specify a size. Does not keep track of scrollbar. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -int nk_group_scrolled_offset_begin(struct nk_context*, nk_uint *x_offset, nk_uint *y_offset, const char *title, nk_flags flags); +nk_bool nk_group_scrolled_offset_begin(struct nk_context*, nk_uint *x_offset, nk_uint *y_offset, const char *title, nk_flags flags); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter | Description ------------|----------------------------------------------------------- @@ -1858,7 +1868,7 @@ Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise Starts a new widget group. requires a previous layouting function to specify a size. Does not keep track of scrollbar. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -int nk_group_scrolled_begin(struct nk_context*, struct nk_scroll *off, const char *title, nk_flags); +nk_bool nk_group_scrolled_begin(struct nk_context*, struct nk_scroll *off, const char *title, nk_flags); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter | Description ------------|----------------------------------------------------------- @@ -1986,7 +1996,7 @@ Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise Start a collapsible UI section with internal state management with full control over internal unique ID used to store state ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -int nk_tree_push_hashed(struct nk_context*, enum nk_tree_type, const char *title, enum nk_collapse_states initial_state, const char *hash, int len,int seed); +nk_bool nk_tree_push_hashed(struct nk_context*, enum nk_tree_type, const char *title, enum nk_collapse_states initial_state, const char *hash, int len,int seed); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter | Description ------------|----------------------------------------------------------- @@ -2035,7 +2045,7 @@ Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise Start a collapsible UI section with internal state management with full control over internal unique ID used to store state ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -int nk_tree_image_push_hashed(struct nk_context*, enum nk_tree_type, struct nk_image, const char *title, enum nk_collapse_states initial_state, const char *hash, int len,int seed); +nk_bool nk_tree_image_push_hashed(struct nk_context*, enum nk_tree_type, struct nk_image, const char *title, enum nk_collapse_states initial_state, const char *hash, int len,int seed); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter | Description ------------|----------------------------------------------------------- @@ -2059,7 +2069,7 @@ __ctx__ | Must point to an previously initialized `nk_context` struct after #### nk_tree_state_push Start a collapsible UI section with external state management ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -int nk_tree_state_push(struct nk_context*, enum nk_tree_type, const char *title, enum nk_collapse_states *state); +nk_bool nk_tree_state_push(struct nk_context*, enum nk_tree_type, const char *title, enum nk_collapse_states *state); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter | Description ------------|----------------------------------------------------------- @@ -2071,7 +2081,7 @@ Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise #### nk_tree_state_image_push Start a collapsible UI section with image and label header and external state management ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -int nk_tree_state_image_push(struct nk_context*, enum nk_tree_type, struct nk_image, const char *title, enum nk_collapse_states *state); +nk_bool nk_tree_state_image_push(struct nk_context*, enum nk_tree_type, struct nk_image, const char *title, enum nk_collapse_states *state); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter | Description ------------|----------------------------------------------------------- @@ -2260,6 +2270,302 @@ __max__ | Maximum value not allowed to be overflown __step__ | Increment added and subtracted on increment and decrement button __inc_per_pixel__ | Value per pixel added or subtracted on dragging Returns the new modified double value +### Font +Font handling in this library was designed to be quite customizable and lets +you decide what you want to use and what you want to provide. There are three +different ways to use the font atlas. The first two will use your font +handling scheme and only requires essential data to run nuklear. The next +slightly more advanced features is font handling with vertex buffer output. +Finally the most complex API wise is using nuklear's font baking API. +#### Using your own implementation without vertex buffer output + +So first up the easiest way to do font handling is by just providing a +`nk_user_font` struct which only requires the height in pixel of the used +font and a callback to calculate the width of a string. This way of handling +fonts is best fitted for using the normal draw shape command API where you +do all the text drawing yourself and the library does not require any kind +of deeper knowledge about which font handling mechanism you use. +IMPORTANT: the `nk_user_font` pointer provided to nuklear has to persist +over the complete life time! I know this sucks but it is currently the only +way to switch between fonts. +```c + float your_text_width_calculation(nk_handle handle, float height, const char *text, int len) + { + your_font_type *type = handle.ptr; + float text_width = ...; + return text_width; + } + struct nk_user_font font; + font.userdata.ptr = &your_font_class_or_struct; + font.height = your_font_height; + font.width = your_text_width_calculation; + + struct nk_context ctx; + nk_init_default(&ctx, &font); +``` +#### Using your own implementation with vertex buffer output + +While the first approach works fine if you don't want to use the optional +vertex buffer output it is not enough if you do. To get font handling working +for these cases you have to provide two additional parameters inside the +`nk_user_font`. First a texture atlas handle used to draw text as subimages +of a bigger font atlas texture and a callback to query a character's glyph +information (offset, size, ...). So it is still possible to provide your own +font and use the vertex buffer output. +```c + float your_text_width_calculation(nk_handle handle, float height, const char *text, int len) + { + your_font_type *type = handle.ptr; + float text_width = ...; + return text_width; + } + void query_your_font_glyph(nk_handle handle, float font_height, struct nk_user_font_glyph *glyph, nk_rune codepoint, nk_rune next_codepoint) + { + your_font_type *type = handle.ptr; + glyph.width = ...; + glyph.height = ...; + glyph.xadvance = ...; + glyph.uv[0].x = ...; + glyph.uv[0].y = ...; + glyph.uv[1].x = ...; + glyph.uv[1].y = ...; + glyph.offset.x = ...; + glyph.offset.y = ...; + } + + struct nk_user_font font; + font.userdata.ptr = &your_font_class_or_struct; + font.height = your_font_height; + font.width = your_text_width_calculation; + font.query = query_your_font_glyph; + font.texture.id = your_font_texture; + + struct nk_context ctx; + nk_init_default(&ctx, &font); +``` +#### Nuklear font baker + +The final approach if you do not have a font handling functionality or don't +want to use it in this library is by using the optional font baker. +The font baker APIs can be used to create a font plus font atlas texture +and can be used with or without the vertex buffer output. + +It still uses the `nk_user_font` struct and the two different approaches +previously stated still work. The font baker is not located inside +`nk_context` like all other systems since it can be understood as more of +an extension to nuklear and does not really depend on any `nk_context` state. + +Font baker need to be initialized first by one of the nk_font_atlas_init_xxx +functions. If you don't care about memory just call the default version +`nk_font_atlas_init_default` which will allocate all memory from the standard library. +If you want to control memory allocation but you don't care if the allocated +memory is temporary and therefore can be freed directly after the baking process +is over or permanent you can call `nk_font_atlas_init`. + +After successfully initializing the font baker you can add Truetype(.ttf) fonts from +different sources like memory or from file by calling one of the `nk_font_atlas_add_xxx`. +functions. Adding font will permanently store each font, font config and ttf memory block(!) +inside the font atlas and allows to reuse the font atlas. If you don't want to reuse +the font baker by for example adding additional fonts you can call +`nk_font_atlas_cleanup` after the baking process is over (after calling nk_font_atlas_end). + +As soon as you added all fonts you wanted you can now start the baking process +for every selected glyph to image by calling `nk_font_atlas_bake`. +The baking process returns image memory, width and height which can be used to +either create your own image object or upload it to any graphics library. +No matter which case you finally have to call `nk_font_atlas_end` which +will free all temporary memory including the font atlas image so make sure +you created our texture beforehand. `nk_font_atlas_end` requires a handle +to your font texture or object and optionally fills a `struct nk_draw_null_texture` +which can be used for the optional vertex output. If you don't want it just +set the argument to `NULL`. + +At this point you are done and if you don't want to reuse the font atlas you +can call `nk_font_atlas_cleanup` to free all truetype blobs and configuration +memory. Finally if you don't use the font atlas and any of it's fonts anymore +you need to call `nk_font_atlas_clear` to free all memory still being used. + +```c + struct nk_font_atlas atlas; + nk_font_atlas_init_default(&atlas); + nk_font_atlas_begin(&atlas); + nk_font *font = nk_font_atlas_add_from_file(&atlas, "Path/To/Your/TTF_Font.ttf", 13, 0); + nk_font *font2 = nk_font_atlas_add_from_file(&atlas, "Path/To/Your/TTF_Font2.ttf", 16, 0); + const void* img = nk_font_atlas_bake(&atlas, &img_width, &img_height, NK_FONT_ATLAS_RGBA32); + nk_font_atlas_end(&atlas, nk_handle_id(texture), 0); + + struct nk_context ctx; + nk_init_default(&ctx, &font->handle); + while (1) { + + } + nk_font_atlas_clear(&atlas); +``` +The font baker API is probably the most complex API inside this library and +I would suggest reading some of my examples `example/` to get a grip on how +to use the font atlas. There are a number of details I left out. For example +how to merge fonts, configure a font with `nk_font_config` to use other languages, +use another texture coordinate format and a lot more: +```c + struct nk_font_config cfg = nk_font_config(font_pixel_height); + cfg.merge_mode = nk_false or nk_true; + cfg.range = nk_font_korean_glyph_ranges(); + cfg.coord_type = NK_COORD_PIXEL; + nk_font *font = nk_font_atlas_add_from_file(&atlas, "Path/To/Your/TTF_Font.ttf", 13, &cfg); +``` +### Memory Buffer +A basic (double)-buffer with linear allocation and resetting as only +freeing policy. The buffer's main purpose is to control all memory management +inside the GUI toolkit and still leave memory control as much as possible in +the hand of the user while also making sure the library is easy to use if +not as much control is needed. +In general all memory inside this library can be provided from the user in +three different ways. + +The first way and the one providing most control is by just passing a fixed +size memory block. In this case all control lies in the hand of the user +since he can exactly control where the memory comes from and how much memory +the library should consume. Of course using the fixed size API removes the +ability to automatically resize a buffer if not enough memory is provided so +you have to take over the resizing. While being a fixed sized buffer sounds +quite limiting, it is very effective in this library since the actual memory +consumption is quite stable and has a fixed upper bound for a lot of cases. + +If you don't want to think about how much memory the library should allocate +at all time or have a very dynamic UI with unpredictable memory consumption +habits but still want control over memory allocation you can use the dynamic +allocator based API. The allocator consists of two callbacks for allocating +and freeing memory and optional userdata so you can plugin your own allocator. + +The final and easiest way can be used by defining +NK_INCLUDE_DEFAULT_ALLOCATOR which uses the standard library memory +allocation functions malloc and free and takes over complete control over +memory in this library. +### Text Editor +Editing text in this library is handled by either `nk_edit_string` or +`nk_edit_buffer`. But like almost everything in this library there are multiple +ways of doing it and a balance between control and ease of use with memory +as well as functionality controlled by flags. +This library generally allows three different levels of memory control: +First of is the most basic way of just providing a simple char array with +string length. This method is probably the easiest way of handling simple +user text input. Main upside is complete control over memory while the biggest +downside in comparison with the other two approaches is missing undo/redo. +For UIs that require undo/redo the second way was created. It is based on +a fixed size nk_text_edit struct, which has an internal undo/redo stack. +This is mainly useful if you want something more like a text editor but don't want +to have a dynamically growing buffer. +The final way is using a dynamically growing nk_text_edit struct, which +has both a default version if you don't care where memory comes from and an +allocator version if you do. While the text editor is quite powerful for its +complexity I would not recommend editing gigabytes of data with it. +It is rather designed for uses cases which make sense for a GUI library not for +an full blown text editor. +### Drawing +This library was designed to be render backend agnostic so it does +not draw anything to screen. Instead all drawn shapes, widgets +are made of, are buffered into memory and make up a command queue. +Each frame therefore fills the command buffer with draw commands +that then need to be executed by the user and his own render backend. +After that the command buffer needs to be cleared and a new frame can be +started. It is probably important to note that the command buffer is the main +drawing API and the optional vertex buffer API only takes this format and +converts it into a hardware accessible format. + +To use the command queue to draw your own widgets you can access the +command buffer of each window by calling `nk_window_get_canvas` after +previously having called `nk_begin`: + +```c + void draw_red_rectangle_widget(struct nk_context *ctx) + { + struct nk_command_buffer *canvas; + struct nk_input *input = &ctx->input; + canvas = nk_window_get_canvas(ctx); + + struct nk_rect space; + enum nk_widget_layout_states state; + state = nk_widget(&space, ctx); + if (!state) return; + + if (state != NK_WIDGET_ROM) + update_your_widget_by_user_input(...); + nk_fill_rect(canvas, space, 0, nk_rgb(255,0,0)); + } + + if (nk_begin(...)) { + nk_layout_row_dynamic(ctx, 25, 1); + draw_red_rectangle_widget(ctx); + } + nk_end(..) + +``` +Important to know if you want to create your own widgets is the `nk_widget` +call. It allocates space on the panel reserved for this widget to be used, +but also returns the state of the widget space. If your widget is not seen and does +not have to be updated it is '0' and you can just return. If it only has +to be drawn the state will be `NK_WIDGET_ROM` otherwise you can do both +update and draw your widget. The reason for separating is to only draw and +update what is actually necessary which is crucial for performance. +Draw List +The optional vertex buffer draw list provides a 2D drawing context +with antialiasing functionality which takes basic filled or outlined shapes +or a path and outputs vertexes, elements and draw commands. +The actual draw list API is not required to be used directly while using this +library since converting the default library draw command output is done by +just calling `nk_convert` but I decided to still make this library accessible +since it can be useful. + +The draw list is based on a path buffering and polygon and polyline +rendering API which allows a lot of ways to draw 2D content to screen. +In fact it is probably more powerful than needed but allows even more crazy +things than this library provides by default. +### Stack +The style modifier stack can be used to temporarily change a +property inside `nk_style`. For example if you want a special +red button you can temporarily push the old button color onto a stack +draw the button with a red color and then you just pop the old color +back from the stack: + + nk_style_push_style_item(ctx, &ctx->style.button.normal, nk_style_item_color(nk_rgb(255,0,0))); + nk_style_push_style_item(ctx, &ctx->style.button.hover, nk_style_item_color(nk_rgb(255,0,0))); + nk_style_push_style_item(ctx, &ctx->style.button.active, nk_style_item_color(nk_rgb(255,0,0))); + nk_style_push_vec2(ctx, &cx->style.button.padding, nk_vec2(2,2)); + + nk_button(...); + + nk_style_pop_style_item(ctx); + nk_style_pop_style_item(ctx); + nk_style_pop_style_item(ctx); + nk_style_pop_vec2(ctx); + +Nuklear has a stack for style_items, float properties, vector properties, +flags, colors, fonts and for button_behavior. Each has it's own fixed size stack +which can be changed at compile time. +### Math + Since nuklear is supposed to work on all systems providing floating point + math without any dependencies I also had to implement my own math functions + for sqrt, sin and cos. Since the actual highly accurate implementations for + the standard library functions are quite complex and I do not need high + precision for my use cases I use approximations. + Sqrt + ---- + For square root nuklear uses the famous fast inverse square root: + https://en.wikipedia.org/wiki/Fast_inverse_square_root with + slightly tweaked magic constant. While on today's hardware it is + probably not faster it is still fast and accurate enough for + nuklear's use cases. IMPORTANT: this requires float format IEEE 754 + Sine/Cosine + ----------- + All constants inside both function are generated Remez's minimax + approximations for value range 0...2*PI. The reason why I decided to + approximate exactly that range is that nuklear only needs sine and + cosine to generate circles which only requires that exact range. + In addition I used Remez instead of Taylor for additional precision: + www.lolengine.net/blog/2011/12/21/better-function-approximations. + The tool I used to generate constants for both sine and cosine + (it can actually approximate a lot more functions) can be + found here: www.lolengine.net/wiki/oss/lolremez -XXX.XXX- X...X - X...X -X....X - X....X" X...XXXXXXXXXXXXX...X - " ## License @@ -2306,13 +2612,55 @@ X...XXXXXXXXXXXXX...X - " ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ## Changelog ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~none -[date][x.yy.zz]-[description] --[date]: date on which the change has been pushed --[x.yy.zz]: Numerical version string representation. Each version number on the right - resets back to zero if version on the left is incremented. - - [x]: Major version with API and library breaking changes - - [yy]: Minor version with non-breaking API and library changes - - [zz]: Bug fix version with no direct changes to API +[date] ([x.y.z]) - [description] +- [date]: date on which the change has been pushed +- [x.y.z]: Version string, represented in Semantic Versioning format + - [x]: Major version with API and library breaking changes + - [y]: Minor version with non-breaking API and library changes + - [z]: Patch version with no direct changes to the API +- 2022/12/17 (4.10.5) - Fix nk_font_bake_pack() using TTC font offset incorrectly +- 2022/10/24 (4.10.4) - Fix nk_str_{append,insert}_str_utf8 always returning 0 +- 2022/09/03 (4.10.3) - Renamed the `null` texture variable to `tex_null` +- 2022/08/01 (4.10.2) - Fix Apple Silicon with incorrect NK_SITE_TYPE and NK_POINTER_TYPE +- 2022/08/01 (4.10.1) - Fix cursor jumping back to beginning of text when typing more than + nk_edit_xxx limit +- 2022/05/27 (4.10.0) - Add nk_input_has_mouse_click_in_button_rect() to fix window move bug +- 2022/04/18 (4.9.7) - Change button behavior when NK_BUTTON_TRIGGER_ON_RELEASE is defined to + only trigger when the mouse position was inside the same button on down +- 2022/02/03 (4.9.6) - Allow overriding the NK_INV_SQRT function, similar to NK_SIN and NK_COS +- 2021/12/22 (4.9.5) - Revert layout bounds not accounting for padding due to regressions +- 2021/12/22 (4.9.4) - Fix checking hovering when window is minimized +- 2021/12/22 (4.09.3) - Fix layout bounds not accounting for padding +- 2021/12/19 (4.09.2) - Update to stb_rect_pack.h v1.01 and stb_truetype.h v1.26 +- 2021/12/16 (4.09.1) - Fix the majority of GCC warnings +- 2021/10/16 (4.09.0) - Added nk_spacer() widget +- 2021/09/22 (4.08.6) - Fix "may be used uninitialized" warnings in nk_widget +- 2021/09/22 (4.08.5) - GCC __builtin_offsetof only exists in version 4 and later +- 2021/09/15 (4.08.4) - Fix "'num_len' may be used uninitialized" in nk_do_property +- 2021/09/15 (4.08.3) - Fix "Templates cannot be declared to have 'C' Linkage" +- 2021/09/08 (4.08.2) - Fix warnings in C89 builds +- 2021/09/08 (4.08.1) - Use compiler builtins for NK_OFFSETOF when possible +- 2021/08/17 (4.08.0) - Implemented 9-slice scaling support for widget styles +- 2021/08/16 (4.07.5) - Replace usage of memset in nk_font_atlas_bake with NK_MEMSET +- 2021/08/15 (4.07.4) - Fix conversion and sign conversion warnings +- 2021/08/08 (4.07.3) - Fix crash when baking merged fonts +- 2021/08/08 (4.07.2) - Fix Multiline Edit wrong offset +- 2021/03/17 (4.07.1) - Fix warning about unused parameter +- 2021/03/17 (4.07.0) - Fix nk_property hover bug +- 2021/03/15 (4.06.4) - Change nk_propertyi back to int +- 2021/03/15 (4.06.3) - Update documentation for functions that now return nk_bool +- 2020/12/19 (4.06.2) - Fix additional C++ style comments which are not allowed in ISO C90. +- 2020/10/11 (4.06.1) - Fix C++ style comments which are not allowed in ISO C90. +- 2020/10/07 (4.06.0) - Fix nk_combo return type wrongly changed to nk_bool +- 2020/09/05 (4.05.0) - Use the nk_font_atlas allocator for stb_truetype memory management. +- 2020/09/04 (4.04.1) - Replace every boolean int by nk_bool +- 2020/09/04 (4.04.0) - Add nk_bool with NK_INCLUDE_STANDARD_BOOL +- 2020/06/13 (4.03.1) - Fix nk_pool allocation sizes. +- 2020/06/04 (4.03.0) - Made nk_combo header symbols optional. +- 2020/05/27 (4.02.5) - Fix nk_do_edit: Keep scroll position when re-activating edit widget. +- 2020/05/09 (4.02.4) - Fix nk_menubar height calculation bug +- 2020/05/08 (4.02.3) - Fix missing stdarg.h with NK_INCLUDE_STANDARD_VARARGS +- 2020/04/30 (4.02.2) - Fix nk_edit border drawing bug - 2020/04/09 (4.02.1) - Removed unused nk_sqrt function to fix compiler warnings - Fixed compiler warnings if you bring your own methods for nk_cos/nk_sin/nk_strtod/nk_memset/nk_memcopy/nk_dtoa diff --git a/index.html b/index.html new file mode 100644 index 0000000..e69de29 diff --git a/nuklear.h b/nuklear.h index febee39..b06753f 100644 --- a/nuklear.h +++ b/nuklear.h @@ -48,6 +48,7 @@ /// - No global or hidden state /// - Customizable library modules (you can compile and use only what you need) /// - Optional font baker and vertex buffer output +/// - [Code available on github](https://github.com/Immediate-Mode-UI/Nuklear/) /// /// ## Features /// - Absolutely no platform dependent code @@ -3797,149 +3798,155 @@ NK_API const char* nk_utf_at(const char *buffer, int length, int index, nk_rune * FONT * * ===============================================================*/ -/* Font handling in this library was designed to be quite customizable and lets - you decide what you want to use and what you want to provide. There are three - different ways to use the font atlas. The first two will use your font - handling scheme and only requires essential data to run nuklear. The next - slightly more advanced features is font handling with vertex buffer output. - Finally the most complex API wise is using nuklear's font baking API. - - 1.) Using your own implementation without vertex buffer output - -------------------------------------------------------------- - So first up the easiest way to do font handling is by just providing a - `nk_user_font` struct which only requires the height in pixel of the used - font and a callback to calculate the width of a string. This way of handling - fonts is best fitted for using the normal draw shape command API where you - do all the text drawing yourself and the library does not require any kind - of deeper knowledge about which font handling mechanism you use. - IMPORTANT: the `nk_user_font` pointer provided to nuklear has to persist - over the complete life time! I know this sucks but it is currently the only - way to switch between fonts. - - float your_text_width_calculation(nk_handle handle, float height, const char *text, int len) - { - your_font_type *type = handle.ptr; - float text_width = ...; - return text_width; - } - - struct nk_user_font font; - font.userdata.ptr = &your_font_class_or_struct; - font.height = your_font_height; - font.width = your_text_width_calculation; - - struct nk_context ctx; - nk_init_default(&ctx, &font); - - 2.) Using your own implementation with vertex buffer output - -------------------------------------------------------------- - While the first approach works fine if you don't want to use the optional - vertex buffer output it is not enough if you do. To get font handling working - for these cases you have to provide two additional parameters inside the - `nk_user_font`. First a texture atlas handle used to draw text as subimages - of a bigger font atlas texture and a callback to query a character's glyph - information (offset, size, ...). So it is still possible to provide your own - font and use the vertex buffer output. - - float your_text_width_calculation(nk_handle handle, float height, const char *text, int len) - { - your_font_type *type = handle.ptr; - float text_width = ...; - return text_width; - } - void query_your_font_glyph(nk_handle handle, float font_height, struct nk_user_font_glyph *glyph, nk_rune codepoint, nk_rune next_codepoint) - { - your_font_type *type = handle.ptr; - glyph.width = ...; - glyph.height = ...; - glyph.xadvance = ...; - glyph.uv[0].x = ...; - glyph.uv[0].y = ...; - glyph.uv[1].x = ...; - glyph.uv[1].y = ...; - glyph.offset.x = ...; - glyph.offset.y = ...; - } - - struct nk_user_font font; - font.userdata.ptr = &your_font_class_or_struct; - font.height = your_font_height; - font.width = your_text_width_calculation; - font.query = query_your_font_glyph; - font.texture.id = your_font_texture; - - struct nk_context ctx; - nk_init_default(&ctx, &font); - - 3.) Nuklear font baker - ------------------------------------ - The final approach if you do not have a font handling functionality or don't - want to use it in this library is by using the optional font baker. - The font baker APIs can be used to create a font plus font atlas texture - and can be used with or without the vertex buffer output. - - It still uses the `nk_user_font` struct and the two different approaches - previously stated still work. The font baker is not located inside - `nk_context` like all other systems since it can be understood as more of - an extension to nuklear and does not really depend on any `nk_context` state. - - Font baker need to be initialized first by one of the nk_font_atlas_init_xxx - functions. If you don't care about memory just call the default version - `nk_font_atlas_init_default` which will allocate all memory from the standard library. - If you want to control memory allocation but you don't care if the allocated - memory is temporary and therefore can be freed directly after the baking process - is over or permanent you can call `nk_font_atlas_init`. - - After successfully initializing the font baker you can add Truetype(.ttf) fonts from - different sources like memory or from file by calling one of the `nk_font_atlas_add_xxx`. - functions. Adding font will permanently store each font, font config and ttf memory block(!) - inside the font atlas and allows to reuse the font atlas. If you don't want to reuse - the font baker by for example adding additional fonts you can call - `nk_font_atlas_cleanup` after the baking process is over (after calling nk_font_atlas_end). - - As soon as you added all fonts you wanted you can now start the baking process - for every selected glyph to image by calling `nk_font_atlas_bake`. - The baking process returns image memory, width and height which can be used to - either create your own image object or upload it to any graphics library. - No matter which case you finally have to call `nk_font_atlas_end` which - will free all temporary memory including the font atlas image so make sure - you created our texture beforehand. `nk_font_atlas_end` requires a handle - to your font texture or object and optionally fills a `struct nk_draw_null_texture` - which can be used for the optional vertex output. If you don't want it just - set the argument to `NULL`. - - At this point you are done and if you don't want to reuse the font atlas you - can call `nk_font_atlas_cleanup` to free all truetype blobs and configuration - memory. Finally if you don't use the font atlas and any of it's fonts anymore - you need to call `nk_font_atlas_clear` to free all memory still being used. - - struct nk_font_atlas atlas; - nk_font_atlas_init_default(&atlas); - nk_font_atlas_begin(&atlas); - nk_font *font = nk_font_atlas_add_from_file(&atlas, "Path/To/Your/TTF_Font.ttf", 13, 0); - nk_font *font2 = nk_font_atlas_add_from_file(&atlas, "Path/To/Your/TTF_Font2.ttf", 16, 0); - const void* img = nk_font_atlas_bake(&atlas, &img_width, &img_height, NK_FONT_ATLAS_RGBA32); - nk_font_atlas_end(&atlas, nk_handle_id(texture), 0); - - struct nk_context ctx; - nk_init_default(&ctx, &font->handle); - while (1) { - - } - nk_font_atlas_clear(&atlas); - - The font baker API is probably the most complex API inside this library and - I would suggest reading some of my examples `example/` to get a grip on how - to use the font atlas. There are a number of details I left out. For example - how to merge fonts, configure a font with `nk_font_config` to use other languages, - use another texture coordinate format and a lot more: - - struct nk_font_config cfg = nk_font_config(font_pixel_height); - cfg.merge_mode = nk_false or nk_true; - cfg.range = nk_font_korean_glyph_ranges(); - cfg.coord_type = NK_COORD_PIXEL; - nk_font *font = nk_font_atlas_add_from_file(&atlas, "Path/To/Your/TTF_Font.ttf", 13, &cfg); - +/*/// ### Font +/// Font handling in this library was designed to be quite customizable and lets +/// you decide what you want to use and what you want to provide. There are three +/// different ways to use the font atlas. The first two will use your font +/// handling scheme and only requires essential data to run nuklear. The next +/// slightly more advanced features is font handling with vertex buffer output. +/// Finally the most complex API wise is using nuklear's font baking API. +// +/// #### Using your own implementation without vertex buffer output +/// +/// So first up the easiest way to do font handling is by just providing a +/// `nk_user_font` struct which only requires the height in pixel of the used +/// font and a callback to calculate the width of a string. This way of handling +/// fonts is best fitted for using the normal draw shape command API where you +/// do all the text drawing yourself and the library does not require any kind +/// of deeper knowledge about which font handling mechanism you use. +/// IMPORTANT: the `nk_user_font` pointer provided to nuklear has to persist +/// over the complete life time! I know this sucks but it is currently the only +/// way to switch between fonts. +/// +/// ```c +/// float your_text_width_calculation(nk_handle handle, float height, const char *text, int len) +/// { +/// your_font_type *type = handle.ptr; +/// float text_width = ...; +/// return text_width; +/// } +/// +/// struct nk_user_font font; +/// font.userdata.ptr = &your_font_class_or_struct; +/// font.height = your_font_height; +/// font.width = your_text_width_calculation; +/// +/// struct nk_context ctx; +/// nk_init_default(&ctx, &font); +/// ``` +/// #### Using your own implementation with vertex buffer output +/// +/// While the first approach works fine if you don't want to use the optional +/// vertex buffer output it is not enough if you do. To get font handling working +/// for these cases you have to provide two additional parameters inside the +/// `nk_user_font`. First a texture atlas handle used to draw text as subimages +/// of a bigger font atlas texture and a callback to query a character's glyph +/// information (offset, size, ...). So it is still possible to provide your own +/// font and use the vertex buffer output. +/// +/// ```c +/// float your_text_width_calculation(nk_handle handle, float height, const char *text, int len) +/// { +/// your_font_type *type = handle.ptr; +/// float text_width = ...; +/// return text_width; +/// } +/// void query_your_font_glyph(nk_handle handle, float font_height, struct nk_user_font_glyph *glyph, nk_rune codepoint, nk_rune next_codepoint) +/// { +/// your_font_type *type = handle.ptr; +/// glyph.width = ...; +/// glyph.height = ...; +/// glyph.xadvance = ...; +/// glyph.uv[0].x = ...; +/// glyph.uv[0].y = ...; +/// glyph.uv[1].x = ...; +/// glyph.uv[1].y = ...; +/// glyph.offset.x = ...; +/// glyph.offset.y = ...; +/// } +/// +/// struct nk_user_font font; +/// font.userdata.ptr = &your_font_class_or_struct; +/// font.height = your_font_height; +/// font.width = your_text_width_calculation; +/// font.query = query_your_font_glyph; +/// font.texture.id = your_font_texture; +/// +/// struct nk_context ctx; +/// nk_init_default(&ctx, &font); +/// ``` +/// +/// #### Nuklear font baker +/// +/// The final approach if you do not have a font handling functionality or don't +/// want to use it in this library is by using the optional font baker. +/// The font baker APIs can be used to create a font plus font atlas texture +/// and can be used with or without the vertex buffer output. +/// +/// It still uses the `nk_user_font` struct and the two different approaches +/// previously stated still work. The font baker is not located inside +/// `nk_context` like all other systems since it can be understood as more of +/// an extension to nuklear and does not really depend on any `nk_context` state. +/// +/// Font baker need to be initialized first by one of the nk_font_atlas_init_xxx +/// functions. If you don't care about memory just call the default version +/// `nk_font_atlas_init_default` which will allocate all memory from the standard library. +/// If you want to control memory allocation but you don't care if the allocated +/// memory is temporary and therefore can be freed directly after the baking process +/// is over or permanent you can call `nk_font_atlas_init`. +/// +/// After successfully initializing the font baker you can add Truetype(.ttf) fonts from +/// different sources like memory or from file by calling one of the `nk_font_atlas_add_xxx`. +/// functions. Adding font will permanently store each font, font config and ttf memory block(!) +/// inside the font atlas and allows to reuse the font atlas. If you don't want to reuse +/// the font baker by for example adding additional fonts you can call +/// `nk_font_atlas_cleanup` after the baking process is over (after calling nk_font_atlas_end). +/// +/// As soon as you added all fonts you wanted you can now start the baking process +/// for every selected glyph to image by calling `nk_font_atlas_bake`. +/// The baking process returns image memory, width and height which can be used to +/// either create your own image object or upload it to any graphics library. +/// No matter which case you finally have to call `nk_font_atlas_end` which +/// will free all temporary memory including the font atlas image so make sure +/// you created our texture beforehand. `nk_font_atlas_end` requires a handle +/// to your font texture or object and optionally fills a `struct nk_draw_null_texture` +/// which can be used for the optional vertex output. If you don't want it just +/// set the argument to `NULL`. +/// +/// At this point you are done and if you don't want to reuse the font atlas you +/// can call `nk_font_atlas_cleanup` to free all truetype blobs and configuration +/// memory. Finally if you don't use the font atlas and any of it's fonts anymore +/// you need to call `nk_font_atlas_clear` to free all memory still being used. +/// +/// ```c +/// struct nk_font_atlas atlas; +/// nk_font_atlas_init_default(&atlas); +/// nk_font_atlas_begin(&atlas); +/// nk_font *font = nk_font_atlas_add_from_file(&atlas, "Path/To/Your/TTF_Font.ttf", 13, 0); +/// nk_font *font2 = nk_font_atlas_add_from_file(&atlas, "Path/To/Your/TTF_Font2.ttf", 16, 0); +/// const void* img = nk_font_atlas_bake(&atlas, &img_width, &img_height, NK_FONT_ATLAS_RGBA32); +/// nk_font_atlas_end(&atlas, nk_handle_id(texture), 0); +/// +/// struct nk_context ctx; +/// nk_init_default(&ctx, &font->handle); +/// while (1) { +/// +/// } +/// nk_font_atlas_clear(&atlas); +/// ``` +/// The font baker API is probably the most complex API inside this library and +/// I would suggest reading some of my examples `example/` to get a grip on how +/// to use the font atlas. There are a number of details I left out. For example +/// how to merge fonts, configure a font with `nk_font_config` to use other languages, +/// use another texture coordinate format and a lot more: +/// +/// ```c +/// struct nk_font_config cfg = nk_font_config(font_pixel_height); +/// cfg.merge_mode = nk_false or nk_true; +/// cfg.range = nk_font_korean_glyph_ranges(); +/// cfg.coord_type = NK_COORD_PIXEL; +/// nk_font *font = nk_font_atlas_add_from_file(&atlas, "Path/To/Your/TTF_Font.ttf", 13, &cfg); +/// ``` */ struct nk_user_font_glyph; typedef float(*nk_text_width_f)(nk_handle, float h, const char*, int len); @@ -4110,33 +4117,34 @@ NK_API void nk_font_atlas_clear(struct nk_font_atlas*); * MEMORY BUFFER * * ===============================================================*/ -/* A basic (double)-buffer with linear allocation and resetting as only - freeing policy. The buffer's main purpose is to control all memory management - inside the GUI toolkit and still leave memory control as much as possible in - the hand of the user while also making sure the library is easy to use if - not as much control is needed. - In general all memory inside this library can be provided from the user in - three different ways. - - The first way and the one providing most control is by just passing a fixed - size memory block. In this case all control lies in the hand of the user - since he can exactly control where the memory comes from and how much memory - the library should consume. Of course using the fixed size API removes the - ability to automatically resize a buffer if not enough memory is provided so - you have to take over the resizing. While being a fixed sized buffer sounds - quite limiting, it is very effective in this library since the actual memory - consumption is quite stable and has a fixed upper bound for a lot of cases. - - If you don't want to think about how much memory the library should allocate - at all time or have a very dynamic UI with unpredictable memory consumption - habits but still want control over memory allocation you can use the dynamic - allocator based API. The allocator consists of two callbacks for allocating - and freeing memory and optional userdata so you can plugin your own allocator. - - The final and easiest way can be used by defining - NK_INCLUDE_DEFAULT_ALLOCATOR which uses the standard library memory - allocation functions malloc and free and takes over complete control over - memory in this library. +/*/// ### Memory Buffer +/// A basic (double)-buffer with linear allocation and resetting as only +/// freeing policy. The buffer's main purpose is to control all memory management +/// inside the GUI toolkit and still leave memory control as much as possible in +/// the hand of the user while also making sure the library is easy to use if +/// not as much control is needed. +/// In general all memory inside this library can be provided from the user in +/// three different ways. +/// +/// The first way and the one providing most control is by just passing a fixed +/// size memory block. In this case all control lies in the hand of the user +/// since he can exactly control where the memory comes from and how much memory +/// the library should consume. Of course using the fixed size API removes the +/// ability to automatically resize a buffer if not enough memory is provided so +/// you have to take over the resizing. While being a fixed sized buffer sounds +/// quite limiting, it is very effective in this library since the actual memory +/// consumption is quite stable and has a fixed upper bound for a lot of cases. +/// +/// If you don't want to think about how much memory the library should allocate +/// at all time or have a very dynamic UI with unpredictable memory consumption +/// habits but still want control over memory allocation you can use the dynamic +/// allocator based API. The allocator consists of two callbacks for allocating +/// and freeing memory and optional userdata so you can plugin your own allocator. +/// +/// The final and easiest way can be used by defining +/// NK_INCLUDE_DEFAULT_ALLOCATOR which uses the standard library memory +/// allocation functions malloc and free and takes over complete control over +/// memory in this library. */ struct nk_memory_status { void *memory; @@ -4261,28 +4269,29 @@ NK_API int nk_str_len_char(struct nk_str*); * TEXT EDITOR * * ===============================================================*/ -/* Editing text in this library is handled by either `nk_edit_string` or - * `nk_edit_buffer`. But like almost everything in this library there are multiple - * ways of doing it and a balance between control and ease of use with memory - * as well as functionality controlled by flags. - * - * This library generally allows three different levels of memory control: - * First of is the most basic way of just providing a simple char array with - * string length. This method is probably the easiest way of handling simple - * user text input. Main upside is complete control over memory while the biggest - * downside in comparison with the other two approaches is missing undo/redo. - * - * For UIs that require undo/redo the second way was created. It is based on - * a fixed size nk_text_edit struct, which has an internal undo/redo stack. - * This is mainly useful if you want something more like a text editor but don't want - * to have a dynamically growing buffer. - * - * The final way is using a dynamically growing nk_text_edit struct, which - * has both a default version if you don't care where memory comes from and an - * allocator version if you do. While the text editor is quite powerful for its - * complexity I would not recommend editing gigabytes of data with it. - * It is rather designed for uses cases which make sense for a GUI library not for - * an full blown text editor. +/*/// ### Text Editor +/// Editing text in this library is handled by either `nk_edit_string` or +/// `nk_edit_buffer`. But like almost everything in this library there are multiple +/// ways of doing it and a balance between control and ease of use with memory +/// as well as functionality controlled by flags. +/// +/// This library generally allows three different levels of memory control: +/// First of is the most basic way of just providing a simple char array with +/// string length. This method is probably the easiest way of handling simple +/// user text input. Main upside is complete control over memory while the biggest +/// downside in comparison with the other two approaches is missing undo/redo. +/// +/// For UIs that require undo/redo the second way was created. It is based on +/// a fixed size nk_text_edit struct, which has an internal undo/redo stack. +/// This is mainly useful if you want something more like a text editor but don't want +/// to have a dynamically growing buffer. +/// +/// The final way is using a dynamically growing nk_text_edit struct, which +/// has both a default version if you don't care where memory comes from and an +/// allocator version if you do. While the text editor is quite powerful for its +/// complexity I would not recommend editing gigabytes of data with it. +/// It is rather designed for uses cases which make sense for a GUI library not for +/// an full blown text editor. */ #ifndef NK_TEXTEDIT_UNDOSTATECOUNT #define NK_TEXTEDIT_UNDOSTATECOUNT 99 @@ -4376,49 +4385,52 @@ NK_API void nk_textedit_redo(struct nk_text_edit*); * DRAWING * * ===============================================================*/ -/* This library was designed to be render backend agnostic so it does - not draw anything to screen. Instead all drawn shapes, widgets - are made of, are buffered into memory and make up a command queue. - Each frame therefore fills the command buffer with draw commands - that then need to be executed by the user and his own render backend. - After that the command buffer needs to be cleared and a new frame can be - started. It is probably important to note that the command buffer is the main - drawing API and the optional vertex buffer API only takes this format and - converts it into a hardware accessible format. - - To use the command queue to draw your own widgets you can access the - command buffer of each window by calling `nk_window_get_canvas` after - previously having called `nk_begin`: - - void draw_red_rectangle_widget(struct nk_context *ctx) - { - struct nk_command_buffer *canvas; - struct nk_input *input = &ctx->input; - canvas = nk_window_get_canvas(ctx); - - struct nk_rect space; - enum nk_widget_layout_states state; - state = nk_widget(&space, ctx); - if (!state) return; - - if (state != NK_WIDGET_ROM) - update_your_widget_by_user_input(...); - nk_fill_rect(canvas, space, 0, nk_rgb(255,0,0)); - } - - if (nk_begin(...)) { - nk_layout_row_dynamic(ctx, 25, 1); - draw_red_rectangle_widget(ctx); - } - nk_end(..) - - Important to know if you want to create your own widgets is the `nk_widget` - call. It allocates space on the panel reserved for this widget to be used, - but also returns the state of the widget space. If your widget is not seen and does - not have to be updated it is '0' and you can just return. If it only has - to be drawn the state will be `NK_WIDGET_ROM` otherwise you can do both - update and draw your widget. The reason for separating is to only draw and - update what is actually necessary which is crucial for performance. +/*/// ### Drawing +/// This library was designed to be render backend agnostic so it does +/// not draw anything to screen. Instead all drawn shapes, widgets +/// are made of, are buffered into memory and make up a command queue. +/// Each frame therefore fills the command buffer with draw commands +/// that then need to be executed by the user and his own render backend. +/// After that the command buffer needs to be cleared and a new frame can be +/// started. It is probably important to note that the command buffer is the main +/// drawing API and the optional vertex buffer API only takes this format and +/// converts it into a hardware accessible format. +/// +/// To use the command queue to draw your own widgets you can access the +/// command buffer of each window by calling `nk_window_get_canvas` after +/// previously having called `nk_begin`: +/// +/// ```c +/// void draw_red_rectangle_widget(struct nk_context *ctx) +/// { +/// struct nk_command_buffer *canvas; +/// struct nk_input *input = &ctx->input; +/// canvas = nk_window_get_canvas(ctx); +/// +/// struct nk_rect space; +/// enum nk_widget_layout_states state; +/// state = nk_widget(&space, ctx); +/// if (!state) return; +/// +/// if (state != NK_WIDGET_ROM) +/// update_your_widget_by_user_input(...); +/// nk_fill_rect(canvas, space, 0, nk_rgb(255,0,0)); +/// } +/// +/// if (nk_begin(...)) { +/// nk_layout_row_dynamic(ctx, 25, 1); +/// draw_red_rectangle_widget(ctx); +/// } +/// nk_end(..) +/// +/// ``` +/// Important to know if you want to create your own widgets is the `nk_widget` +/// call. It allocates space on the panel reserved for this widget to be used, +/// but also returns the state of the widget space. If your widget is not seen and does +/// not have to be updated it is '0' and you can just return. If it only has +/// to be drawn the state will be `NK_WIDGET_ROM` otherwise you can do both +/// update and draw your widget. The reason for separating is to only draw and +/// update what is actually necessary which is crucial for performance. */ enum nk_command_type { NK_COMMAND_NOP, @@ -4703,18 +4715,19 @@ NK_API nk_bool nk_input_is_key_down(const struct nk_input*, enum nk_keys); * * ===============================================================*/ #ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT -/* The optional vertex buffer draw list provides a 2D drawing context - with antialiasing functionality which takes basic filled or outlined shapes - or a path and outputs vertexes, elements and draw commands. - The actual draw list API is not required to be used directly while using this - library since converting the default library draw command output is done by - just calling `nk_convert` but I decided to still make this library accessible - since it can be useful. - - The draw list is based on a path buffering and polygon and polyline - rendering API which allows a lot of ways to draw 2D content to screen. - In fact it is probably more powerful than needed but allows even more crazy - things than this library provides by default. +/* ### Draw List +/// The optional vertex buffer draw list provides a 2D drawing context +/// with antialiasing functionality which takes basic filled or outlined shapes +/// or a path and outputs vertexes, elements and draw commands. +/// The actual draw list API is not required to be used directly while using this +/// library since converting the default library draw command output is done by +/// just calling `nk_convert` but I decided to still make this library accessible +/// since it can be useful. +/// +/// The draw list is based on a path buffering and polygon and polyline +/// rendering API which allows a lot of ways to draw 2D content to screen. +/// In fact it is probably more powerful than needed but allows even more crazy +/// things than this library provides by default. */ #ifdef NK_UINT_DRAW_INDEX typedef nk_uint nk_draw_index; @@ -5492,27 +5505,28 @@ struct nk_window { /*============================================================== * STACK * =============================================================*/ -/* The style modifier stack can be used to temporarily change a - * property inside `nk_style`. For example if you want a special - * red button you can temporarily push the old button color onto a stack - * draw the button with a red color and then you just pop the old color - * back from the stack: - * - * nk_style_push_style_item(ctx, &ctx->style.button.normal, nk_style_item_color(nk_rgb(255,0,0))); - * nk_style_push_style_item(ctx, &ctx->style.button.hover, nk_style_item_color(nk_rgb(255,0,0))); - * nk_style_push_style_item(ctx, &ctx->style.button.active, nk_style_item_color(nk_rgb(255,0,0))); - * nk_style_push_vec2(ctx, &cx->style.button.padding, nk_vec2(2,2)); - * - * nk_button(...); - * - * nk_style_pop_style_item(ctx); - * nk_style_pop_style_item(ctx); - * nk_style_pop_style_item(ctx); - * nk_style_pop_vec2(ctx); - * - * Nuklear has a stack for style_items, float properties, vector properties, - * flags, colors, fonts and for button_behavior. Each has it's own fixed size stack - * which can be changed at compile time. +/*/// ### Stack +/// The style modifier stack can be used to temporarily change a +/// property inside `nk_style`. For example if you want a special +/// red button you can temporarily push the old button color onto a stack +/// draw the button with a red color and then you just pop the old color +/// back from the stack: +/// +/// nk_style_push_style_item(ctx, &ctx->style.button.normal, nk_style_item_color(nk_rgb(255,0,0))); +/// nk_style_push_style_item(ctx, &ctx->style.button.hover, nk_style_item_color(nk_rgb(255,0,0))); +/// nk_style_push_style_item(ctx, &ctx->style.button.active, nk_style_item_color(nk_rgb(255,0,0))); +/// nk_style_push_vec2(ctx, &cx->style.button.padding, nk_vec2(2,2)); +/// +/// nk_button(...); +/// +/// nk_style_pop_style_item(ctx); +/// nk_style_pop_style_item(ctx); +/// nk_style_pop_style_item(ctx); +/// nk_style_pop_vec2(ctx); +/// +/// Nuklear has a stack for style_items, float properties, vector properties, +/// flags, colors, fonts and for button_behavior. Each has it's own fixed size stack +/// which can be changed at compile time. */ #ifndef NK_BUTTON_BEHAVIOR_STACK_SIZE #define NK_BUTTON_BEHAVIOR_STACK_SIZE 8 @@ -6111,32 +6125,33 @@ nk_stbtt_free(void *ptr, void *user_data) { * MATH * * ===============================================================*/ -/* Since nuklear is supposed to work on all systems providing floating point - math without any dependencies I also had to implement my own math functions - for sqrt, sin and cos. Since the actual highly accurate implementations for - the standard library functions are quite complex and I do not need high - precision for my use cases I use approximations. - - Sqrt - ---- - For square root nuklear uses the famous fast inverse square root: - https://en.wikipedia.org/wiki/Fast_inverse_square_root with - slightly tweaked magic constant. While on today's hardware it is - probably not faster it is still fast and accurate enough for - nuklear's use cases. IMPORTANT: this requires float format IEEE 754 - - Sine/Cosine - ----------- - All constants inside both function are generated Remez's minimax - approximations for value range 0...2*PI. The reason why I decided to - approximate exactly that range is that nuklear only needs sine and - cosine to generate circles which only requires that exact range. - In addition I used Remez instead of Taylor for additional precision: - www.lolengine.net/blog/2011/12/21/better-function-approximations. - - The tool I used to generate constants for both sine and cosine - (it can actually approximate a lot more functions) can be - found here: www.lolengine.net/wiki/oss/lolremez +/*/// ### Math +/// Since nuklear is supposed to work on all systems providing floating point +/// math without any dependencies I also had to implement my own math functions +/// for sqrt, sin and cos. Since the actual highly accurate implementations for +/// the standard library functions are quite complex and I do not need high +/// precision for my use cases I use approximations. +/// +/// Sqrt +/// ---- +/// For square root nuklear uses the famous fast inverse square root: +/// https://en.wikipedia.org/wiki/Fast_inverse_square_root with +/// slightly tweaked magic constant. While on today's hardware it is +/// probably not faster it is still fast and accurate enough for +/// nuklear's use cases. IMPORTANT: this requires float format IEEE 754 +/// +/// Sine/Cosine +/// ----------- +/// All constants inside both function are generated Remez's minimax +/// approximations for value range 0...2*PI. The reason why I decided to +/// approximate exactly that range is that nuklear only needs sine and +/// cosine to generate circles which only requires that exact range. +/// In addition I used Remez instead of Taylor for additional precision: +/// www.lolengine.net/blog/2011/12/21/better-function-approximations. +/// +/// The tool I used to generate constants for both sine and cosine +/// (it can actually approximate a lot more functions) can be +/// found here: www.lolengine.net/wiki/oss/lolremez */ #ifndef NK_INV_SQRT #define NK_INV_SQRT nk_inv_sqrt diff --git a/src/nuklear.h b/src/nuklear.h index 2d4af9d..36539c3 100644 --- a/src/nuklear.h +++ b/src/nuklear.h @@ -3576,149 +3576,155 @@ NK_API const char* nk_utf_at(const char *buffer, int length, int index, nk_rune * FONT * * ===============================================================*/ -/* Font handling in this library was designed to be quite customizable and lets - you decide what you want to use and what you want to provide. There are three - different ways to use the font atlas. The first two will use your font - handling scheme and only requires essential data to run nuklear. The next - slightly more advanced features is font handling with vertex buffer output. - Finally the most complex API wise is using nuklear's font baking API. - - 1.) Using your own implementation without vertex buffer output - -------------------------------------------------------------- - So first up the easiest way to do font handling is by just providing a - `nk_user_font` struct which only requires the height in pixel of the used - font and a callback to calculate the width of a string. This way of handling - fonts is best fitted for using the normal draw shape command API where you - do all the text drawing yourself and the library does not require any kind - of deeper knowledge about which font handling mechanism you use. - IMPORTANT: the `nk_user_font` pointer provided to nuklear has to persist - over the complete life time! I know this sucks but it is currently the only - way to switch between fonts. - - float your_text_width_calculation(nk_handle handle, float height, const char *text, int len) - { - your_font_type *type = handle.ptr; - float text_width = ...; - return text_width; - } - - struct nk_user_font font; - font.userdata.ptr = &your_font_class_or_struct; - font.height = your_font_height; - font.width = your_text_width_calculation; - - struct nk_context ctx; - nk_init_default(&ctx, &font); - - 2.) Using your own implementation with vertex buffer output - -------------------------------------------------------------- - While the first approach works fine if you don't want to use the optional - vertex buffer output it is not enough if you do. To get font handling working - for these cases you have to provide two additional parameters inside the - `nk_user_font`. First a texture atlas handle used to draw text as subimages - of a bigger font atlas texture and a callback to query a character's glyph - information (offset, size, ...). So it is still possible to provide your own - font and use the vertex buffer output. - - float your_text_width_calculation(nk_handle handle, float height, const char *text, int len) - { - your_font_type *type = handle.ptr; - float text_width = ...; - return text_width; - } - void query_your_font_glyph(nk_handle handle, float font_height, struct nk_user_font_glyph *glyph, nk_rune codepoint, nk_rune next_codepoint) - { - your_font_type *type = handle.ptr; - glyph.width = ...; - glyph.height = ...; - glyph.xadvance = ...; - glyph.uv[0].x = ...; - glyph.uv[0].y = ...; - glyph.uv[1].x = ...; - glyph.uv[1].y = ...; - glyph.offset.x = ...; - glyph.offset.y = ...; - } - - struct nk_user_font font; - font.userdata.ptr = &your_font_class_or_struct; - font.height = your_font_height; - font.width = your_text_width_calculation; - font.query = query_your_font_glyph; - font.texture.id = your_font_texture; - - struct nk_context ctx; - nk_init_default(&ctx, &font); - - 3.) Nuklear font baker - ------------------------------------ - The final approach if you do not have a font handling functionality or don't - want to use it in this library is by using the optional font baker. - The font baker APIs can be used to create a font plus font atlas texture - and can be used with or without the vertex buffer output. - - It still uses the `nk_user_font` struct and the two different approaches - previously stated still work. The font baker is not located inside - `nk_context` like all other systems since it can be understood as more of - an extension to nuklear and does not really depend on any `nk_context` state. - - Font baker need to be initialized first by one of the nk_font_atlas_init_xxx - functions. If you don't care about memory just call the default version - `nk_font_atlas_init_default` which will allocate all memory from the standard library. - If you want to control memory allocation but you don't care if the allocated - memory is temporary and therefore can be freed directly after the baking process - is over or permanent you can call `nk_font_atlas_init`. - - After successfully initializing the font baker you can add Truetype(.ttf) fonts from - different sources like memory or from file by calling one of the `nk_font_atlas_add_xxx`. - functions. Adding font will permanently store each font, font config and ttf memory block(!) - inside the font atlas and allows to reuse the font atlas. If you don't want to reuse - the font baker by for example adding additional fonts you can call - `nk_font_atlas_cleanup` after the baking process is over (after calling nk_font_atlas_end). - - As soon as you added all fonts you wanted you can now start the baking process - for every selected glyph to image by calling `nk_font_atlas_bake`. - The baking process returns image memory, width and height which can be used to - either create your own image object or upload it to any graphics library. - No matter which case you finally have to call `nk_font_atlas_end` which - will free all temporary memory including the font atlas image so make sure - you created our texture beforehand. `nk_font_atlas_end` requires a handle - to your font texture or object and optionally fills a `struct nk_draw_null_texture` - which can be used for the optional vertex output. If you don't want it just - set the argument to `NULL`. - - At this point you are done and if you don't want to reuse the font atlas you - can call `nk_font_atlas_cleanup` to free all truetype blobs and configuration - memory. Finally if you don't use the font atlas and any of it's fonts anymore - you need to call `nk_font_atlas_clear` to free all memory still being used. - - struct nk_font_atlas atlas; - nk_font_atlas_init_default(&atlas); - nk_font_atlas_begin(&atlas); - nk_font *font = nk_font_atlas_add_from_file(&atlas, "Path/To/Your/TTF_Font.ttf", 13, 0); - nk_font *font2 = nk_font_atlas_add_from_file(&atlas, "Path/To/Your/TTF_Font2.ttf", 16, 0); - const void* img = nk_font_atlas_bake(&atlas, &img_width, &img_height, NK_FONT_ATLAS_RGBA32); - nk_font_atlas_end(&atlas, nk_handle_id(texture), 0); - - struct nk_context ctx; - nk_init_default(&ctx, &font->handle); - while (1) { - - } - nk_font_atlas_clear(&atlas); - - The font baker API is probably the most complex API inside this library and - I would suggest reading some of my examples `example/` to get a grip on how - to use the font atlas. There are a number of details I left out. For example - how to merge fonts, configure a font with `nk_font_config` to use other languages, - use another texture coordinate format and a lot more: - - struct nk_font_config cfg = nk_font_config(font_pixel_height); - cfg.merge_mode = nk_false or nk_true; - cfg.range = nk_font_korean_glyph_ranges(); - cfg.coord_type = NK_COORD_PIXEL; - nk_font *font = nk_font_atlas_add_from_file(&atlas, "Path/To/Your/TTF_Font.ttf", 13, &cfg); - +/*/// ### Font +/// Font handling in this library was designed to be quite customizable and lets +/// you decide what you want to use and what you want to provide. There are three +/// different ways to use the font atlas. The first two will use your font +/// handling scheme and only requires essential data to run nuklear. The next +/// slightly more advanced features is font handling with vertex buffer output. +/// Finally the most complex API wise is using nuklear's font baking API. +// +/// #### Using your own implementation without vertex buffer output +/// +/// So first up the easiest way to do font handling is by just providing a +/// `nk_user_font` struct which only requires the height in pixel of the used +/// font and a callback to calculate the width of a string. This way of handling +/// fonts is best fitted for using the normal draw shape command API where you +/// do all the text drawing yourself and the library does not require any kind +/// of deeper knowledge about which font handling mechanism you use. +/// IMPORTANT: the `nk_user_font` pointer provided to nuklear has to persist +/// over the complete life time! I know this sucks but it is currently the only +/// way to switch between fonts. +/// +/// ```c +/// float your_text_width_calculation(nk_handle handle, float height, const char *text, int len) +/// { +/// your_font_type *type = handle.ptr; +/// float text_width = ...; +/// return text_width; +/// } +/// +/// struct nk_user_font font; +/// font.userdata.ptr = &your_font_class_or_struct; +/// font.height = your_font_height; +/// font.width = your_text_width_calculation; +/// +/// struct nk_context ctx; +/// nk_init_default(&ctx, &font); +/// ``` +/// #### Using your own implementation with vertex buffer output +/// +/// While the first approach works fine if you don't want to use the optional +/// vertex buffer output it is not enough if you do. To get font handling working +/// for these cases you have to provide two additional parameters inside the +/// `nk_user_font`. First a texture atlas handle used to draw text as subimages +/// of a bigger font atlas texture and a callback to query a character's glyph +/// information (offset, size, ...). So it is still possible to provide your own +/// font and use the vertex buffer output. +/// +/// ```c +/// float your_text_width_calculation(nk_handle handle, float height, const char *text, int len) +/// { +/// your_font_type *type = handle.ptr; +/// float text_width = ...; +/// return text_width; +/// } +/// void query_your_font_glyph(nk_handle handle, float font_height, struct nk_user_font_glyph *glyph, nk_rune codepoint, nk_rune next_codepoint) +/// { +/// your_font_type *type = handle.ptr; +/// glyph.width = ...; +/// glyph.height = ...; +/// glyph.xadvance = ...; +/// glyph.uv[0].x = ...; +/// glyph.uv[0].y = ...; +/// glyph.uv[1].x = ...; +/// glyph.uv[1].y = ...; +/// glyph.offset.x = ...; +/// glyph.offset.y = ...; +/// } +/// +/// struct nk_user_font font; +/// font.userdata.ptr = &your_font_class_or_struct; +/// font.height = your_font_height; +/// font.width = your_text_width_calculation; +/// font.query = query_your_font_glyph; +/// font.texture.id = your_font_texture; +/// +/// struct nk_context ctx; +/// nk_init_default(&ctx, &font); +/// ``` +/// +/// #### Nuklear font baker +/// +/// The final approach if you do not have a font handling functionality or don't +/// want to use it in this library is by using the optional font baker. +/// The font baker APIs can be used to create a font plus font atlas texture +/// and can be used with or without the vertex buffer output. +/// +/// It still uses the `nk_user_font` struct and the two different approaches +/// previously stated still work. The font baker is not located inside +/// `nk_context` like all other systems since it can be understood as more of +/// an extension to nuklear and does not really depend on any `nk_context` state. +/// +/// Font baker need to be initialized first by one of the nk_font_atlas_init_xxx +/// functions. If you don't care about memory just call the default version +/// `nk_font_atlas_init_default` which will allocate all memory from the standard library. +/// If you want to control memory allocation but you don't care if the allocated +/// memory is temporary and therefore can be freed directly after the baking process +/// is over or permanent you can call `nk_font_atlas_init`. +/// +/// After successfully initializing the font baker you can add Truetype(.ttf) fonts from +/// different sources like memory or from file by calling one of the `nk_font_atlas_add_xxx`. +/// functions. Adding font will permanently store each font, font config and ttf memory block(!) +/// inside the font atlas and allows to reuse the font atlas. If you don't want to reuse +/// the font baker by for example adding additional fonts you can call +/// `nk_font_atlas_cleanup` after the baking process is over (after calling nk_font_atlas_end). +/// +/// As soon as you added all fonts you wanted you can now start the baking process +/// for every selected glyph to image by calling `nk_font_atlas_bake`. +/// The baking process returns image memory, width and height which can be used to +/// either create your own image object or upload it to any graphics library. +/// No matter which case you finally have to call `nk_font_atlas_end` which +/// will free all temporary memory including the font atlas image so make sure +/// you created our texture beforehand. `nk_font_atlas_end` requires a handle +/// to your font texture or object and optionally fills a `struct nk_draw_null_texture` +/// which can be used for the optional vertex output. If you don't want it just +/// set the argument to `NULL`. +/// +/// At this point you are done and if you don't want to reuse the font atlas you +/// can call `nk_font_atlas_cleanup` to free all truetype blobs and configuration +/// memory. Finally if you don't use the font atlas and any of it's fonts anymore +/// you need to call `nk_font_atlas_clear` to free all memory still being used. +/// +/// ```c +/// struct nk_font_atlas atlas; +/// nk_font_atlas_init_default(&atlas); +/// nk_font_atlas_begin(&atlas); +/// nk_font *font = nk_font_atlas_add_from_file(&atlas, "Path/To/Your/TTF_Font.ttf", 13, 0); +/// nk_font *font2 = nk_font_atlas_add_from_file(&atlas, "Path/To/Your/TTF_Font2.ttf", 16, 0); +/// const void* img = nk_font_atlas_bake(&atlas, &img_width, &img_height, NK_FONT_ATLAS_RGBA32); +/// nk_font_atlas_end(&atlas, nk_handle_id(texture), 0); +/// +/// struct nk_context ctx; +/// nk_init_default(&ctx, &font->handle); +/// while (1) { +/// +/// } +/// nk_font_atlas_clear(&atlas); +/// ``` +/// The font baker API is probably the most complex API inside this library and +/// I would suggest reading some of my examples `example/` to get a grip on how +/// to use the font atlas. There are a number of details I left out. For example +/// how to merge fonts, configure a font with `nk_font_config` to use other languages, +/// use another texture coordinate format and a lot more: +/// +/// ```c +/// struct nk_font_config cfg = nk_font_config(font_pixel_height); +/// cfg.merge_mode = nk_false or nk_true; +/// cfg.range = nk_font_korean_glyph_ranges(); +/// cfg.coord_type = NK_COORD_PIXEL; +/// nk_font *font = nk_font_atlas_add_from_file(&atlas, "Path/To/Your/TTF_Font.ttf", 13, &cfg); +/// ``` */ struct nk_user_font_glyph; typedef float(*nk_text_width_f)(nk_handle, float h, const char*, int len); @@ -3889,33 +3895,34 @@ NK_API void nk_font_atlas_clear(struct nk_font_atlas*); * MEMORY BUFFER * * ===============================================================*/ -/* A basic (double)-buffer with linear allocation and resetting as only - freeing policy. The buffer's main purpose is to control all memory management - inside the GUI toolkit and still leave memory control as much as possible in - the hand of the user while also making sure the library is easy to use if - not as much control is needed. - In general all memory inside this library can be provided from the user in - three different ways. - - The first way and the one providing most control is by just passing a fixed - size memory block. In this case all control lies in the hand of the user - since he can exactly control where the memory comes from and how much memory - the library should consume. Of course using the fixed size API removes the - ability to automatically resize a buffer if not enough memory is provided so - you have to take over the resizing. While being a fixed sized buffer sounds - quite limiting, it is very effective in this library since the actual memory - consumption is quite stable and has a fixed upper bound for a lot of cases. - - If you don't want to think about how much memory the library should allocate - at all time or have a very dynamic UI with unpredictable memory consumption - habits but still want control over memory allocation you can use the dynamic - allocator based API. The allocator consists of two callbacks for allocating - and freeing memory and optional userdata so you can plugin your own allocator. - - The final and easiest way can be used by defining - NK_INCLUDE_DEFAULT_ALLOCATOR which uses the standard library memory - allocation functions malloc and free and takes over complete control over - memory in this library. +/*/// ### Memory Buffer +/// A basic (double)-buffer with linear allocation and resetting as only +/// freeing policy. The buffer's main purpose is to control all memory management +/// inside the GUI toolkit and still leave memory control as much as possible in +/// the hand of the user while also making sure the library is easy to use if +/// not as much control is needed. +/// In general all memory inside this library can be provided from the user in +/// three different ways. +/// +/// The first way and the one providing most control is by just passing a fixed +/// size memory block. In this case all control lies in the hand of the user +/// since he can exactly control where the memory comes from and how much memory +/// the library should consume. Of course using the fixed size API removes the +/// ability to automatically resize a buffer if not enough memory is provided so +/// you have to take over the resizing. While being a fixed sized buffer sounds +/// quite limiting, it is very effective in this library since the actual memory +/// consumption is quite stable and has a fixed upper bound for a lot of cases. +/// +/// If you don't want to think about how much memory the library should allocate +/// at all time or have a very dynamic UI with unpredictable memory consumption +/// habits but still want control over memory allocation you can use the dynamic +/// allocator based API. The allocator consists of two callbacks for allocating +/// and freeing memory and optional userdata so you can plugin your own allocator. +/// +/// The final and easiest way can be used by defining +/// NK_INCLUDE_DEFAULT_ALLOCATOR which uses the standard library memory +/// allocation functions malloc and free and takes over complete control over +/// memory in this library. */ struct nk_memory_status { void *memory; @@ -4040,28 +4047,29 @@ NK_API int nk_str_len_char(struct nk_str*); * TEXT EDITOR * * ===============================================================*/ -/* Editing text in this library is handled by either `nk_edit_string` or - * `nk_edit_buffer`. But like almost everything in this library there are multiple - * ways of doing it and a balance between control and ease of use with memory - * as well as functionality controlled by flags. - * - * This library generally allows three different levels of memory control: - * First of is the most basic way of just providing a simple char array with - * string length. This method is probably the easiest way of handling simple - * user text input. Main upside is complete control over memory while the biggest - * downside in comparison with the other two approaches is missing undo/redo. - * - * For UIs that require undo/redo the second way was created. It is based on - * a fixed size nk_text_edit struct, which has an internal undo/redo stack. - * This is mainly useful if you want something more like a text editor but don't want - * to have a dynamically growing buffer. - * - * The final way is using a dynamically growing nk_text_edit struct, which - * has both a default version if you don't care where memory comes from and an - * allocator version if you do. While the text editor is quite powerful for its - * complexity I would not recommend editing gigabytes of data with it. - * It is rather designed for uses cases which make sense for a GUI library not for - * an full blown text editor. +/*/// ### Text Editor +/// Editing text in this library is handled by either `nk_edit_string` or +/// `nk_edit_buffer`. But like almost everything in this library there are multiple +/// ways of doing it and a balance between control and ease of use with memory +/// as well as functionality controlled by flags. +/// +/// This library generally allows three different levels of memory control: +/// First of is the most basic way of just providing a simple char array with +/// string length. This method is probably the easiest way of handling simple +/// user text input. Main upside is complete control over memory while the biggest +/// downside in comparison with the other two approaches is missing undo/redo. +/// +/// For UIs that require undo/redo the second way was created. It is based on +/// a fixed size nk_text_edit struct, which has an internal undo/redo stack. +/// This is mainly useful if you want something more like a text editor but don't want +/// to have a dynamically growing buffer. +/// +/// The final way is using a dynamically growing nk_text_edit struct, which +/// has both a default version if you don't care where memory comes from and an +/// allocator version if you do. While the text editor is quite powerful for its +/// complexity I would not recommend editing gigabytes of data with it. +/// It is rather designed for uses cases which make sense for a GUI library not for +/// an full blown text editor. */ #ifndef NK_TEXTEDIT_UNDOSTATECOUNT #define NK_TEXTEDIT_UNDOSTATECOUNT 99 @@ -4155,49 +4163,52 @@ NK_API void nk_textedit_redo(struct nk_text_edit*); * DRAWING * * ===============================================================*/ -/* This library was designed to be render backend agnostic so it does - not draw anything to screen. Instead all drawn shapes, widgets - are made of, are buffered into memory and make up a command queue. - Each frame therefore fills the command buffer with draw commands - that then need to be executed by the user and his own render backend. - After that the command buffer needs to be cleared and a new frame can be - started. It is probably important to note that the command buffer is the main - drawing API and the optional vertex buffer API only takes this format and - converts it into a hardware accessible format. - - To use the command queue to draw your own widgets you can access the - command buffer of each window by calling `nk_window_get_canvas` after - previously having called `nk_begin`: - - void draw_red_rectangle_widget(struct nk_context *ctx) - { - struct nk_command_buffer *canvas; - struct nk_input *input = &ctx->input; - canvas = nk_window_get_canvas(ctx); - - struct nk_rect space; - enum nk_widget_layout_states state; - state = nk_widget(&space, ctx); - if (!state) return; - - if (state != NK_WIDGET_ROM) - update_your_widget_by_user_input(...); - nk_fill_rect(canvas, space, 0, nk_rgb(255,0,0)); - } - - if (nk_begin(...)) { - nk_layout_row_dynamic(ctx, 25, 1); - draw_red_rectangle_widget(ctx); - } - nk_end(..) - - Important to know if you want to create your own widgets is the `nk_widget` - call. It allocates space on the panel reserved for this widget to be used, - but also returns the state of the widget space. If your widget is not seen and does - not have to be updated it is '0' and you can just return. If it only has - to be drawn the state will be `NK_WIDGET_ROM` otherwise you can do both - update and draw your widget. The reason for separating is to only draw and - update what is actually necessary which is crucial for performance. +/*/// ### Drawing +/// This library was designed to be render backend agnostic so it does +/// not draw anything to screen. Instead all drawn shapes, widgets +/// are made of, are buffered into memory and make up a command queue. +/// Each frame therefore fills the command buffer with draw commands +/// that then need to be executed by the user and his own render backend. +/// After that the command buffer needs to be cleared and a new frame can be +/// started. It is probably important to note that the command buffer is the main +/// drawing API and the optional vertex buffer API only takes this format and +/// converts it into a hardware accessible format. +/// +/// To use the command queue to draw your own widgets you can access the +/// command buffer of each window by calling `nk_window_get_canvas` after +/// previously having called `nk_begin`: +/// +/// ```c +/// void draw_red_rectangle_widget(struct nk_context *ctx) +/// { +/// struct nk_command_buffer *canvas; +/// struct nk_input *input = &ctx->input; +/// canvas = nk_window_get_canvas(ctx); +/// +/// struct nk_rect space; +/// enum nk_widget_layout_states state; +/// state = nk_widget(&space, ctx); +/// if (!state) return; +/// +/// if (state != NK_WIDGET_ROM) +/// update_your_widget_by_user_input(...); +/// nk_fill_rect(canvas, space, 0, nk_rgb(255,0,0)); +/// } +/// +/// if (nk_begin(...)) { +/// nk_layout_row_dynamic(ctx, 25, 1); +/// draw_red_rectangle_widget(ctx); +/// } +/// nk_end(..) +/// +/// ``` +/// Important to know if you want to create your own widgets is the `nk_widget` +/// call. It allocates space on the panel reserved for this widget to be used, +/// but also returns the state of the widget space. If your widget is not seen and does +/// not have to be updated it is '0' and you can just return. If it only has +/// to be drawn the state will be `NK_WIDGET_ROM` otherwise you can do both +/// update and draw your widget. The reason for separating is to only draw and +/// update what is actually necessary which is crucial for performance. */ enum nk_command_type { NK_COMMAND_NOP, @@ -4482,18 +4493,19 @@ NK_API nk_bool nk_input_is_key_down(const struct nk_input*, enum nk_keys); * * ===============================================================*/ #ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT -/* The optional vertex buffer draw list provides a 2D drawing context - with antialiasing functionality which takes basic filled or outlined shapes - or a path and outputs vertexes, elements and draw commands. - The actual draw list API is not required to be used directly while using this - library since converting the default library draw command output is done by - just calling `nk_convert` but I decided to still make this library accessible - since it can be useful. - - The draw list is based on a path buffering and polygon and polyline - rendering API which allows a lot of ways to draw 2D content to screen. - In fact it is probably more powerful than needed but allows even more crazy - things than this library provides by default. +/* ### Draw List +/// The optional vertex buffer draw list provides a 2D drawing context +/// with antialiasing functionality which takes basic filled or outlined shapes +/// or a path and outputs vertexes, elements and draw commands. +/// The actual draw list API is not required to be used directly while using this +/// library since converting the default library draw command output is done by +/// just calling `nk_convert` but I decided to still make this library accessible +/// since it can be useful. +/// +/// The draw list is based on a path buffering and polygon and polyline +/// rendering API which allows a lot of ways to draw 2D content to screen. +/// In fact it is probably more powerful than needed but allows even more crazy +/// things than this library provides by default. */ #ifdef NK_UINT_DRAW_INDEX typedef nk_uint nk_draw_index; @@ -5271,27 +5283,28 @@ struct nk_window { /*============================================================== * STACK * =============================================================*/ -/* The style modifier stack can be used to temporarily change a - * property inside `nk_style`. For example if you want a special - * red button you can temporarily push the old button color onto a stack - * draw the button with a red color and then you just pop the old color - * back from the stack: - * - * nk_style_push_style_item(ctx, &ctx->style.button.normal, nk_style_item_color(nk_rgb(255,0,0))); - * nk_style_push_style_item(ctx, &ctx->style.button.hover, nk_style_item_color(nk_rgb(255,0,0))); - * nk_style_push_style_item(ctx, &ctx->style.button.active, nk_style_item_color(nk_rgb(255,0,0))); - * nk_style_push_vec2(ctx, &cx->style.button.padding, nk_vec2(2,2)); - * - * nk_button(...); - * - * nk_style_pop_style_item(ctx); - * nk_style_pop_style_item(ctx); - * nk_style_pop_style_item(ctx); - * nk_style_pop_vec2(ctx); - * - * Nuklear has a stack for style_items, float properties, vector properties, - * flags, colors, fonts and for button_behavior. Each has it's own fixed size stack - * which can be changed at compile time. +/*/// ### Stack +/// The style modifier stack can be used to temporarily change a +/// property inside `nk_style`. For example if you want a special +/// red button you can temporarily push the old button color onto a stack +/// draw the button with a red color and then you just pop the old color +/// back from the stack: +/// +/// nk_style_push_style_item(ctx, &ctx->style.button.normal, nk_style_item_color(nk_rgb(255,0,0))); +/// nk_style_push_style_item(ctx, &ctx->style.button.hover, nk_style_item_color(nk_rgb(255,0,0))); +/// nk_style_push_style_item(ctx, &ctx->style.button.active, nk_style_item_color(nk_rgb(255,0,0))); +/// nk_style_push_vec2(ctx, &cx->style.button.padding, nk_vec2(2,2)); +/// +/// nk_button(...); +/// +/// nk_style_pop_style_item(ctx); +/// nk_style_pop_style_item(ctx); +/// nk_style_pop_style_item(ctx); +/// nk_style_pop_vec2(ctx); +/// +/// Nuklear has a stack for style_items, float properties, vector properties, +/// flags, colors, fonts and for button_behavior. Each has it's own fixed size stack +/// which can be changed at compile time. */ #ifndef NK_BUTTON_BEHAVIOR_STACK_SIZE #define NK_BUTTON_BEHAVIOR_STACK_SIZE 8 diff --git a/src/nuklear_math.c b/src/nuklear_math.c index c288a0b..672fd81 100644 --- a/src/nuklear_math.c +++ b/src/nuklear_math.c @@ -6,32 +6,33 @@ * MATH * * ===============================================================*/ -/* Since nuklear is supposed to work on all systems providing floating point - math without any dependencies I also had to implement my own math functions - for sqrt, sin and cos. Since the actual highly accurate implementations for - the standard library functions are quite complex and I do not need high - precision for my use cases I use approximations. - - Sqrt - ---- - For square root nuklear uses the famous fast inverse square root: - https://en.wikipedia.org/wiki/Fast_inverse_square_root with - slightly tweaked magic constant. While on today's hardware it is - probably not faster it is still fast and accurate enough for - nuklear's use cases. IMPORTANT: this requires float format IEEE 754 - - Sine/Cosine - ----------- - All constants inside both function are generated Remez's minimax - approximations for value range 0...2*PI. The reason why I decided to - approximate exactly that range is that nuklear only needs sine and - cosine to generate circles which only requires that exact range. - In addition I used Remez instead of Taylor for additional precision: - www.lolengine.net/blog/2011/12/21/better-function-approximations. - - The tool I used to generate constants for both sine and cosine - (it can actually approximate a lot more functions) can be - found here: www.lolengine.net/wiki/oss/lolremez +/*/// ### Math +/// Since nuklear is supposed to work on all systems providing floating point +/// math without any dependencies I also had to implement my own math functions +/// for sqrt, sin and cos. Since the actual highly accurate implementations for +/// the standard library functions are quite complex and I do not need high +/// precision for my use cases I use approximations. +/// +/// Sqrt +/// ---- +/// For square root nuklear uses the famous fast inverse square root: +/// https://en.wikipedia.org/wiki/Fast_inverse_square_root with +/// slightly tweaked magic constant. While on today's hardware it is +/// probably not faster it is still fast and accurate enough for +/// nuklear's use cases. IMPORTANT: this requires float format IEEE 754 +/// +/// Sine/Cosine +/// ----------- +/// All constants inside both function are generated Remez's minimax +/// approximations for value range 0...2*PI. The reason why I decided to +/// approximate exactly that range is that nuklear only needs sine and +/// cosine to generate circles which only requires that exact range. +/// In addition I used Remez instead of Taylor for additional precision: +/// www.lolengine.net/blog/2011/12/21/better-function-approximations. +/// +/// The tool I used to generate constants for both sine and cosine +/// (it can actually approximate a lot more functions) can be +/// found here: www.lolengine.net/wiki/oss/lolremez */ #ifndef NK_INV_SQRT #define NK_INV_SQRT nk_inv_sqrt From 892a5cb7ca47bd1e337383541a91f441e26b87c4 Mon Sep 17 00:00:00 2001 From: vabenil Date: Fri, 17 Feb 2023 15:53:55 +0200 Subject: [PATCH 033/106] fix variable name in docs --- nuklear.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nuklear.h b/nuklear.h index febee39..2339d57 100644 --- a/nuklear.h +++ b/nuklear.h @@ -2153,7 +2153,7 @@ NK_API void nk_window_show_if(struct nk_context*, const char *name, enum nk_show /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c /// if (nk_begin_xxx(...) { /// // two rows with height: 30 composed of two widgets with width 60 and 40 -/// const float size[] = {60,40}; +/// const float ratio[] = {60,40}; /// nk_layout_row(ctx, NK_STATIC, 30, 2, ratio); /// nk_widget(...); /// nk_widget(...); From f0e776031b47309f4e05815f83d2a0f9e279e4ad Mon Sep 17 00:00:00 2001 From: vabenil Date: Mon, 20 Feb 2023 18:59:43 +0200 Subject: [PATCH 034/106] Fix docs variable name in source --- src/nuklear.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/nuklear.h b/src/nuklear.h index 2d4af9d..dac6ca0 100644 --- a/src/nuklear.h +++ b/src/nuklear.h @@ -1932,7 +1932,7 @@ NK_API void nk_window_show_if(struct nk_context*, const char *name, enum nk_show /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c /// if (nk_begin_xxx(...) { /// // two rows with height: 30 composed of two widgets with width 60 and 40 -/// const float size[] = {60,40}; +/// const float ratio[] = {60,40}; /// nk_layout_row(ctx, NK_STATIC, 30, 2, ratio); /// nk_widget(...); /// nk_widget(...); From c09e3b36f8c80f06386e3bad09890d6ab47fa9df Mon Sep 17 00:00:00 2001 From: Andrew Kravchuk Date: Wed, 1 Mar 2023 18:53:02 +0100 Subject: [PATCH 035/106] demo/allegro5: minor string-related tweaks --- demo/allegro5/nuklear_allegro5.h | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/demo/allegro5/nuklear_allegro5.h b/demo/allegro5/nuklear_allegro5.h index 8e10c9b..0e980c7 100644 --- a/demo/allegro5/nuklear_allegro5.h +++ b/demo/allegro5/nuklear_allegro5.h @@ -101,7 +101,7 @@ static float nk_allegro5_font_get_text_width(nk_handle handle, float height, const char *text, int len) { float width; - char *strcpy; + char *str; NkAllegro5Font *font = (NkAllegro5Font*)handle.ptr; NK_UNUSED(height); if (!font || !text) { @@ -111,11 +111,11 @@ nk_allegro5_font_get_text_width(nk_handle handle, float height, const char *text as nuklear uses variable size buffers and al_get_text_width doesn't accept a length, it infers length from null-termination (which is unsafe API design by allegro devs!) */ - strcpy = malloc(len + 1); - strncpy(strcpy, text, len); - strcpy[len] = '\0'; - width = al_get_text_width(font->font, strcpy); - free(strcpy); + str = calloc((size_t)len + 1, 1); + if(!str) return 0; + strncpy(str, text, len); + width = al_get_text_width(font->font, str); + free(str); return width; } @@ -473,10 +473,9 @@ nk_allegro5_clipboard_copy(nk_handle usr, const char *text, int len) char *str = 0; (void)usr; if (!len) return; - str = (char*)malloc((size_t)len+1); + str = calloc((size_t)len + 1, 1); if (!str) return; - memcpy(str, text, (size_t)len); - str[len] = '\0'; + strncpy(str, text, len); al_set_clipboard_text(allegro5.dsp, str); free(str); } From fa4ed560dded62d14547ce11eb3523babd0bdd3b Mon Sep 17 00:00:00 2001 From: Richard Gill Date: Fri, 28 Apr 2023 21:58:43 +0200 Subject: [PATCH 036/106] Delete index.html removed that one as it has no purpose (empty anyway) --- index.html | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 index.html diff --git a/index.html b/index.html deleted file mode 100644 index e69de29..0000000 From 77490e155cd7bba8e0b7c05fe2af07b5410c098a Mon Sep 17 00:00:00 2001 From: Richard Gill Date: Tue, 16 May 2023 09:21:51 +0200 Subject: [PATCH 037/106] fixed titlebar options in overview demo --- demo/common/overview.c | 37 +++++++++++++------------------------ 1 file changed, 13 insertions(+), 24 deletions(-) diff --git a/demo/common/overview.c b/demo/common/overview.c index b696011..86cb9f2 100644 --- a/demo/common/overview.c +++ b/demo/common/overview.c @@ -3,30 +3,19 @@ overview(struct nk_context *ctx) { /* window flags */ static int show_menu = nk_true; - static int titlebar = nk_true; - static int border = nk_true; - static int resize = nk_true; - static int movable = nk_true; - static int no_scrollbar = nk_false; - static int scale_left = nk_false; - static nk_flags window_flags = 0; - static int minimizable = nk_true; + static nk_flags window_flags = NK_WINDOW_TITLE|NK_WINDOW_BORDER|NK_WINDOW_SCALABLE|NK_WINDOW_MOVABLE|NK_WINDOW_MINIMIZABLE; + nk_flags actual_window_flags; /* popups */ static enum nk_style_header_align header_align = NK_HEADER_RIGHT; static int show_app_about = nk_false; - /* window flags */ - window_flags = 0; ctx->style.window.header.align = header_align; - if (border) window_flags |= NK_WINDOW_BORDER; - if (resize) window_flags |= NK_WINDOW_SCALABLE; - if (movable) window_flags |= NK_WINDOW_MOVABLE; - if (no_scrollbar) window_flags |= NK_WINDOW_NO_SCROLLBAR; - if (scale_left) window_flags |= NK_WINDOW_SCALE_LEFT; - if (minimizable) window_flags |= NK_WINDOW_MINIMIZABLE; - if (nk_begin(ctx, "Overview", nk_rect(10, 10, 400, 600), window_flags)) + actual_window_flags = window_flags; + if (!(actual_window_flags & NK_WINDOW_TITLE)) + actual_window_flags &= ~(NK_WINDOW_MINIMIZABLE|NK_WINDOW_CLOSABLE); + if (nk_begin(ctx, "Overview", nk_rect(10, 10, 400, 600), actual_window_flags)) { if (show_menu) { @@ -132,14 +121,14 @@ overview(struct nk_context *ctx) /* window flags */ if (nk_tree_push(ctx, NK_TREE_TAB, "Window", NK_MINIMIZED)) { nk_layout_row_dynamic(ctx, 30, 2); - nk_checkbox_label(ctx, "Titlebar", &titlebar); nk_checkbox_label(ctx, "Menu", &show_menu); - nk_checkbox_label(ctx, "Border", &border); - nk_checkbox_label(ctx, "Resizable", &resize); - nk_checkbox_label(ctx, "Movable", &movable); - nk_checkbox_label(ctx, "No Scrollbar", &no_scrollbar); - nk_checkbox_label(ctx, "Minimizable", &minimizable); - nk_checkbox_label(ctx, "Scale Left", &scale_left); + nk_checkbox_flags_label(ctx, "Titlebar", &window_flags, NK_WINDOW_TITLE); + nk_checkbox_flags_label(ctx, "Border", &window_flags, NK_WINDOW_BORDER); + nk_checkbox_flags_label(ctx, "Resizable", &window_flags, NK_WINDOW_SCALABLE); + nk_checkbox_flags_label(ctx, "Movable", &window_flags, NK_WINDOW_MOVABLE); + nk_checkbox_flags_label(ctx, "No Scrollbar", &window_flags, NK_WINDOW_NO_SCROLLBAR); + nk_checkbox_flags_label(ctx, "Minimizable", &window_flags, NK_WINDOW_MINIMIZABLE); + nk_checkbox_flags_label(ctx, "Scale Left", &window_flags, NK_WINDOW_SCALE_LEFT); nk_tree_pop(ctx); } From e48dd2144fdc21a5a1aca049412c14fce60634b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wladislav=20=E3=83=B4=E3=83=A9=E3=83=89=20Artsimovich?= Date: Mon, 26 Jun 2023 19:30:45 +0900 Subject: [PATCH 038/106] Fix Click-Drag for touch events. --- src/nuklear_input.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/nuklear_input.c b/src/nuklear_input.c index e438581..49d878b 100644 --- a/src/nuklear_input.c +++ b/src/nuklear_input.c @@ -83,6 +83,10 @@ nk_input_button(struct nk_context *ctx, enum nk_buttons id, int x, int y, nk_boo btn->clicked_pos.y = (float)y; btn->down = down; btn->clicked++; + + /* Fix Click-Drag for touch events. */ + in->mouse.delta.x = 0; + in->mouse.delta.y = 0; #ifdef NK_BUTTON_TRIGGER_ON_RELEASE if (down == 1 && id == NK_BUTTON_LEFT) { From 71bc457d39f7bea871995d9cfb32b6b69c7ca322 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wladislav=20=E3=83=B4=E3=83=A9=E3=83=89=20Artsimovich?= Date: Mon, 26 Jun 2023 19:37:51 +0900 Subject: [PATCH 039/106] Update nuklear.h --- nuklear.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/nuklear.h b/nuklear.h index b06753f..e4afef4 100644 --- a/nuklear.h +++ b/nuklear.h @@ -17898,6 +17898,10 @@ nk_input_button(struct nk_context *ctx, enum nk_buttons id, int x, int y, nk_boo btn->clicked_pos.y = (float)y; btn->down = down; btn->clicked++; + + /* Fix Click-Drag for touch events. */ + in->mouse.delta.x = 0; + in->mouse.delta.y = 0; #ifdef NK_BUTTON_TRIGGER_ON_RELEASE if (down == 1 && id == NK_BUTTON_LEFT) { From 4848a032825cce7144b53da090c00bde61c2bba5 Mon Sep 17 00:00:00 2001 From: Rob Loach Date: Sun, 9 Jul 2023 22:17:11 -0400 Subject: [PATCH 040/106] Remove doc binary --- doc/doc | Bin 33632 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100755 doc/doc diff --git a/doc/doc b/doc/doc deleted file mode 100755 index 906b2cc19faa9e40ab935b2e401968269fa40f9e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 33632 zcmeI5eQZ-z6u{4GhrocXz#IcLJdCV}v=#Xjw$ZUIFcCJ#j8%+}(!Q?G^=o~vj(zBg z2IB`1j3kiw1tvsCkO&$i0kyv`%h>1~{CJ_8%i3uofGU_?+y>49*3DG~#Nlx!M z=bn4sxxd%`d2hcN=({!^KmZgA>O@pA4`4HhXaP(`U5P45^_44Xo~UW4qv%M{7mo~G z=TV)PFj0~kYdno3r}g#jkufm+Q5Yu0mUNLMP2Q-P4i35XQf0vfhzpMt}5X)YW2ID8w`Q&JHr(cy07qSN zMk@wMscjpoBsE2|Uc(LRWw?RcSdU9}xeY%v@00?=-?N8n*Q~0kuFZT$k~w{$PqLnx zL7{$3l)673AW8kvTc&-^GyPrYQ!m7(1obrfV{qKK37{Uwai}zA3+0khuQ!rw}t%ZliYzyeFR@9u@y~U`1+B1Vx?NT;q3=7CZY(H;Qo_%jlQd%=FzwyByNb}n~fU&;nO z2}*IG`X`eHpLNfC(@GCcp%k025#WOn?b60Vco%m;e)C0!)AjFaajO1egF5U;<2l2`~XB zzyz286JP>NfC(^xAp!$UN4x)&gzi5cvvgmsvvv=5?YQv%H2ZG(D>KSjBdjNEl(L$YD8qZ;d0Vg2R!oXYNjrW5a{tkRjO zI5!2g7?sxEUJRa+ykx^@fFg>~+=HWGB0UF>52hO_e;>|weFiP5e0O^CTG{T#~MW~`@YQXcJ%@~&Xs zDa<=(ffkBUt@RcU_Ept>Wy;QJlye;C@vP{FwtRO#Sf-!R?Sd?OQkGq8*kxf^^NPNp zH?GQBxjmr;9E!gRn6s%DgLO>=~LBZ zR8{rGm6%qM$*PNKN;IODcW6=HT6)Y9dsy}>iLm|IrDZNN8Omlj9O7!~4+}359gYgK zj;O|cx71DMxz4Z>aXw8g4L`*=AABbml0DK{Upfnn=b&}Or!&Ok@eHs{KT!<$ zvjFo5wk;{(9G>h=8fS%VN#l66Eomg!l5_?iC8>Y%2NPfdOn?b60Vco%m;e)C0!)Aj zFaajO1egF5U;<2l2`~XBzyz286JP>NfC(@GCcp%k025#WOn?b60Vco%m;e)C0!)Aj zFaajO1egF5U;<2l2`~XBzyz286JP>NfC(@GCh)%#5V2xCY7mwF>)f~t01XuLf&ks7 z{}RuLZo4ttorxIh1iU~%C`O%wikDaj)u>clk|b60E0LIKMH3pD0XZ4~sY%v+AjJ~q zr%ELS3C8M|5m=;fP?9&wzJw-ALD}n<<1i}hRU$Cc3aK{p@fm}b6bg9L1Pbi~TS4Er z6M=lXD*;C`b)o+|&-Ul$_=|G<@*KY^$0uHNR|0XwyFm2+UZ=Yha^oUmxPD)fzOP$F zh2@82;OzJm?r1v(GJ7n-7`>HFuwWM!y`?8{-eWEr3$W?5Xwm cD(caGJlWe?d+q9$FFv`jZTDB7Tb9=T4GB_2tpET3 From 351e5d7296ed83e1b95a18138d1a3e5ee74660e0 Mon Sep 17 00:00:00 2001 From: Rob Loach Date: Sun, 9 Jul 2023 22:18:20 -0400 Subject: [PATCH 041/106] doc: Add clean up, and git ignore the binary --- .gitignore | 1 + doc/Makefile | 8 +++++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index 65a3136..e0495a0 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ example/bin/* docs/xml docs/build docs/src +doc/doc* *.tmp *.swo *.swp diff --git a/doc/Makefile b/doc/Makefile index 72a598b..967bd8f 100644 --- a/doc/Makefile +++ b/doc/Makefile @@ -13,12 +13,14 @@ LIBS = else UNAME_S := $(shell uname -s) ifeq ($(UNAME_S),Darwin) - LIBS = + LIBS = else LIBS = endif endif -$(BIN): - rm -f $(BIN) $(OBJS) +$(BIN): clean $(CC) $(SRC) $(CFLAGS) -o $(BIN) + +clean: + rm -f $(BIN) $(OBJS) From 24ceaad002d2e477dad68362a8798b5afd720f73 Mon Sep 17 00:00:00 2001 From: nyaruku <38096703+nyaruku@users.noreply.github.com> Date: Wed, 6 Sep 2023 04:47:25 +0300 Subject: [PATCH 042/106] Add files via upload --- demo/gdi/nuklear_gdi.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/demo/gdi/nuklear_gdi.h b/demo/gdi/nuklear_gdi.h index 8efc8da..ecab260 100644 --- a/demo/gdi/nuklear_gdi.h +++ b/demo/gdi/nuklear_gdi.h @@ -516,6 +516,7 @@ static void nk_gdi_draw_text(HDC dc, short x, short y, unsigned short w, unsigned short h, const char *text, int len, GdiFont *font, struct nk_color cbg, struct nk_color cfg) { + int wsize; WCHAR* wstr; @@ -524,8 +525,8 @@ nk_gdi_draw_text(HDC dc, short x, short y, unsigned short w, unsigned short h, wsize = MultiByteToWideChar(CP_UTF8, 0, text, len, NULL, 0); wstr = (WCHAR*)_alloca(wsize * sizeof(wchar_t)); MultiByteToWideChar(CP_UTF8, 0, text, len, wstr, wsize); - - SetBkColor(dc, convert_color(cbg)); + // Transparent Text Background + SetBkMode(dc, TRANSPARENT); SetTextColor(dc, convert_color(cfg)); SelectObject(dc, font->handle); From 1aae7b555ab400f0017fbd4da8811e9354203023 Mon Sep 17 00:00:00 2001 From: nyaruku <38096703+nyaruku@users.noreply.github.com> Date: Wed, 6 Sep 2023 05:00:45 +0300 Subject: [PATCH 043/106] Update nuklear_gdi.h --- demo/gdi/nuklear_gdi.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/demo/gdi/nuklear_gdi.h b/demo/gdi/nuklear_gdi.h index ecab260..4f52cb2 100644 --- a/demo/gdi/nuklear_gdi.h +++ b/demo/gdi/nuklear_gdi.h @@ -516,7 +516,6 @@ static void nk_gdi_draw_text(HDC dc, short x, short y, unsigned short w, unsigned short h, const char *text, int len, GdiFont *font, struct nk_color cbg, struct nk_color cfg) { - int wsize; WCHAR* wstr; @@ -525,8 +524,9 @@ nk_gdi_draw_text(HDC dc, short x, short y, unsigned short w, unsigned short h, wsize = MultiByteToWideChar(CP_UTF8, 0, text, len, NULL, 0); wstr = (WCHAR*)_alloca(wsize * sizeof(wchar_t)); MultiByteToWideChar(CP_UTF8, 0, text, len, wstr, wsize); - // Transparent Text Background - SetBkMode(dc, TRANSPARENT); + + SetBkMode(dc, TRANSPARENT); // Transparent Text Background + SetBkColor(dc, convert_color(cbg)); SetTextColor(dc, convert_color(cfg)); SelectObject(dc, font->handle); From 0435477a914dc4a58e3e80dd5301314757a67749 Mon Sep 17 00:00:00 2001 From: nyaruku <38096703+nyaruku@users.noreply.github.com> Date: Fri, 8 Sep 2023 16:29:21 +0300 Subject: [PATCH 044/106] Fix Copy/Paste/Select All for Text Input --- demo/gdip/nuklear_gdip.h | 131 ++++++++++++++++----------------------- 1 file changed, 54 insertions(+), 77 deletions(-) diff --git a/demo/gdip/nuklear_gdip.h b/demo/gdip/nuklear_gdip.h index f83964d..c0dd5dd 100644 --- a/demo/gdip/nuklear_gdip.h +++ b/demo/gdip/nuklear_gdip.h @@ -761,7 +761,7 @@ nk_gdipfont_get_text_width(nk_handle handle, float height, const char *text, int (void)height; wsize = MultiByteToWideChar(CP_UTF8, 0, text, len, NULL, 0); - wstr = (WCHAR*)_alloca(wsize * sizeof(wchar_t)); + wstr = (WCHAR*)_malloca(wsize * sizeof(wchar_t)); MultiByteToWideChar(CP_UTF8, 0, text, len, wstr, wsize); GdipMeasureString(gdip.memory, wstr, wsize, font->handle, &layout, gdip.format, &bbox, NULL, NULL); @@ -777,93 +777,63 @@ nk_gdipfont_del(GdipFont *font) } static void -nk_gdip_clipboard_paste(nk_handle usr, struct nk_text_edit *edit) +nk_gdip_clipboard_paste(nk_handle usr, struct nk_text_edit* edit) { - HGLOBAL mem; - SIZE_T size; - LPCWSTR wstr; - int utf8size; - char* utf8; (void)usr; - - if (!IsClipboardFormatAvailable(CF_UNICODETEXT) && OpenClipboard(NULL)) - return; - - mem = (HGLOBAL)GetClipboardData(CF_UNICODETEXT); - if (!mem) { + if (IsClipboardFormatAvailable(CF_UNICODETEXT) && OpenClipboard(NULL)) + { + HGLOBAL mem = GetClipboardData(CF_UNICODETEXT); + if (mem) + { + SIZE_T size = GlobalSize(mem) - 1; + if (size) + { + LPCWSTR wstr = (LPCWSTR)GlobalLock(mem); + if (wstr) + { + int utf8size = WideCharToMultiByte(CP_UTF8, 0, wstr, (int)(size / sizeof(wchar_t)), NULL, 0, NULL, NULL); + if (utf8size) + { + char* utf8 = (char*)malloc(utf8size); + if (utf8) + { + WideCharToMultiByte(CP_UTF8, 0, wstr, (int)(size / sizeof(wchar_t)), utf8, utf8size, NULL, NULL); + nk_textedit_paste(edit, utf8, utf8size); + free(utf8); + } + } + GlobalUnlock(mem); + } + } + } CloseClipboard(); - return; } - - size = GlobalSize(mem) - 1; - if (!size) { - CloseClipboard(); - return; - } - - wstr = (LPCWSTR)GlobalLock(mem); - if (!wstr) { - CloseClipboard(); - return; - } - - utf8size = WideCharToMultiByte(CP_UTF8, 0, wstr, (int)(size / sizeof(wchar_t)), NULL, 0, NULL, NULL); - if (!utf8size) { - GlobalUnlock(mem); - CloseClipboard(); - return; - } - - utf8 = (char*)malloc(utf8size); - if (!utf8) { - GlobalUnlock(mem); - CloseClipboard(); - return; - } - - WideCharToMultiByte(CP_UTF8, 0, wstr, (int)(size / sizeof(wchar_t)), utf8, utf8size, NULL, NULL); - nk_textedit_paste(edit, utf8, utf8size); - free(utf8); - GlobalUnlock(mem); - CloseClipboard(); } static void -nk_gdip_clipboard_copy(nk_handle usr, const char *text, int len) +nk_gdip_clipboard_copy(nk_handle usr, const char* text, int len) { - HGLOBAL mem; - wchar_t* wstr; - int wsize; - (void)usr; + if (OpenClipboard(NULL)) + { + int wsize = MultiByteToWideChar(CP_UTF8, 0, text, len, NULL, 0); + if (wsize) + { + HGLOBAL mem = (HGLOBAL)GlobalAlloc(GMEM_MOVEABLE, (wsize + 1) * sizeof(wchar_t)); + if (mem) + { + wchar_t* wstr = (wchar_t*)GlobalLock(mem); + if (wstr) + { + MultiByteToWideChar(CP_UTF8, 0, text, len, wstr, wsize); + wstr[wsize] = 0; + GlobalUnlock(mem); - if (!OpenClipboard(NULL)) - return; - - wsize = MultiByteToWideChar(CP_UTF8, 0, text, len, NULL, 0); - if (!wsize) { + SetClipboardData(CF_UNICODETEXT, mem); + } + } + } CloseClipboard(); - return; } - - mem = (HGLOBAL)GlobalAlloc(GMEM_MOVEABLE, (wsize + 1) * sizeof(wchar_t)); - if (!mem) { - CloseClipboard(); - return; - } - - wstr = (wchar_t*)GlobalLock(mem); - if (!wstr) { - GlobalFree(mem); - CloseClipboard(); - return; - } - - MultiByteToWideChar(CP_UTF8, 0, text, len, wstr, wsize); - wstr[wsize] = 0; - GlobalUnlock(mem); - if (!SetClipboardData(CF_UNICODETEXT, mem)) - GlobalFree(mem); - CloseClipboard(); } NK_API struct nk_context* @@ -997,6 +967,13 @@ nk_gdip_handle_event(HWND wnd, UINT msg, WPARAM wparam, LPARAM lparam) nk_input_key(&gdip.ctx, NK_KEY_SCROLL_UP, down); return 1; + case 'A': + if (ctrl) { + nk_input_key(&gdip.ctx, NK_KEY_TEXT_SELECT_ALL, down); + return 1; + } + break; + case 'C': if (ctrl) { nk_input_key(&gdip.ctx, NK_KEY_COPY, down); From 036f8226bbbb5a4550ac1ba39b8e05e875b92b8c Mon Sep 17 00:00:00 2001 From: nyaruku <38096703+nyaruku@users.noreply.github.com> Date: Tue, 12 Sep 2023 18:47:27 +0300 Subject: [PATCH 045/106] Fixed Transparent Text Background for GDI Co-authored-by: Rob Loach --- demo/gdi/nuklear_gdi.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demo/gdi/nuklear_gdi.h b/demo/gdi/nuklear_gdi.h index 4f52cb2..6bbedb6 100644 --- a/demo/gdi/nuklear_gdi.h +++ b/demo/gdi/nuklear_gdi.h @@ -525,7 +525,7 @@ nk_gdi_draw_text(HDC dc, short x, short y, unsigned short w, unsigned short h, wstr = (WCHAR*)_alloca(wsize * sizeof(wchar_t)); MultiByteToWideChar(CP_UTF8, 0, text, len, wstr, wsize); - SetBkMode(dc, TRANSPARENT); // Transparent Text Background + SetBkMode(dc, TRANSPARENT); /* Transparent Text Background */ SetBkColor(dc, convert_color(cbg)); SetTextColor(dc, convert_color(cfg)); From 83df3367b4d80330a629dfdc0b33f1df1554ae20 Mon Sep 17 00:00:00 2001 From: Thomas Fitzsimmons Date: Tue, 12 Sep 2023 16:26:17 -0400 Subject: [PATCH 046/106] Use __PPC64__ macro for GCC detection --- nuklear.h | 4 ++-- src/nuklear.h | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/nuklear.h b/nuklear.h index 2d754a6..3d676ad 100644 --- a/nuklear.h +++ b/nuklear.h @@ -373,7 +373,7 @@ extern "C" { #elif (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER) #define NK_SIZE_TYPE unsigned __int32 #elif defined(__GNUC__) || defined(__clang__) - #if defined(__x86_64__) || defined(__ppc64__) || defined(__aarch64__) + #if defined(__x86_64__) || defined(__ppc64__) || defined(__PPC64__) || defined(__aarch64__) #define NK_SIZE_TYPE unsigned long #else #define NK_SIZE_TYPE unsigned int @@ -388,7 +388,7 @@ extern "C" { #elif (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER) #define NK_POINTER_TYPE unsigned __int32 #elif defined(__GNUC__) || defined(__clang__) - #if defined(__x86_64__) || defined(__ppc64__) || defined(__aarch64__) + #if defined(__x86_64__) || defined(__ppc64__) || defined(__PPC64__) || defined(__aarch64__) #define NK_POINTER_TYPE unsigned long #else #define NK_POINTER_TYPE unsigned int diff --git a/src/nuklear.h b/src/nuklear.h index 5111d9b..b09f606 100644 --- a/src/nuklear.h +++ b/src/nuklear.h @@ -151,7 +151,7 @@ extern "C" { #elif (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER) #define NK_SIZE_TYPE unsigned __int32 #elif defined(__GNUC__) || defined(__clang__) - #if defined(__x86_64__) || defined(__ppc64__) || defined(__aarch64__) + #if defined(__x86_64__) || defined(__ppc64__) || defined(__PPC64__) || defined(__aarch64__) #define NK_SIZE_TYPE unsigned long #else #define NK_SIZE_TYPE unsigned int @@ -166,7 +166,7 @@ extern "C" { #elif (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER) #define NK_POINTER_TYPE unsigned __int32 #elif defined(__GNUC__) || defined(__clang__) - #if defined(__x86_64__) || defined(__ppc64__) || defined(__aarch64__) + #if defined(__x86_64__) || defined(__ppc64__) || defined(__PPC64__) || defined(__aarch64__) #define NK_POINTER_TYPE unsigned long #else #define NK_POINTER_TYPE unsigned int From 8016ff334da7120e713287ea3c9d34a7a4305c5e Mon Sep 17 00:00:00 2001 From: Yukyduky Date: Wed, 11 Oct 2023 21:27:52 +0200 Subject: [PATCH 047/106] Added feature to disable widgets --- clib.json | 2 +- demo/common/overview.c | 20 +- nuklear.h | 505 +++++++++++++++++++++++++++---------- src/CHANGELOG | 1 + src/nuklear.h | 31 ++- src/nuklear_button.c | 35 ++- src/nuklear_chart.c | 24 +- src/nuklear_color.c | 10 + src/nuklear_color_picker.c | 2 +- src/nuklear_combo.c | 75 +++--- src/nuklear_contextual.c | 57 +++-- src/nuklear_edit.c | 19 +- src/nuklear_menu.c | 10 +- src/nuklear_progress.c | 18 +- src/nuklear_property.c | 12 +- src/nuklear_selectable.c | 17 +- src/nuklear_slider.c | 19 +- src/nuklear_style.c | 48 ++++ src/nuklear_text.c | 4 +- src/nuklear_toggle.c | 24 +- src/nuklear_widget.c | 99 ++++++++ src/nuklear_window.c | 1 + 22 files changed, 747 insertions(+), 286 deletions(-) diff --git a/clib.json b/clib.json index cf690c7..1cad42b 100644 --- a/clib.json +++ b/clib.json @@ -1,6 +1,6 @@ { "name": "nuklear", - "version": "4.10.6", + "version": "4.11.0", "repo": "Immediate-Mode-UI/Nuklear", "description": "A small ANSI C gui toolkit", "keywords": ["gl", "ui", "toolkit"], diff --git a/demo/common/overview.c b/demo/common/overview.c index 86cb9f2..3c33c80 100644 --- a/demo/common/overview.c +++ b/demo/common/overview.c @@ -248,20 +248,14 @@ overview(struct nk_context *ctx) nk_layout_row_static(ctx, 30, 80, 1); if (inactive) { - struct nk_style_button button; - button = ctx->style.button; - ctx->style.button.normal = nk_style_item_color(nk_rgb(40,40,40)); - ctx->style.button.hover = nk_style_item_color(nk_rgb(40,40,40)); - ctx->style.button.active = nk_style_item_color(nk_rgb(40,40,40)); - ctx->style.button.border_color = nk_rgb(60,60,60); - ctx->style.button.text_background = nk_rgb(60,60,60); - ctx->style.button.text_normal = nk_rgb(60,60,60); - ctx->style.button.text_hover = nk_rgb(60,60,60); - ctx->style.button.text_active = nk_rgb(60,60,60); - nk_button_label(ctx, "button"); - ctx->style.button = button; - } else if (nk_button_label(ctx, "button")) + nk_widget_disable_begin(ctx); + } + + if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); + + nk_widget_disable_end(ctx); + nk_tree_pop(ctx); } diff --git a/nuklear.h b/nuklear.h index 2d754a6..0d9b9a2 100644 --- a/nuklear.h +++ b/nuklear.h @@ -3076,7 +3076,8 @@ NK_API void nk_list_view_end(struct nk_list_view*); enum nk_widget_layout_states { NK_WIDGET_INVALID, /* The widget cannot be seen and is completely out of view */ NK_WIDGET_VALID, /* The widget is completely inside the window and can be updated and drawn */ - NK_WIDGET_ROM /* The widget is partially visible and cannot be updated */ + NK_WIDGET_ROM, /* The widget is partially visible and cannot be updated */ + NK_WIDGET_DISABLED /* The widget is manually disabled and acts like NK_WIDGET_ROM */ }; enum nk_widget_states { NK_WIDGET_STATE_MODIFIED = NK_FLAG(1), @@ -3099,6 +3100,8 @@ NK_API nk_bool nk_widget_is_hovered(struct nk_context*); NK_API nk_bool nk_widget_is_mouse_clicked(struct nk_context*, enum nk_buttons); NK_API nk_bool nk_widget_has_mouse_click_down(struct nk_context*, enum nk_buttons, nk_bool down); NK_API void nk_spacing(struct nk_context*, int cols); +NK_API void nk_widget_disable_begin(struct nk_context* ctx); +NK_API void nk_widget_disable_end(struct nk_context* ctx); /* ============================================================================= * * TEXT @@ -3669,6 +3672,7 @@ NK_API struct nk_color nk_rgb_f(float r, float g, float b); NK_API struct nk_color nk_rgb_fv(const float *rgb); NK_API struct nk_color nk_rgb_cf(struct nk_colorf c); NK_API struct nk_color nk_rgb_hex(const char *rgb); +NK_API struct nk_color nk_rgb_factor(const struct nk_color col, const float factor); NK_API struct nk_color nk_rgba(int r, int g, int b, int a); NK_API struct nk_color nk_rgba_u32(nk_uint); @@ -4889,6 +4893,8 @@ struct nk_style_item { struct nk_style_text { struct nk_color color; struct nk_vec2 padding; + float color_factor; + float disabled_factor; }; struct nk_style_button { @@ -4911,6 +4917,8 @@ struct nk_style_button { struct nk_vec2 padding; struct nk_vec2 image_padding; struct nk_vec2 touch_padding; + float color_factor; + float disabled_factor; /* optional user callbacks */ nk_handle userdata; @@ -4941,6 +4949,8 @@ struct nk_style_toggle { struct nk_vec2 touch_padding; float spacing; float border; + float color_factor; + float disabled_factor; /* optional user callbacks */ nk_handle userdata; @@ -4976,6 +4986,8 @@ struct nk_style_selectable { struct nk_vec2 padding; struct nk_vec2 touch_padding; struct nk_vec2 image_padding; + float color_factor; + float disabled_factor; /* optional user callbacks */ nk_handle userdata; @@ -5008,6 +5020,8 @@ struct nk_style_slider { struct nk_vec2 padding; struct nk_vec2 spacing; struct nk_vec2 cursor_size; + float color_factor; + float disabled_factor; /* optional buttons */ int show_buttons; @@ -5041,6 +5055,8 @@ struct nk_style_progress { float cursor_border; float cursor_rounding; struct nk_vec2 padding; + float color_factor; + float disabled_factor; /* optional user callbacks */ nk_handle userdata; @@ -5067,6 +5083,8 @@ struct nk_style_scrollbar { float border_cursor; float rounding_cursor; struct nk_vec2 padding; + float color_factor; + float disabled_factor; /* optional buttons */ int show_buttons; @@ -5113,6 +5131,8 @@ struct nk_style_edit { struct nk_vec2 scrollbar_size; struct nk_vec2 padding; float row_padding; + float color_factor; + float disabled_factor; }; struct nk_style_property { @@ -5135,6 +5155,8 @@ struct nk_style_property { float border; float rounding; struct nk_vec2 padding; + float color_factor; + float disabled_factor; struct nk_style_edit edit; struct nk_style_button inc_button; @@ -5157,6 +5179,8 @@ struct nk_style_chart { float border; float rounding; struct nk_vec2 padding; + float color_factor; + float disabled_factor; }; struct nk_style_combo { @@ -5188,6 +5212,8 @@ struct nk_style_combo { struct nk_vec2 content_padding; struct nk_vec2 button_padding; struct nk_vec2 spacing; + float color_factor; + float disabled_factor; }; struct nk_style_tab { @@ -5210,6 +5236,8 @@ struct nk_style_tab { float indent; struct nk_vec2 padding; struct nk_vec2 spacing; + float color_factor; + float disabled_factor; }; enum nk_style_header_align { @@ -5492,6 +5520,7 @@ struct nk_window { struct nk_popup_state popup; struct nk_edit_state edit; unsigned int scrolled; + nk_bool widgets_disabled; struct nk_table *tables; unsigned int table_count; @@ -7575,6 +7604,16 @@ nk_parse_hex(const char *p, int length) return i; } NK_API struct nk_color +nk_rgb_factor(const struct nk_color col, const float factor) +{ + struct nk_color ret; + ret.r = col.r * factor; + ret.g = col.g * factor; + ret.b = col.b * factor; + ret.a = col.a; + return ret; +} +NK_API struct nk_color nk_rgba(int r, int g, int b, int a) { struct nk_color ret; @@ -18212,6 +18251,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) text = &style->text; text->color = table[NK_COLOR_TEXT]; text->padding = nk_vec2(0,0); + text->color_factor = 1.0f; + text->disabled_factor = 0.5f; /* default button */ button = &style->button; @@ -18231,6 +18272,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 1.0f; button->rounding = 4.0f; + button->color_factor = 1.0f; + button->disabled_factor = 0.5f; button->draw_begin = 0; button->draw_end = 0; @@ -18251,6 +18294,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor = 1.0f; + button->disabled_factor = 0.5f; button->draw_begin = 0; button->draw_end = 0; @@ -18271,6 +18316,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 1.0f; + button->color_factor = 1.0f; + button->disabled_factor = 0.5f; button->draw_begin = 0; button->draw_end = 0; @@ -18292,6 +18339,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) toggle->border_color = nk_rgba(0,0,0,0); toggle->border = 0.0f; toggle->spacing = 4; + toggle->color_factor = 1.0f; + toggle->disabled_factor = 0.5f; /* option toggle */ toggle = &style->option; @@ -18311,6 +18360,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) toggle->border_color = nk_rgba(0,0,0,0); toggle->border = 0.0f; toggle->spacing = 4; + toggle->color_factor = 1.0f; + toggle->disabled_factor = 0.5f; /* selectable */ select = &style->selectable; @@ -18332,6 +18383,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) select->touch_padding = nk_vec2(0,0); select->userdata = nk_handle_ptr(0); select->rounding = 0.0f; + select->color_factor = 1.0f; + select->disabled_factor = 0.5f; select->draw_begin = 0; select->draw_end = 0; @@ -18357,6 +18410,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) slider->show_buttons = nk_false; slider->bar_height = 8; slider->rounding = 0; + slider->color_factor = 1.0f; + slider->disabled_factor = 0.5f; slider->draw_begin = 0; slider->draw_end = 0; @@ -18376,6 +18431,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 1.0f; button->rounding = 0.0f; + button->color_factor = 1.0f; + button->disabled_factor = 0.5f; button->draw_begin = 0; button->draw_end = 0; style->slider.dec_button = style->slider.inc_button; @@ -18397,6 +18454,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) prog->border = 0; prog->cursor_rounding = 0; prog->cursor_border = 0; + prog->color_factor = 1.0f; + prog->disabled_factor = 0.5f; prog->draw_begin = 0; prog->draw_end = 0; @@ -18420,6 +18479,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) scroll->rounding = 0; scroll->border_cursor = 0; scroll->rounding_cursor = 0; + scroll->color_factor = 1.0f; + scroll->disabled_factor = 0.5f; scroll->draw_begin = 0; scroll->draw_end = 0; style->scrollv = style->scrollh; @@ -18440,6 +18501,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 1.0f; button->rounding = 0.0f; + button->color_factor = 1.0f; + button->disabled_factor = 0.5f; button->draw_begin = 0; button->draw_end = 0; style->scrollh.dec_button = style->scrollh.inc_button; @@ -18471,6 +18534,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) edit->cursor_size = 4; edit->border = 1; edit->rounding = 0; + edit->color_factor = 1.0f; + edit->disabled_factor = 0.5f; /* property */ property = &style->property; @@ -18490,6 +18555,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) property->rounding = 10; property->draw_begin = 0; property->draw_end = 0; + property->color_factor = 1.0f; + property->disabled_factor = 0.5f; /* property buttons */ button = &style->property.dec_button; @@ -18508,6 +18575,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor = 1.0f; + button->disabled_factor = 0.5f; button->draw_begin = 0; button->draw_end = 0; style->property.inc_button = style->property.dec_button; @@ -18534,6 +18603,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) edit->cursor_size = 8; edit->border = 0; edit->rounding = 0; + edit->color_factor = 1.0f; + edit->disabled_factor = 0.5f; /* chart */ chart = &style->chart; @@ -18545,6 +18616,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) chart->padding = nk_vec2(4,4); chart->border = 0; chart->rounding = 0; + chart->color_factor = 1.0f; + chart->disabled_factor = 0.5f; /* combo */ combo = &style->combo; @@ -18563,6 +18636,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) combo->spacing = nk_vec2(4,0); combo->border = 1; combo->rounding = 0; + combo->color_factor = 1.0f; + combo->disabled_factor = 0.5f; /* combo button */ button = &style->combo.button; @@ -18581,6 +18656,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor = 1.0f; + button->disabled_factor = 0.5f; button->draw_begin = 0; button->draw_end = 0; @@ -18596,6 +18673,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) tab->indent = 10.0f; tab->border = 1; tab->rounding = 0; + tab->color_factor = 1.0f; + tab->disabled_factor = 0.5f; /* tab button */ button = &style->tab.tab_minimize_button; @@ -18614,6 +18693,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor = 1.0f; + button->disabled_factor = 0.5f; button->draw_begin = 0; button->draw_end = 0; style->tab.tab_maximize_button =*button; @@ -18635,6 +18716,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor = 1.0f; + button->disabled_factor = 0.5f; button->draw_begin = 0; button->draw_end = 0; style->tab.node_maximize_button =*button; @@ -18672,6 +18755,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor = 1.0f; + button->disabled_factor = 0.5f; button->draw_begin = 0; button->draw_end = 0; @@ -18692,6 +18777,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor = 1.0f; + button->disabled_factor = 0.5f; button->draw_begin = 0; button->draw_end = 0; @@ -20241,6 +20328,7 @@ nk_begin_titled(struct nk_context *ctx, const char *name, const char *title, NK_MEMCPY(win->name_string, name, name_length); win->name_string[name_length] = 0; win->popup.win = 0; + win->widgets_disabled = false; if (!ctx->active) ctx->active = win; } else { @@ -21010,6 +21098,7 @@ nk_contextual_begin(struct nk_context *ctx, nk_flags flags, struct nk_vec2 size, struct nk_window *win; struct nk_window *popup; struct nk_rect body; + struct nk_input* in; NK_STORAGE const struct nk_rect null_rect = {-1,-1,0,0}; int is_clicked = 0; @@ -21030,35 +21119,39 @@ nk_contextual_begin(struct nk_context *ctx, nk_flags flags, struct nk_vec2 size, /* check if currently active contextual is active */ popup = win->popup.win; is_open = (popup && win->popup.type == NK_PANEL_CONTEXTUAL); - is_clicked = nk_input_mouse_clicked(&ctx->input, NK_BUTTON_RIGHT, trigger_bounds); - if (win->popup.active_con && win->popup.con_count != win->popup.active_con) - return 0; - if (!is_open && win->popup.active_con) - win->popup.active_con = 0; - if ((!is_open && !is_clicked)) - return 0; + in = win->widgets_disabled ? 0 : &ctx->input; + if (in) { + is_clicked = nk_input_mouse_clicked(in, NK_BUTTON_RIGHT, trigger_bounds); + if (win->popup.active_con && win->popup.con_count != win->popup.active_con) + return 0; + if (!is_open && win->popup.active_con) + win->popup.active_con = 0; + if ((!is_open && !is_clicked)) + return 0; - /* calculate contextual position on click */ - win->popup.active_con = win->popup.con_count; - if (is_clicked) { - body.x = ctx->input.mouse.pos.x; - body.y = ctx->input.mouse.pos.y; - } else { - body.x = popup->bounds.x; - body.y = popup->bounds.y; - } - body.w = size.x; - body.h = size.y; + /* calculate contextual position on click */ + win->popup.active_con = win->popup.con_count; + if (is_clicked) { + body.x = in->mouse.pos.x; + body.y = in->mouse.pos.y; + } else { + body.x = popup->bounds.x; + body.y = popup->bounds.y; + } - /* start nonblocking contextual popup */ - ret = nk_nonblock_begin(ctx, flags|NK_WINDOW_NO_SCROLLBAR, body, + body.w = size.x; + body.h = size.y; + + /* start nonblocking contextual popup */ + ret = nk_nonblock_begin(ctx, flags | NK_WINDOW_NO_SCROLLBAR, body, null_rect, NK_PANEL_CONTEXTUAL); - if (ret) win->popup.type = NK_PANEL_CONTEXTUAL; - else { - win->popup.active_con = 0; - win->popup.type = NK_PANEL_NONE; - if (win->popup.win) - win->popup.win->flags = 0; + if (ret) win->popup.type = NK_PANEL_CONTEXTUAL; + else { + win->popup.active_con = 0; + win->popup.type = NK_PANEL_NONE; + if (win->popup.win) + win->popup.win->flags = 0; + } } return ret; } @@ -21347,7 +21440,7 @@ nk_menu_begin_text(struct nk_context *ctx, const char *title, int len, win = ctx->current; state = nk_widget(&header, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || win->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_text(&ctx->last_widget_state, &win->buffer, header, title, len, align, NK_BUTTON_DEFAULT, &ctx->style.menu_button, in, ctx->style.font)) is_clicked = nk_true; @@ -21377,7 +21470,7 @@ nk_menu_begin_image(struct nk_context *ctx, const char *id, struct nk_image img, win = ctx->current; state = nk_widget(&header, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_image(&ctx->last_widget_state, &win->buffer, header, img, NK_BUTTON_DEFAULT, &ctx->style.menu_button, in)) is_clicked = nk_true; @@ -21402,7 +21495,7 @@ nk_menu_begin_symbol(struct nk_context *ctx, const char *id, win = ctx->current; state = nk_widget(&header, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_symbol(&ctx->last_widget_state, &win->buffer, header, sym, NK_BUTTON_DEFAULT, &ctx->style.menu_button, in, ctx->style.font)) is_clicked = nk_true; @@ -21427,7 +21520,7 @@ nk_menu_begin_image_text(struct nk_context *ctx, const char *title, int len, win = ctx->current; state = nk_widget(&header, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_text_image(&ctx->last_widget_state, &win->buffer, header, img, title, len, align, NK_BUTTON_DEFAULT, &ctx->style.menu_button, ctx->style.font, in)) @@ -21460,7 +21553,7 @@ nk_menu_begin_symbol_text(struct nk_context *ctx, const char *title, int len, state = nk_widget(&header, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_text_symbol(&ctx->last_widget_state, &win->buffer, header, sym, title, len, align, NK_BUTTON_DEFAULT, &ctx->style.menu_button, ctx->style.font, in)) is_clicked = nk_true; @@ -23132,6 +23225,8 @@ nk_widget(struct nk_rect *bounds, const struct nk_context *ctx) nk_unify(&v, &c, bounds->x, bounds->y, bounds->x + bounds->w, bounds->y + bounds->h); if (!NK_INTERSECT(c.x, c.y, c.w, c.h, bounds->x, bounds->y, bounds->w, bounds->h)) return NK_WIDGET_INVALID; + if (win->widgets_disabled) + return NK_WIDGET_DISABLED; if (!NK_INBOX(in->mouse.pos.x, in->mouse.pos.y, v.x, v.y, v.w, v.h)) return NK_WIDGET_ROM; return NK_WIDGET_VALID; @@ -23184,7 +23279,104 @@ nk_spacing(struct nk_context *ctx, int cols) nk_panel_alloc_space(&none, ctx); } layout->row.index = index; } +NK_API void +nk_widget_disable_begin(struct nk_context* ctx) +{ + struct nk_window* win; + struct nk_style* style; + NK_ASSERT(ctx); + NK_ASSERT(ctx->current); + + if (!ctx || !ctx->current) + return; + + win = ctx->current; + style = &ctx->style; + + win->widgets_disabled = nk_true; + + style->button.color_factor = style->button.disabled_factor; + style->chart.color_factor = style->chart.disabled_factor; + style->checkbox.color_factor = style->checkbox.disabled_factor; + style->combo.color_factor = style->combo.disabled_factor; + style->combo.button.color_factor = style->combo.button.disabled_factor; + style->contextual_button.color_factor = style->contextual_button.disabled_factor; + style->edit.color_factor = style->edit.disabled_factor; + style->edit.scrollbar.color_factor = style->edit.scrollbar.disabled_factor; + style->menu_button.color_factor = style->menu_button.disabled_factor; + style->option.color_factor = style->option.disabled_factor; + style->progress.color_factor = style->progress.disabled_factor; + style->property.color_factor = style->property.disabled_factor; + style->property.inc_button.color_factor = style->property.inc_button.disabled_factor; + style->property.dec_button.color_factor = style->property.dec_button.disabled_factor; + style->property.edit.color_factor = style->property.edit.disabled_factor; + style->scrollh.color_factor = style->scrollh.disabled_factor; + style->scrollh.inc_button.color_factor = style->scrollh.inc_button.disabled_factor; + style->scrollh.dec_button.color_factor = style->scrollh.dec_button.disabled_factor; + style->scrollv.color_factor = style->scrollv.disabled_factor; + style->scrollv.inc_button.color_factor = style->scrollv.inc_button.disabled_factor; + style->scrollv.dec_button.color_factor = style->scrollv.dec_button.disabled_factor; + style->selectable.color_factor = style->selectable.disabled_factor; + style->slider.color_factor = style->slider.disabled_factor; + style->slider.inc_button.color_factor = style->slider.inc_button.disabled_factor; + style->slider.dec_button.color_factor = style->slider.dec_button.disabled_factor; + style->tab.color_factor = style->tab.disabled_factor; + style->tab.node_maximize_button.color_factor = style->tab.node_maximize_button.disabled_factor; + style->tab.node_minimize_button.color_factor = style->tab.node_minimize_button.disabled_factor; + style->tab.tab_maximize_button.color_factor = style->tab.tab_maximize_button.disabled_factor; + style->tab.tab_minimize_button.color_factor = style->tab.tab_minimize_button.disabled_factor; + style->text.color_factor = style->text.disabled_factor; +} +NK_API void +nk_widget_disable_end(struct nk_context* ctx) +{ + struct nk_window* win; + struct nk_style* style; + + NK_ASSERT(ctx); + NK_ASSERT(ctx->current); + + if (!ctx || !ctx->current) + return; + + win = ctx->current; + style = &ctx->style; + + win->widgets_disabled = nk_false; + + style->button.color_factor = 1.0f; + style->chart.color_factor = 1.0f; + style->checkbox.color_factor = 1.0f; + style->combo.color_factor = 1.0f; + style->combo.button.color_factor = 1.0f; + style->contextual_button.color_factor = 1.0f; + style->edit.color_factor = 1.0f; + style->edit.scrollbar.color_factor = 1.0f; + style->menu_button.color_factor = 1.0f; + style->option.color_factor = 1.0f; + style->progress.color_factor = 1.0f; + style->property.color_factor = 1.0f; + style->property.inc_button.color_factor = 1.0f; + style->property.dec_button.color_factor = 1.0f; + style->property.edit.color_factor = 1.0f; + style->scrollh.color_factor = 1.0f; + style->scrollh.inc_button.color_factor = 1.0f; + style->scrollh.dec_button.color_factor = 1.0f; + style->scrollv.color_factor = 1.0f; + style->scrollv.inc_button.color_factor = 1.0f; + style->scrollv.dec_button.color_factor = 1.0f; + style->selectable.color_factor = 1.0f; + style->slider.color_factor = 1.0f; + style->slider.inc_button.color_factor = 1.0f; + style->slider.dec_button.color_factor = 1.0f; + style->tab.color_factor = 1.0f; + style->tab.node_maximize_button.color_factor = 1.0f; + style->tab.node_minimize_button.color_factor = 1.0f; + style->tab.tab_maximize_button.color_factor = 1.0f; + style->tab.tab_minimize_button.color_factor = 1.0f; + style->text.color_factor = 1.0f; +} @@ -23302,7 +23494,7 @@ nk_text_colored(struct nk_context *ctx, const char *str, int len, text.padding.x = item_padding.x; text.padding.y = item_padding.y; text.background = style->window.background; - text.text = color; + text.text = nk_rgb_factor(color, style->text.color_factor); nk_widget_text(&win->buffer, bounds, str, len, &text, alignment, style->font); } NK_API void @@ -23329,7 +23521,7 @@ nk_text_wrap_colored(struct nk_context *ctx, const char *str, text.padding.x = item_padding.x; text.padding.y = item_padding.y; text.background = style->window.background; - text.text = color; + text.text = nk_rgb_factor(color, style->text.color_factor); nk_widget_text_wrap(&win->buffer, bounds, str, len, &text, style->font); } #ifdef NK_INCLUDE_STANDARD_VARARGS @@ -23826,16 +24018,16 @@ nk_draw_button(struct nk_command_buffer *out, background = &style->active; else background = &style->normal; - switch(background->type) { + switch (background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, *bounds, &background->data.image, nk_white); + nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_rgb_factor(nk_white, style->color_factor), style->color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, *bounds, style->rounding, background->data.color); - nk_stroke_rect(out, *bounds, style->rounding, style->border, style->border_color); + nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); + nk_stroke_rect(out, *bounds, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor)); break; } return background; @@ -23885,6 +24077,8 @@ nk_draw_button_text(struct nk_command_buffer *out, text.text = style->text_active; else text.text = style->text_normal; + text.text = nk_rgb_factor(text.text, style->color_factor); + text.padding = nk_vec2(0,0); nk_widget_text(out, *content, txt, len, &text, text_alignment, font); } @@ -23932,6 +24126,8 @@ nk_draw_button_symbol(struct nk_command_buffer *out, else if (state & NK_WIDGET_STATE_ACTIVED) sym = style->text_active; else sym = style->text_normal; + + sym = nk_rgb_factor(sym, style->color_factor); nk_draw_symbol(out, type, *content, bg, sym, 1, font); } NK_LIB nk_bool @@ -23963,7 +24159,7 @@ nk_draw_button_image(struct nk_command_buffer *out, nk_flags state, const struct nk_style_button *style, const struct nk_image *img) { nk_draw_button(out, bounds, state, style); - nk_draw_image(out, *content, img, nk_white); + nk_draw_image(out, *content, img, nk_rgb_factor(nk_white, style->color_factor)); } NK_LIB nk_bool nk_do_button_image(nk_flags *state, @@ -24020,6 +24216,8 @@ nk_draw_button_text_symbol(struct nk_command_buffer *out, text.text = style->text_normal; } + sym = nk_rgb_factor(sym, style->color_factor); + text.text = nk_rgb_factor(text.text, style->color_factor); text.padding = nk_vec2(0,0); nk_draw_symbol(out, type, *symbol, style->text_background, sym, 0, font); nk_widget_text(out, *label, str, len, &text, NK_TEXT_CENTERED, font); @@ -24077,9 +24275,10 @@ nk_draw_button_text_image(struct nk_command_buffer *out, text.text = style->text_active; else text.text = style->text_normal; - text.padding = nk_vec2(0,0); + text.text = nk_rgb_factor(text.text, style->color_factor); + text.padding = nk_vec2(0, 0); nk_widget_text(out, *label, str, len, &text, NK_TEXT_CENTERED, font); - nk_draw_image(out, *image, img, nk_white); + nk_draw_image(out, *image, img, nk_rgb_factor(nk_white, style->color_factor)); } NK_LIB nk_bool nk_do_button_text_image(nk_flags *state, @@ -24184,7 +24383,7 @@ nk_button_text_styled(struct nk_context *ctx, state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_text(&ctx->last_widget_state, &win->buffer, bounds, title, len, style->text_alignment, ctx->button_behavior, style, in, ctx->style.font); @@ -24229,7 +24428,7 @@ nk_button_color(struct nk_context *ctx, struct nk_color color) state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; button = ctx->style.button; button.normal = nk_style_item_color(color); @@ -24261,7 +24460,7 @@ nk_button_symbol_styled(struct nk_context *ctx, layout = win->layout; state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_symbol(&ctx->last_widget_state, &win->buffer, bounds, symbol, ctx->button_behavior, style, in, ctx->style.font); } @@ -24294,7 +24493,7 @@ nk_button_image_styled(struct nk_context *ctx, const struct nk_style_button *sty state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_image(&ctx->last_widget_state, &win->buffer, bounds, img, ctx->button_behavior, style, in); } @@ -24328,7 +24527,7 @@ nk_button_symbol_text_styled(struct nk_context *ctx, state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_text_symbol(&ctx->last_widget_state, &win->buffer, bounds, symbol, text, len, align, ctx->button_behavior, style, ctx->style.font, in); @@ -24375,7 +24574,7 @@ nk_button_image_text_styled(struct nk_context *ctx, state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_text_image(&ctx->last_widget_state, &win->buffer, bounds, img, text, len, align, ctx->button_behavior, style, ctx->style.font, in); @@ -24448,14 +24647,16 @@ nk_draw_checkbox(struct nk_command_buffer *out, text.text = style->text_normal; } + text.text = nk_rgb_factor(text.text, style->color_factor); + /* draw background and cursor */ if (background->type == NK_STYLE_ITEM_COLOR) { - nk_fill_rect(out, *selector, 0, style->border_color); - nk_fill_rect(out, nk_shrink_rect(*selector, style->border), 0, background->data.color); - } else nk_draw_image(out, *selector, &background->data.image, nk_white); + nk_fill_rect(out, *selector, 0, nk_rgb_factor(style->border_color, style->color_factor)); + nk_fill_rect(out, nk_shrink_rect(*selector, style->border), 0, nk_rgb_factor(background->data.color, style->color_factor)); + } else nk_draw_image(out, *selector, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); if (active) { if (cursor->type == NK_STYLE_ITEM_IMAGE) - nk_draw_image(out, *cursors, &cursor->data.image, nk_white); + nk_draw_image(out, *cursors, &cursor->data.image, nk_rgb_factor(nk_white, style->color_factor)); else nk_fill_rect(out, *cursors, 0, cursor->data.color); } @@ -24490,14 +24691,16 @@ nk_draw_option(struct nk_command_buffer *out, text.text = style->text_normal; } + text.text = nk_rgb_factor(text.text, style->color_factor); + /* draw background and cursor */ if (background->type == NK_STYLE_ITEM_COLOR) { - nk_fill_circle(out, *selector, style->border_color); - nk_fill_circle(out, nk_shrink_rect(*selector, style->border), background->data.color); - } else nk_draw_image(out, *selector, &background->data.image, nk_white); + nk_fill_circle(out, *selector, nk_rgb_factor(style->border_color, style->color_factor)); + nk_fill_circle(out, nk_shrink_rect(*selector, style->border), nk_rgb_factor(background->data.color, style->color_factor)); + } else nk_draw_image(out, *selector, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); if (active) { if (cursor->type == NK_STYLE_ITEM_IMAGE) - nk_draw_image(out, *cursors, &cursor->data.image, nk_white); + nk_draw_image(out, *cursors, &cursor->data.image, nk_rgb_factor(nk_white, style->color_factor)); else nk_fill_circle(out, *cursors, cursor->data.color); } @@ -24596,7 +24799,7 @@ nk_check_text(struct nk_context *ctx, const char *text, int len, nk_bool active) state = nk_widget(&bounds, ctx); if (!state) return active; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &active, text, len, NK_TOGGLE_CHECK, &style->checkbox, in, style->font); return active; @@ -24691,7 +24894,7 @@ nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_act state = nk_widget(&bounds, ctx); if (!state) return (int)state; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &is_active, text, len, NK_TOGGLE_OPTION, &style->option, in, style->font); return is_active; @@ -24763,23 +24966,26 @@ nk_draw_selectable(struct nk_command_buffer *out, text.text = style->text_normal_active; } } + + text.text = nk_rgb_factor(text.text, style->color_factor); + /* draw selectable background and text */ switch (background->type) { case NK_STYLE_ITEM_IMAGE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_image(out, *bounds, &background->data.image, nk_white); + nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: text.background = background->data.color; - nk_fill_rect(out, *bounds, style->rounding, background->data.color); + nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); break; } if (icon) { - if (img) nk_draw_image(out, *icon, img, nk_white); + if (img) nk_draw_image(out, *icon, img, nk_rgb_factor(nk_white, style->color_factor)); else nk_draw_symbol(out, sym, *icon, text.background, text.text, 1, font); } nk_widget_text(out, *bounds, string, len, &text, align, font); @@ -24940,7 +25146,7 @@ nk_selectable_text(struct nk_context *ctx, const char *str, int len, state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_selectable(&ctx->last_widget_state, &win->buffer, bounds, str, len, align, value, &style->selectable, in, style->font); } @@ -24969,7 +25175,7 @@ nk_selectable_image_text(struct nk_context *ctx, struct nk_image img, state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_selectable_image(&ctx->last_widget_state, &win->buffer, bounds, str, len, align, value, &img, &style->selectable, in, style->font); } @@ -24998,7 +25204,7 @@ nk_selectable_symbol_text(struct nk_context *ctx, enum nk_symbol_type sym, state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_selectable_symbol(&ctx->last_widget_state, &win->buffer, bounds, str, len, align, value, sym, &style->selectable, in, style->font); } @@ -25130,6 +25336,7 @@ nk_draw_slider(struct nk_command_buffer *out, nk_flags state, bar_color = style->bar_normal; cursor = &style->cursor_normal; } + /* calculate slider background bar */ bar.x = bounds->x; bar.y = (visual_cursor->y + visual_cursor->h/2) - bounds->h/12; @@ -25145,26 +25352,26 @@ nk_draw_slider(struct nk_command_buffer *out, nk_flags state, /* draw background */ switch(background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, *bounds, &background->data.image, nk_white); + nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, *bounds, style->rounding, background->data.color); - nk_stroke_rect(out, *bounds, style->rounding, style->border, style->border_color); + nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); + nk_stroke_rect(out, *bounds, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor)); break; } /* draw slider bar */ - nk_fill_rect(out, bar, style->rounding, bar_color); - nk_fill_rect(out, fill, style->rounding, style->bar_filled); + nk_fill_rect(out, bar, style->rounding, nk_rgb_factor(bar_color, style->color_factor)); + nk_fill_rect(out, fill, style->rounding, nk_rgb_factor(style->bar_filled, style->color_factor)); /* draw cursor */ if (cursor->type == NK_STYLE_ITEM_IMAGE) - nk_draw_image(out, *visual_cursor, &cursor->data.image, nk_white); + nk_draw_image(out, *visual_cursor, &cursor->data.image, nk_rgb_factor(nk_white, style->color_factor)); else - nk_fill_circle(out, *visual_cursor, cursor->data.color); + nk_fill_circle(out, *visual_cursor, nk_rgb_factor(cursor->data.color, style->color_factor)); } NK_LIB float nk_do_slider(nk_flags *state, @@ -25282,7 +25489,7 @@ nk_slider_float(struct nk_context *ctx, float min_value, float *value, float max state = nk_widget(&bounds, ctx); if (!state) return ret; - in = (/*state == NK_WIDGET_ROM || */ layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (/*state == NK_WIDGET_ROM || */ state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; old_value = *value; *value = nk_do_slider(&ctx->last_widget_state, &win->buffer, bounds, min_value, @@ -25376,28 +25583,28 @@ nk_draw_progress(struct nk_command_buffer *out, nk_flags state, /* draw background */ switch(background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, *bounds, &background->data.image, nk_white); + nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, *bounds, style->rounding, background->data.color); - nk_stroke_rect(out, *bounds, style->rounding, style->border, style->border_color); + nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); + nk_stroke_rect(out, *bounds, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor)); break; } /* draw cursor */ switch(cursor->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, *scursor, &cursor->data.image, nk_white); + nk_draw_image(out, *scursor, &cursor->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, *scursor, &cursor->data.slice, nk_white); + nk_draw_nine_slice(out, *scursor, &cursor->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, *scursor, style->rounding, cursor->data.color); - nk_stroke_rect(out, *scursor, style->rounding, style->border, style->border_color); + nk_fill_rect(out, *scursor, style->rounding, nk_rgb_factor(cursor->data.color, style->color_factor)); + nk_stroke_rect(out, *scursor, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor)); break; } } @@ -25457,7 +25664,7 @@ nk_progress(struct nk_context *ctx, nk_size *cur, nk_size max, nk_bool is_modify state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; old_value = *cur; *cur = nk_do_progress(&ctx->last_widget_state, &win->buffer, bounds, *cur, max, is_modifyable, &style->progress, in); @@ -26903,6 +27110,9 @@ nk_edit_draw_text(struct nk_command_buffer *out, float line_offset = 0; int line_count = 0; + foreground = nk_rgb_factor(foreground, style->color_factor); + background = nk_rgb_factor(background, style->color_factor); + struct nk_text txt; txt.padding = nk_vec2(0,0); txt.background = background; @@ -27145,14 +27355,14 @@ nk_do_edit(nk_flags *state, struct nk_command_buffer *out, /* draw background frame */ switch(background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, bounds, &background->data.image, nk_white); + nk_draw_image(out, bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(out, bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, bounds, style->rounding, background->data.color); - nk_stroke_rect(out, bounds, style->rounding, style->border, style->border_color); + nk_fill_rect(out, bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); + nk_stroke_rect(out, bounds, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor)); break; }} @@ -27361,6 +27571,8 @@ nk_do_edit(nk_flags *state, struct nk_command_buffer *out, else background_color = background->data.color; + cursor_color = nk_rgb_factor(cursor_color, style->color_factor); + cursor_text_color = nk_rgb_factor(cursor_text_color, style->color_factor); if (edit->select_start == edit->select_end) { /* no selection so just draw the complete text */ @@ -27468,6 +27680,10 @@ nk_do_edit(nk_flags *state, struct nk_command_buffer *out, background_color = nk_rgba(0,0,0,0); else background_color = background->data.color; + + background_color = nk_rgb_factor(background_color, style->color_factor); + text_color = nk_rgb_factor(text_color, style->color_factor); + nk_edit_draw_text(out, style, area.x - edit->scrollbar.x, area.y - edit->scrollbar.y, 0, begin, l, row_height, font, background_color, text_color, nk_false); @@ -27587,6 +27803,8 @@ nk_edit_buffer(struct nk_context *ctx, nk_flags flags, style = &ctx->style; state = nk_widget(&bounds, ctx); if (!state) return state; + else if (state == NK_WIDGET_DISABLED) + flags |= NK_EDIT_READ_ONLY; in = (win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; /* check if edit is currently hot item */ @@ -27720,20 +27938,22 @@ nk_draw_property(struct nk_command_buffer *out, const struct nk_style_property * text.text = style->label_normal; } + text.text = nk_rgb_factor(text.text, style->color_factor); + /* draw background */ switch(background->type) { case NK_STYLE_ITEM_IMAGE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_image(out, *bounds, &background->data.image, nk_white); + nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: text.background = background->data.color; - nk_fill_rect(out, *bounds, style->rounding, background->data.color); - nk_stroke_rect(out, *bounds, style->rounding, style->border, background->data.color); + nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); + nk_stroke_rect(out, *bounds, style->rounding, style->border, nk_rgb_factor(background->data.color, style->color_factor)); break; } @@ -28018,7 +28238,7 @@ nk_property(struct nk_context *ctx, const char *name, struct nk_property_variant old_state = *state; ctx->text_edit.clip = ctx->clip; in = ((s == NK_WIDGET_ROM && !win->property.active) || - layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED) ? 0 : &ctx->input; nk_do_property(&ctx->last_widget_state, &win->buffer, bounds, name, variant, inc_per_pixel, buffer, len, state, cursor, select_begin, select_end, &style->property, filter, in, style->font, &ctx->text_edit, @@ -28187,7 +28407,7 @@ nk_chart_begin_colored(struct nk_context *ctx, enum nk_chart_type type, {struct nk_chart_slot *slot = &chart->slots[chart->slot++]; slot->type = type; slot->count = count; - slot->color = color; + slot->color = nk_rgb_factor(color, style->color_factor); slot->highlight = highlight; slot->min = NK_MIN(min_value, max_value); slot->max = NK_MAX(min_value, max_value); @@ -28198,15 +28418,15 @@ nk_chart_begin_colored(struct nk_context *ctx, enum nk_chart_type type, switch(background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(&win->buffer, bounds, &background->data.image, nk_white); + nk_draw_image(&win->buffer, bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(&win->buffer, bounds, &background->data.slice, nk_white); + nk_draw_image(&win->buffer, bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(&win->buffer, bounds, style->rounding, style->border_color); + nk_fill_rect(&win->buffer, bounds, style->rounding, nk_rgb_factor(style->border_color, style->color_factor)); nk_fill_rect(&win->buffer, nk_shrink_rect(bounds, style->border), - style->rounding, style->background.data.color); + style->rounding, nk_rgb_factor(style->background.data.color, style->color_factor)); break; } return 1; @@ -28223,6 +28443,8 @@ nk_chart_add_slot_colored(struct nk_context *ctx, const enum nk_chart_type type, struct nk_color color, struct nk_color highlight, int count, float min_value, float max_value) { + const struct nk_style_chart* style; + NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); @@ -28230,12 +28452,14 @@ nk_chart_add_slot_colored(struct nk_context *ctx, const enum nk_chart_type type, if (!ctx || !ctx->current || !ctx->current->layout) return; if (ctx->current->layout->chart.slot >= NK_CHART_MAX_SLOT) return; + style = &ctx->style.chart; + /* add another slot into the graph */ {struct nk_chart *chart = &ctx->current->layout->chart; struct nk_chart_slot *slot = &chart->slots[chart->slot++]; slot->type = type; slot->count = count; - slot->color = color; + slot->color = nk_rgb_factor(color, style->color_factor); slot->highlight = highlight; slot->min = NK_MIN(min_value, max_value); slot->max = NK_MAX(min_value, max_value); @@ -28253,7 +28477,7 @@ nk_chart_push_line(struct nk_context *ctx, struct nk_window *win, struct nk_chart *g, float value, int slot) { struct nk_panel *layout = win->layout; - const struct nk_input *i = &ctx->input; + const struct nk_input *i = ctx->current->widgets_disabled ? 0 : &ctx->input; struct nk_command_buffer *out = &win->buffer; nk_flags ret = 0; @@ -28279,7 +28503,7 @@ nk_chart_push_line(struct nk_context *ctx, struct nk_window *win, bounds.w = bounds.h = 4; color = g->slots[slot].color; - if (!(layout->flags & NK_WINDOW_ROM) && + if (!(layout->flags & NK_WINDOW_ROM) && i && NK_INBOX(i->mouse.pos.x,i->mouse.pos.y, g->slots[slot].last.x-3, g->slots[slot].last.y-3, 6, 6)){ ret = nk_input_is_mouse_hovering_rect(i, bounds) ? NK_CHART_HOVERING : 0; ret |= (i->mouse.buttons[NK_BUTTON_LEFT].down && @@ -28323,7 +28547,7 @@ nk_chart_push_column(const struct nk_context *ctx, struct nk_window *win, struct nk_chart *chart, float value, int slot) { struct nk_command_buffer *out = &win->buffer; - const struct nk_input *in = &ctx->input; + const struct nk_input *in = ctx->current->widgets_disabled ? 0 : &ctx->input; struct nk_panel *layout = win->layout; float ratio; @@ -28353,7 +28577,7 @@ nk_chart_push_column(const struct nk_context *ctx, struct nk_window *win, item.x = item.x + ((float)chart->slots[slot].index); /* user chart bar selection */ - if (!(layout->flags & NK_WINDOW_ROM) && + if (!(layout->flags & NK_WINDOW_ROM) && in && NK_INBOX(in->mouse.pos.x,in->mouse.pos.y,item.x,item.y,item.w,item.h)) { ret = NK_CHART_HOVERING; ret |= (!in->mouse.buttons[NK_BUTTON_LEFT].down && @@ -28652,7 +28876,7 @@ nk_color_pick(struct nk_context * ctx, struct nk_colorf *color, layout = win->layout; state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_color_picker(&ctx->last_widget_state, &win->buffer, color, fmt, bounds, nk_vec2(0,0), in, config->font); } @@ -28734,7 +28958,7 @@ nk_combo_begin_text(struct nk_context *ctx, const char *selected, int len, if (s == NK_WIDGET_INVALID) return 0; - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; + in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; @@ -28750,19 +28974,21 @@ nk_combo_begin_text(struct nk_context *ctx, const char *selected, int len, text.text = style->combo.label_normal; } + text.text = nk_rgb_factor(text.text, style->combo.color_factor); + switch(background->type) { case NK_STYLE_ITEM_IMAGE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); + nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_COLOR: text.background = background->data.color; - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); + nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor)); + nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor)); break; } { @@ -28842,7 +29068,7 @@ nk_combo_begin_color(struct nk_context *ctx, struct nk_color color, struct nk_ve if (s == NK_WIDGET_INVALID) return 0; - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; + in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; @@ -28855,14 +29081,14 @@ nk_combo_begin_color(struct nk_context *ctx, struct nk_color color, struct nk_ve switch(background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); + nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); + nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor)); + nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor)); break; } { @@ -28900,7 +29126,7 @@ nk_combo_begin_color(struct nk_context *ctx, struct nk_color color, struct nk_ve bounds.w = (button.x - (style->combo.content_padding.x + style->combo.spacing.x)) - bounds.x; else bounds.w = header.w - 4 * style->combo.content_padding.x; - nk_fill_rect(&win->buffer, bounds, 0, color); + nk_fill_rect(&win->buffer, bounds, 0, nk_rgb_factor(color, style->combo.color_factor)); /* draw open/close button */ if (draw_button_symbol) @@ -28935,7 +29161,7 @@ nk_combo_begin_symbol(struct nk_context *ctx, enum nk_symbol_type symbol, struct if (s == NK_WIDGET_INVALID) return 0; - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; + in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; @@ -28951,19 +29177,21 @@ nk_combo_begin_symbol(struct nk_context *ctx, enum nk_symbol_type symbol, struct symbol_color = style->combo.symbol_hover; } + symbol_color = nk_rgb_factor(symbol_color, style->combo.color_factor); + switch(background->type) { case NK_STYLE_ITEM_IMAGE: sym_background = nk_rgba(0, 0, 0, 0); - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); + nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: sym_background = nk_rgba(0, 0, 0, 0); - nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_COLOR: sym_background = background->data.color; - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); + nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor)); + nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor)); break; } { @@ -29029,7 +29257,7 @@ nk_combo_begin_symbol_text(struct nk_context *ctx, const char *selected, int len s = nk_widget(&header, ctx); if (!s) return 0; - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; + in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; @@ -29048,19 +29276,22 @@ nk_combo_begin_symbol_text(struct nk_context *ctx, const char *selected, int len text.text = style->combo.label_normal; } + text.text = nk_rgb_factor(text.text, style->combo.color_factor); + symbol_color = nk_rgb_factor(symbol_color, style->combo.color_factor); + switch(background->type) { case NK_STYLE_ITEM_IMAGE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); + nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_COLOR: text.background = background->data.color; - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); + nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor)); + nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor)); break; } { @@ -29131,7 +29362,7 @@ nk_combo_begin_image(struct nk_context *ctx, struct nk_image img, struct nk_vec2 if (s == NK_WIDGET_INVALID) return 0; - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; + in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; @@ -29144,14 +29375,14 @@ nk_combo_begin_image(struct nk_context *ctx, struct nk_image img, struct nk_vec2 switch (background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); + nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); + nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor)); + nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor)); break; } { @@ -29189,7 +29420,7 @@ nk_combo_begin_image(struct nk_context *ctx, struct nk_image img, struct nk_vec2 bounds.w = (button.x - style->combo.content_padding.y) - bounds.x; else bounds.w = header.w - 2 * style->combo.content_padding.x; - nk_draw_image(&win->buffer, bounds, &img, nk_white); + nk_draw_image(&win->buffer, bounds, &img, nk_rgb_factor(nk_white, style->combo.color_factor)); /* draw open/close button */ if (draw_button_symbol) @@ -29223,7 +29454,7 @@ nk_combo_begin_image_text(struct nk_context *ctx, const char *selected, int len, s = nk_widget(&header, ctx); if (!s) return 0; - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; + in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; @@ -29239,19 +29470,21 @@ nk_combo_begin_image_text(struct nk_context *ctx, const char *selected, int len, text.text = style->combo.label_normal; } + text.text = nk_rgb_factor(text.text, style->combo.color_factor); + switch(background->type) { case NK_STYLE_ITEM_IMAGE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); + nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_COLOR: text.background = background->data.color; - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); + nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor)); + nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor)); break; } { @@ -29290,7 +29523,7 @@ nk_combo_begin_image_text(struct nk_context *ctx, const char *selected, int len, image.y = header.y + style->combo.content_padding.y; image.h = header.h - 2 * style->combo.content_padding.y; image.w = image.h; - nk_draw_image(&win->buffer, image, &img, nk_white); + nk_draw_image(&win->buffer, image, &img, nk_rgb_factor(nk_white, style->combo.color_factor)); /* draw label */ text.padding = nk_vec2(0,0); diff --git a/src/CHANGELOG b/src/CHANGELOG index 4bcdfdb..7407f3a 100644 --- a/src/CHANGELOG +++ b/src/CHANGELOG @@ -7,6 +7,7 @@ /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// +/// - 2023/10/11 (4.11.0) - Added nk_widget_disable_begin() and nk_widget_disable_end() /// - 2022/12/23 (4.10.6) - Fix incorrect glyph index in nk_font_bake() /// - 2022/12/17 (4.10.5) - Fix nk_font_bake_pack() using TTC font offset incorrectly /// - 2022/10/24 (4.10.4) - Fix nk_str_{append,insert}_str_utf8 always returning 0 diff --git a/src/nuklear.h b/src/nuklear.h index 5111d9b..4d8038a 100644 --- a/src/nuklear.h +++ b/src/nuklear.h @@ -2854,7 +2854,8 @@ NK_API void nk_list_view_end(struct nk_list_view*); enum nk_widget_layout_states { NK_WIDGET_INVALID, /* The widget cannot be seen and is completely out of view */ NK_WIDGET_VALID, /* The widget is completely inside the window and can be updated and drawn */ - NK_WIDGET_ROM /* The widget is partially visible and cannot be updated */ + NK_WIDGET_ROM, /* The widget is partially visible and cannot be updated */ + NK_WIDGET_DISABLED /* The widget is manually disabled and acts like NK_WIDGET_ROM */ }; enum nk_widget_states { NK_WIDGET_STATE_MODIFIED = NK_FLAG(1), @@ -2877,6 +2878,8 @@ NK_API nk_bool nk_widget_is_hovered(struct nk_context*); NK_API nk_bool nk_widget_is_mouse_clicked(struct nk_context*, enum nk_buttons); NK_API nk_bool nk_widget_has_mouse_click_down(struct nk_context*, enum nk_buttons, nk_bool down); NK_API void nk_spacing(struct nk_context*, int cols); +NK_API void nk_widget_disable_begin(struct nk_context* ctx); +NK_API void nk_widget_disable_end(struct nk_context* ctx); /* ============================================================================= * * TEXT @@ -3447,6 +3450,7 @@ NK_API struct nk_color nk_rgb_f(float r, float g, float b); NK_API struct nk_color nk_rgb_fv(const float *rgb); NK_API struct nk_color nk_rgb_cf(struct nk_colorf c); NK_API struct nk_color nk_rgb_hex(const char *rgb); +NK_API struct nk_color nk_rgb_factor(const struct nk_color col, const float factor); NK_API struct nk_color nk_rgba(int r, int g, int b, int a); NK_API struct nk_color nk_rgba_u32(nk_uint); @@ -4667,6 +4671,8 @@ struct nk_style_item { struct nk_style_text { struct nk_color color; struct nk_vec2 padding; + float color_factor; + float disabled_factor; }; struct nk_style_button { @@ -4689,6 +4695,8 @@ struct nk_style_button { struct nk_vec2 padding; struct nk_vec2 image_padding; struct nk_vec2 touch_padding; + float color_factor; + float disabled_factor; /* optional user callbacks */ nk_handle userdata; @@ -4719,6 +4727,8 @@ struct nk_style_toggle { struct nk_vec2 touch_padding; float spacing; float border; + float color_factor; + float disabled_factor; /* optional user callbacks */ nk_handle userdata; @@ -4754,6 +4764,8 @@ struct nk_style_selectable { struct nk_vec2 padding; struct nk_vec2 touch_padding; struct nk_vec2 image_padding; + float color_factor; + float disabled_factor; /* optional user callbacks */ nk_handle userdata; @@ -4786,6 +4798,8 @@ struct nk_style_slider { struct nk_vec2 padding; struct nk_vec2 spacing; struct nk_vec2 cursor_size; + float color_factor; + float disabled_factor; /* optional buttons */ int show_buttons; @@ -4819,6 +4833,8 @@ struct nk_style_progress { float cursor_border; float cursor_rounding; struct nk_vec2 padding; + float color_factor; + float disabled_factor; /* optional user callbacks */ nk_handle userdata; @@ -4845,6 +4861,8 @@ struct nk_style_scrollbar { float border_cursor; float rounding_cursor; struct nk_vec2 padding; + float color_factor; + float disabled_factor; /* optional buttons */ int show_buttons; @@ -4891,6 +4909,8 @@ struct nk_style_edit { struct nk_vec2 scrollbar_size; struct nk_vec2 padding; float row_padding; + float color_factor; + float disabled_factor; }; struct nk_style_property { @@ -4913,6 +4933,8 @@ struct nk_style_property { float border; float rounding; struct nk_vec2 padding; + float color_factor; + float disabled_factor; struct nk_style_edit edit; struct nk_style_button inc_button; @@ -4935,6 +4957,8 @@ struct nk_style_chart { float border; float rounding; struct nk_vec2 padding; + float color_factor; + float disabled_factor; }; struct nk_style_combo { @@ -4966,6 +4990,8 @@ struct nk_style_combo { struct nk_vec2 content_padding; struct nk_vec2 button_padding; struct nk_vec2 spacing; + float color_factor; + float disabled_factor; }; struct nk_style_tab { @@ -4988,6 +5014,8 @@ struct nk_style_tab { float indent; struct nk_vec2 padding; struct nk_vec2 spacing; + float color_factor; + float disabled_factor; }; enum nk_style_header_align { @@ -5270,6 +5298,7 @@ struct nk_window { struct nk_popup_state popup; struct nk_edit_state edit; unsigned int scrolled; + nk_bool widgets_disabled; struct nk_table *tables; unsigned int table_count; diff --git a/src/nuklear_button.c b/src/nuklear_button.c index 2636b60..98c2057 100644 --- a/src/nuklear_button.c +++ b/src/nuklear_button.c @@ -98,16 +98,16 @@ nk_draw_button(struct nk_command_buffer *out, background = &style->active; else background = &style->normal; - switch(background->type) { + switch (background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, *bounds, &background->data.image, nk_white); + nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_rgb_factor(nk_white, style->color_factor), style->color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, *bounds, style->rounding, background->data.color); - nk_stroke_rect(out, *bounds, style->rounding, style->border, style->border_color); + nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); + nk_stroke_rect(out, *bounds, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor)); break; } return background; @@ -157,6 +157,8 @@ nk_draw_button_text(struct nk_command_buffer *out, text.text = style->text_active; else text.text = style->text_normal; + text.text = nk_rgb_factor(text.text, style->color_factor); + text.padding = nk_vec2(0,0); nk_widget_text(out, *content, txt, len, &text, text_alignment, font); } @@ -204,6 +206,8 @@ nk_draw_button_symbol(struct nk_command_buffer *out, else if (state & NK_WIDGET_STATE_ACTIVED) sym = style->text_active; else sym = style->text_normal; + + sym = nk_rgb_factor(sym, style->color_factor); nk_draw_symbol(out, type, *content, bg, sym, 1, font); } NK_LIB nk_bool @@ -235,7 +239,7 @@ nk_draw_button_image(struct nk_command_buffer *out, nk_flags state, const struct nk_style_button *style, const struct nk_image *img) { nk_draw_button(out, bounds, state, style); - nk_draw_image(out, *content, img, nk_white); + nk_draw_image(out, *content, img, nk_rgb_factor(nk_white, style->color_factor)); } NK_LIB nk_bool nk_do_button_image(nk_flags *state, @@ -292,6 +296,8 @@ nk_draw_button_text_symbol(struct nk_command_buffer *out, text.text = style->text_normal; } + sym = nk_rgb_factor(sym, style->color_factor); + text.text = nk_rgb_factor(text.text, style->color_factor); text.padding = nk_vec2(0,0); nk_draw_symbol(out, type, *symbol, style->text_background, sym, 0, font); nk_widget_text(out, *label, str, len, &text, NK_TEXT_CENTERED, font); @@ -349,9 +355,10 @@ nk_draw_button_text_image(struct nk_command_buffer *out, text.text = style->text_active; else text.text = style->text_normal; - text.padding = nk_vec2(0,0); + text.text = nk_rgb_factor(text.text, style->color_factor); + text.padding = nk_vec2(0, 0); nk_widget_text(out, *label, str, len, &text, NK_TEXT_CENTERED, font); - nk_draw_image(out, *image, img, nk_white); + nk_draw_image(out, *image, img, nk_rgb_factor(nk_white, style->color_factor)); } NK_LIB nk_bool nk_do_button_text_image(nk_flags *state, @@ -456,7 +463,7 @@ nk_button_text_styled(struct nk_context *ctx, state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_text(&ctx->last_widget_state, &win->buffer, bounds, title, len, style->text_alignment, ctx->button_behavior, style, in, ctx->style.font); @@ -501,7 +508,7 @@ nk_button_color(struct nk_context *ctx, struct nk_color color) state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; button = ctx->style.button; button.normal = nk_style_item_color(color); @@ -533,7 +540,7 @@ nk_button_symbol_styled(struct nk_context *ctx, layout = win->layout; state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_symbol(&ctx->last_widget_state, &win->buffer, bounds, symbol, ctx->button_behavior, style, in, ctx->style.font); } @@ -566,7 +573,7 @@ nk_button_image_styled(struct nk_context *ctx, const struct nk_style_button *sty state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_image(&ctx->last_widget_state, &win->buffer, bounds, img, ctx->button_behavior, style, in); } @@ -600,7 +607,7 @@ nk_button_symbol_text_styled(struct nk_context *ctx, state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_text_symbol(&ctx->last_widget_state, &win->buffer, bounds, symbol, text, len, align, ctx->button_behavior, style, ctx->style.font, in); @@ -647,7 +654,7 @@ nk_button_image_text_styled(struct nk_context *ctx, state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_text_image(&ctx->last_widget_state, &win->buffer, bounds, img, text, len, align, ctx->button_behavior, style, ctx->style.font, in); diff --git a/src/nuklear_chart.c b/src/nuklear_chart.c index d4fd902..ba886e2 100644 --- a/src/nuklear_chart.c +++ b/src/nuklear_chart.c @@ -48,7 +48,7 @@ nk_chart_begin_colored(struct nk_context *ctx, enum nk_chart_type type, {struct nk_chart_slot *slot = &chart->slots[chart->slot++]; slot->type = type; slot->count = count; - slot->color = color; + slot->color = nk_rgb_factor(color, style->color_factor); slot->highlight = highlight; slot->min = NK_MIN(min_value, max_value); slot->max = NK_MAX(min_value, max_value); @@ -59,15 +59,15 @@ nk_chart_begin_colored(struct nk_context *ctx, enum nk_chart_type type, switch(background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(&win->buffer, bounds, &background->data.image, nk_white); + nk_draw_image(&win->buffer, bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(&win->buffer, bounds, &background->data.slice, nk_white); + nk_draw_image(&win->buffer, bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(&win->buffer, bounds, style->rounding, style->border_color); + nk_fill_rect(&win->buffer, bounds, style->rounding, nk_rgb_factor(style->border_color, style->color_factor)); nk_fill_rect(&win->buffer, nk_shrink_rect(bounds, style->border), - style->rounding, style->background.data.color); + style->rounding, nk_rgb_factor(style->background.data.color, style->color_factor)); break; } return 1; @@ -84,6 +84,8 @@ nk_chart_add_slot_colored(struct nk_context *ctx, const enum nk_chart_type type, struct nk_color color, struct nk_color highlight, int count, float min_value, float max_value) { + const struct nk_style_chart* style; + NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); @@ -91,12 +93,14 @@ nk_chart_add_slot_colored(struct nk_context *ctx, const enum nk_chart_type type, if (!ctx || !ctx->current || !ctx->current->layout) return; if (ctx->current->layout->chart.slot >= NK_CHART_MAX_SLOT) return; + style = &ctx->style.chart; + /* add another slot into the graph */ {struct nk_chart *chart = &ctx->current->layout->chart; struct nk_chart_slot *slot = &chart->slots[chart->slot++]; slot->type = type; slot->count = count; - slot->color = color; + slot->color = nk_rgb_factor(color, style->color_factor); slot->highlight = highlight; slot->min = NK_MIN(min_value, max_value); slot->max = NK_MAX(min_value, max_value); @@ -114,7 +118,7 @@ nk_chart_push_line(struct nk_context *ctx, struct nk_window *win, struct nk_chart *g, float value, int slot) { struct nk_panel *layout = win->layout; - const struct nk_input *i = &ctx->input; + const struct nk_input *i = ctx->current->widgets_disabled ? 0 : &ctx->input; struct nk_command_buffer *out = &win->buffer; nk_flags ret = 0; @@ -140,7 +144,7 @@ nk_chart_push_line(struct nk_context *ctx, struct nk_window *win, bounds.w = bounds.h = 4; color = g->slots[slot].color; - if (!(layout->flags & NK_WINDOW_ROM) && + if (!(layout->flags & NK_WINDOW_ROM) && i && NK_INBOX(i->mouse.pos.x,i->mouse.pos.y, g->slots[slot].last.x-3, g->slots[slot].last.y-3, 6, 6)){ ret = nk_input_is_mouse_hovering_rect(i, bounds) ? NK_CHART_HOVERING : 0; ret |= (i->mouse.buttons[NK_BUTTON_LEFT].down && @@ -184,7 +188,7 @@ nk_chart_push_column(const struct nk_context *ctx, struct nk_window *win, struct nk_chart *chart, float value, int slot) { struct nk_command_buffer *out = &win->buffer; - const struct nk_input *in = &ctx->input; + const struct nk_input *in = ctx->current->widgets_disabled ? 0 : &ctx->input; struct nk_panel *layout = win->layout; float ratio; @@ -214,7 +218,7 @@ nk_chart_push_column(const struct nk_context *ctx, struct nk_window *win, item.x = item.x + ((float)chart->slots[slot].index); /* user chart bar selection */ - if (!(layout->flags & NK_WINDOW_ROM) && + if (!(layout->flags & NK_WINDOW_ROM) && in && NK_INBOX(in->mouse.pos.x,in->mouse.pos.y,item.x,item.y,item.w,item.h)) { ret = NK_CHART_HOVERING; ret |= (!in->mouse.buttons[NK_BUTTON_LEFT].down && diff --git a/src/nuklear_color.c b/src/nuklear_color.c index f2e1e85..dc2e7fc 100644 --- a/src/nuklear_color.c +++ b/src/nuklear_color.c @@ -23,6 +23,16 @@ nk_parse_hex(const char *p, int length) return i; } NK_API struct nk_color +nk_rgb_factor(const struct nk_color col, const float factor) +{ + struct nk_color ret; + ret.r = col.r * factor; + ret.g = col.g * factor; + ret.b = col.b * factor; + ret.a = col.a; + return ret; +} +NK_API struct nk_color nk_rgba(int r, int g, int b, int a) { struct nk_color ret; diff --git a/src/nuklear_color_picker.c b/src/nuklear_color_picker.c index f9f7dfb..114c3c1 100644 --- a/src/nuklear_color_picker.c +++ b/src/nuklear_color_picker.c @@ -187,7 +187,7 @@ nk_color_pick(struct nk_context * ctx, struct nk_colorf *color, layout = win->layout; state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_color_picker(&ctx->last_widget_state, &win->buffer, color, fmt, bounds, nk_vec2(0,0), in, config->font); } diff --git a/src/nuklear_combo.c b/src/nuklear_combo.c index df1db0a..0e403b8 100644 --- a/src/nuklear_combo.c +++ b/src/nuklear_combo.c @@ -67,7 +67,7 @@ nk_combo_begin_text(struct nk_context *ctx, const char *selected, int len, if (s == NK_WIDGET_INVALID) return 0; - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; + in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; @@ -83,19 +83,21 @@ nk_combo_begin_text(struct nk_context *ctx, const char *selected, int len, text.text = style->combo.label_normal; } + text.text = nk_rgb_factor(text.text, style->combo.color_factor); + switch(background->type) { case NK_STYLE_ITEM_IMAGE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); + nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_COLOR: text.background = background->data.color; - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); + nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor)); + nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor)); break; } { @@ -175,7 +177,7 @@ nk_combo_begin_color(struct nk_context *ctx, struct nk_color color, struct nk_ve if (s == NK_WIDGET_INVALID) return 0; - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; + in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; @@ -188,14 +190,14 @@ nk_combo_begin_color(struct nk_context *ctx, struct nk_color color, struct nk_ve switch(background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); + nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); + nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor)); + nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor)); break; } { @@ -233,7 +235,7 @@ nk_combo_begin_color(struct nk_context *ctx, struct nk_color color, struct nk_ve bounds.w = (button.x - (style->combo.content_padding.x + style->combo.spacing.x)) - bounds.x; else bounds.w = header.w - 4 * style->combo.content_padding.x; - nk_fill_rect(&win->buffer, bounds, 0, color); + nk_fill_rect(&win->buffer, bounds, 0, nk_rgb_factor(color, style->combo.color_factor)); /* draw open/close button */ if (draw_button_symbol) @@ -268,7 +270,7 @@ nk_combo_begin_symbol(struct nk_context *ctx, enum nk_symbol_type symbol, struct if (s == NK_WIDGET_INVALID) return 0; - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; + in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; @@ -284,19 +286,21 @@ nk_combo_begin_symbol(struct nk_context *ctx, enum nk_symbol_type symbol, struct symbol_color = style->combo.symbol_hover; } + symbol_color = nk_rgb_factor(symbol_color, style->combo.color_factor); + switch(background->type) { case NK_STYLE_ITEM_IMAGE: sym_background = nk_rgba(0, 0, 0, 0); - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); + nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: sym_background = nk_rgba(0, 0, 0, 0); - nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_COLOR: sym_background = background->data.color; - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); + nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor)); + nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor)); break; } { @@ -362,7 +366,7 @@ nk_combo_begin_symbol_text(struct nk_context *ctx, const char *selected, int len s = nk_widget(&header, ctx); if (!s) return 0; - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; + in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; @@ -381,19 +385,22 @@ nk_combo_begin_symbol_text(struct nk_context *ctx, const char *selected, int len text.text = style->combo.label_normal; } + text.text = nk_rgb_factor(text.text, style->combo.color_factor); + symbol_color = nk_rgb_factor(symbol_color, style->combo.color_factor); + switch(background->type) { case NK_STYLE_ITEM_IMAGE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); + nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_COLOR: text.background = background->data.color; - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); + nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor)); + nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor)); break; } { @@ -464,7 +471,7 @@ nk_combo_begin_image(struct nk_context *ctx, struct nk_image img, struct nk_vec2 if (s == NK_WIDGET_INVALID) return 0; - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; + in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; @@ -477,14 +484,14 @@ nk_combo_begin_image(struct nk_context *ctx, struct nk_image img, struct nk_vec2 switch (background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); + nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); + nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor)); + nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor)); break; } { @@ -522,7 +529,7 @@ nk_combo_begin_image(struct nk_context *ctx, struct nk_image img, struct nk_vec2 bounds.w = (button.x - style->combo.content_padding.y) - bounds.x; else bounds.w = header.w - 2 * style->combo.content_padding.x; - nk_draw_image(&win->buffer, bounds, &img, nk_white); + nk_draw_image(&win->buffer, bounds, &img, nk_rgb_factor(nk_white, style->combo.color_factor)); /* draw open/close button */ if (draw_button_symbol) @@ -556,7 +563,7 @@ nk_combo_begin_image_text(struct nk_context *ctx, const char *selected, int len, s = nk_widget(&header, ctx); if (!s) return 0; - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; + in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; @@ -572,19 +579,21 @@ nk_combo_begin_image_text(struct nk_context *ctx, const char *selected, int len, text.text = style->combo.label_normal; } + text.text = nk_rgb_factor(text.text, style->combo.color_factor); + switch(background->type) { case NK_STYLE_ITEM_IMAGE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); + nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_COLOR: text.background = background->data.color; - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); + nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor)); + nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor)); break; } { @@ -623,7 +632,7 @@ nk_combo_begin_image_text(struct nk_context *ctx, const char *selected, int len, image.y = header.y + style->combo.content_padding.y; image.h = header.h - 2 * style->combo.content_padding.y; image.w = image.h; - nk_draw_image(&win->buffer, image, &img, nk_white); + nk_draw_image(&win->buffer, image, &img, nk_rgb_factor(nk_white, style->combo.color_factor)); /* draw label */ text.padding = nk_vec2(0,0); diff --git a/src/nuklear_contextual.c b/src/nuklear_contextual.c index 6d9358f..f3e7db0 100644 --- a/src/nuklear_contextual.c +++ b/src/nuklear_contextual.c @@ -13,6 +13,7 @@ nk_contextual_begin(struct nk_context *ctx, nk_flags flags, struct nk_vec2 size, struct nk_window *win; struct nk_window *popup; struct nk_rect body; + struct nk_input* in; NK_STORAGE const struct nk_rect null_rect = {-1,-1,0,0}; int is_clicked = 0; @@ -33,35 +34,39 @@ nk_contextual_begin(struct nk_context *ctx, nk_flags flags, struct nk_vec2 size, /* check if currently active contextual is active */ popup = win->popup.win; is_open = (popup && win->popup.type == NK_PANEL_CONTEXTUAL); - is_clicked = nk_input_mouse_clicked(&ctx->input, NK_BUTTON_RIGHT, trigger_bounds); - if (win->popup.active_con && win->popup.con_count != win->popup.active_con) - return 0; - if (!is_open && win->popup.active_con) - win->popup.active_con = 0; - if ((!is_open && !is_clicked)) - return 0; + in = win->widgets_disabled ? 0 : &ctx->input; + if (in) { + is_clicked = nk_input_mouse_clicked(in, NK_BUTTON_RIGHT, trigger_bounds); + if (win->popup.active_con && win->popup.con_count != win->popup.active_con) + return 0; + if (!is_open && win->popup.active_con) + win->popup.active_con = 0; + if ((!is_open && !is_clicked)) + return 0; - /* calculate contextual position on click */ - win->popup.active_con = win->popup.con_count; - if (is_clicked) { - body.x = ctx->input.mouse.pos.x; - body.y = ctx->input.mouse.pos.y; - } else { - body.x = popup->bounds.x; - body.y = popup->bounds.y; - } - body.w = size.x; - body.h = size.y; + /* calculate contextual position on click */ + win->popup.active_con = win->popup.con_count; + if (is_clicked) { + body.x = in->mouse.pos.x; + body.y = in->mouse.pos.y; + } else { + body.x = popup->bounds.x; + body.y = popup->bounds.y; + } - /* start nonblocking contextual popup */ - ret = nk_nonblock_begin(ctx, flags|NK_WINDOW_NO_SCROLLBAR, body, + body.w = size.x; + body.h = size.y; + + /* start nonblocking contextual popup */ + ret = nk_nonblock_begin(ctx, flags | NK_WINDOW_NO_SCROLLBAR, body, null_rect, NK_PANEL_CONTEXTUAL); - if (ret) win->popup.type = NK_PANEL_CONTEXTUAL; - else { - win->popup.active_con = 0; - win->popup.type = NK_PANEL_NONE; - if (win->popup.win) - win->popup.win->flags = 0; + if (ret) win->popup.type = NK_PANEL_CONTEXTUAL; + else { + win->popup.active_con = 0; + win->popup.type = NK_PANEL_NONE; + if (win->popup.win) + win->popup.win->flags = 0; + } } return ret; } diff --git a/src/nuklear_edit.c b/src/nuklear_edit.c index 8cab48e..4157dd8 100644 --- a/src/nuklear_edit.c +++ b/src/nuklear_edit.c @@ -89,6 +89,9 @@ nk_edit_draw_text(struct nk_command_buffer *out, float line_offset = 0; int line_count = 0; + foreground = nk_rgb_factor(foreground, style->color_factor); + background = nk_rgb_factor(background, style->color_factor); + struct nk_text txt; txt.padding = nk_vec2(0,0); txt.background = background; @@ -331,14 +334,14 @@ nk_do_edit(nk_flags *state, struct nk_command_buffer *out, /* draw background frame */ switch(background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, bounds, &background->data.image, nk_white); + nk_draw_image(out, bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(out, bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, bounds, style->rounding, background->data.color); - nk_stroke_rect(out, bounds, style->rounding, style->border, style->border_color); + nk_fill_rect(out, bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); + nk_stroke_rect(out, bounds, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor)); break; }} @@ -547,6 +550,8 @@ nk_do_edit(nk_flags *state, struct nk_command_buffer *out, else background_color = background->data.color; + cursor_color = nk_rgb_factor(cursor_color, style->color_factor); + cursor_text_color = nk_rgb_factor(cursor_text_color, style->color_factor); if (edit->select_start == edit->select_end) { /* no selection so just draw the complete text */ @@ -654,6 +659,10 @@ nk_do_edit(nk_flags *state, struct nk_command_buffer *out, background_color = nk_rgba(0,0,0,0); else background_color = background->data.color; + + background_color = nk_rgb_factor(background_color, style->color_factor); + text_color = nk_rgb_factor(text_color, style->color_factor); + nk_edit_draw_text(out, style, area.x - edit->scrollbar.x, area.y - edit->scrollbar.y, 0, begin, l, row_height, font, background_color, text_color, nk_false); @@ -773,6 +782,8 @@ nk_edit_buffer(struct nk_context *ctx, nk_flags flags, style = &ctx->style; state = nk_widget(&bounds, ctx); if (!state) return state; + else if (state == NK_WIDGET_DISABLED) + flags |= NK_EDIT_READ_ONLY; in = (win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; /* check if edit is currently hot item */ diff --git a/src/nuklear_menu.c b/src/nuklear_menu.c index 60fe692..00ec5e1 100644 --- a/src/nuklear_menu.c +++ b/src/nuklear_menu.c @@ -128,7 +128,7 @@ nk_menu_begin_text(struct nk_context *ctx, const char *title, int len, win = ctx->current; state = nk_widget(&header, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || win->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_text(&ctx->last_widget_state, &win->buffer, header, title, len, align, NK_BUTTON_DEFAULT, &ctx->style.menu_button, in, ctx->style.font)) is_clicked = nk_true; @@ -158,7 +158,7 @@ nk_menu_begin_image(struct nk_context *ctx, const char *id, struct nk_image img, win = ctx->current; state = nk_widget(&header, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_image(&ctx->last_widget_state, &win->buffer, header, img, NK_BUTTON_DEFAULT, &ctx->style.menu_button, in)) is_clicked = nk_true; @@ -183,7 +183,7 @@ nk_menu_begin_symbol(struct nk_context *ctx, const char *id, win = ctx->current; state = nk_widget(&header, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_symbol(&ctx->last_widget_state, &win->buffer, header, sym, NK_BUTTON_DEFAULT, &ctx->style.menu_button, in, ctx->style.font)) is_clicked = nk_true; @@ -208,7 +208,7 @@ nk_menu_begin_image_text(struct nk_context *ctx, const char *title, int len, win = ctx->current; state = nk_widget(&header, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_text_image(&ctx->last_widget_state, &win->buffer, header, img, title, len, align, NK_BUTTON_DEFAULT, &ctx->style.menu_button, ctx->style.font, in)) @@ -241,7 +241,7 @@ nk_menu_begin_symbol_text(struct nk_context *ctx, const char *title, int len, state = nk_widget(&header, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_text_symbol(&ctx->last_widget_state, &win->buffer, header, sym, title, len, align, NK_BUTTON_DEFAULT, &ctx->style.menu_button, ctx->style.font, in)) is_clicked = nk_true; diff --git a/src/nuklear_progress.c b/src/nuklear_progress.c index 65578ca..4f487d7 100644 --- a/src/nuklear_progress.c +++ b/src/nuklear_progress.c @@ -62,28 +62,28 @@ nk_draw_progress(struct nk_command_buffer *out, nk_flags state, /* draw background */ switch(background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, *bounds, &background->data.image, nk_white); + nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, *bounds, style->rounding, background->data.color); - nk_stroke_rect(out, *bounds, style->rounding, style->border, style->border_color); + nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); + nk_stroke_rect(out, *bounds, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor)); break; } /* draw cursor */ switch(cursor->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, *scursor, &cursor->data.image, nk_white); + nk_draw_image(out, *scursor, &cursor->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, *scursor, &cursor->data.slice, nk_white); + nk_draw_nine_slice(out, *scursor, &cursor->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, *scursor, style->rounding, cursor->data.color); - nk_stroke_rect(out, *scursor, style->rounding, style->border, style->border_color); + nk_fill_rect(out, *scursor, style->rounding, nk_rgb_factor(cursor->data.color, style->color_factor)); + nk_stroke_rect(out, *scursor, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor)); break; } } @@ -143,7 +143,7 @@ nk_progress(struct nk_context *ctx, nk_size *cur, nk_size max, nk_bool is_modify state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; old_value = *cur; *cur = nk_do_progress(&ctx->last_widget_state, &win->buffer, bounds, *cur, max, is_modifyable, &style->progress, in); diff --git a/src/nuklear_property.c b/src/nuklear_property.c index 3470873..2a34eb7 100644 --- a/src/nuklear_property.c +++ b/src/nuklear_property.c @@ -85,20 +85,22 @@ nk_draw_property(struct nk_command_buffer *out, const struct nk_style_property * text.text = style->label_normal; } + text.text = nk_rgb_factor(text.text, style->color_factor); + /* draw background */ switch(background->type) { case NK_STYLE_ITEM_IMAGE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_image(out, *bounds, &background->data.image, nk_white); + nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: text.background = background->data.color; - nk_fill_rect(out, *bounds, style->rounding, background->data.color); - nk_stroke_rect(out, *bounds, style->rounding, style->border, background->data.color); + nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); + nk_stroke_rect(out, *bounds, style->rounding, style->border, nk_rgb_factor(background->data.color, style->color_factor)); break; } @@ -383,7 +385,7 @@ nk_property(struct nk_context *ctx, const char *name, struct nk_property_variant old_state = *state; ctx->text_edit.clip = ctx->clip; in = ((s == NK_WIDGET_ROM && !win->property.active) || - layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED) ? 0 : &ctx->input; nk_do_property(&ctx->last_widget_state, &win->buffer, bounds, name, variant, inc_per_pixel, buffer, len, state, cursor, select_begin, select_end, &style->property, filter, in, style->font, &ctx->text_edit, diff --git a/src/nuklear_selectable.c b/src/nuklear_selectable.c index e5f7278..3f4bfc4 100644 --- a/src/nuklear_selectable.c +++ b/src/nuklear_selectable.c @@ -41,23 +41,26 @@ nk_draw_selectable(struct nk_command_buffer *out, text.text = style->text_normal_active; } } + + text.text = nk_rgb_factor(text.text, style->color_factor); + /* draw selectable background and text */ switch (background->type) { case NK_STYLE_ITEM_IMAGE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_image(out, *bounds, &background->data.image, nk_white); + nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: text.background = background->data.color; - nk_fill_rect(out, *bounds, style->rounding, background->data.color); + nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); break; } if (icon) { - if (img) nk_draw_image(out, *icon, img, nk_white); + if (img) nk_draw_image(out, *icon, img, nk_rgb_factor(nk_white, style->color_factor)); else nk_draw_symbol(out, sym, *icon, text.background, text.text, 1, font); } nk_widget_text(out, *bounds, string, len, &text, align, font); @@ -218,7 +221,7 @@ nk_selectable_text(struct nk_context *ctx, const char *str, int len, state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_selectable(&ctx->last_widget_state, &win->buffer, bounds, str, len, align, value, &style->selectable, in, style->font); } @@ -247,7 +250,7 @@ nk_selectable_image_text(struct nk_context *ctx, struct nk_image img, state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_selectable_image(&ctx->last_widget_state, &win->buffer, bounds, str, len, align, value, &img, &style->selectable, in, style->font); } @@ -276,7 +279,7 @@ nk_selectable_symbol_text(struct nk_context *ctx, enum nk_symbol_type sym, state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_selectable_symbol(&ctx->last_widget_state, &win->buffer, bounds, str, len, align, value, sym, &style->selectable, in, style->font); } diff --git a/src/nuklear_slider.c b/src/nuklear_slider.c index 188f7f4..872cbd1 100644 --- a/src/nuklear_slider.c +++ b/src/nuklear_slider.c @@ -78,6 +78,7 @@ nk_draw_slider(struct nk_command_buffer *out, nk_flags state, bar_color = style->bar_normal; cursor = &style->cursor_normal; } + /* calculate slider background bar */ bar.x = bounds->x; bar.y = (visual_cursor->y + visual_cursor->h/2) - bounds->h/12; @@ -93,26 +94,26 @@ nk_draw_slider(struct nk_command_buffer *out, nk_flags state, /* draw background */ switch(background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, *bounds, &background->data.image, nk_white); + nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, *bounds, style->rounding, background->data.color); - nk_stroke_rect(out, *bounds, style->rounding, style->border, style->border_color); + nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); + nk_stroke_rect(out, *bounds, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor)); break; } /* draw slider bar */ - nk_fill_rect(out, bar, style->rounding, bar_color); - nk_fill_rect(out, fill, style->rounding, style->bar_filled); + nk_fill_rect(out, bar, style->rounding, nk_rgb_factor(bar_color, style->color_factor)); + nk_fill_rect(out, fill, style->rounding, nk_rgb_factor(style->bar_filled, style->color_factor)); /* draw cursor */ if (cursor->type == NK_STYLE_ITEM_IMAGE) - nk_draw_image(out, *visual_cursor, &cursor->data.image, nk_white); + nk_draw_image(out, *visual_cursor, &cursor->data.image, nk_rgb_factor(nk_white, style->color_factor)); else - nk_fill_circle(out, *visual_cursor, cursor->data.color); + nk_fill_circle(out, *visual_cursor, nk_rgb_factor(cursor->data.color, style->color_factor)); } NK_LIB float nk_do_slider(nk_flags *state, @@ -230,7 +231,7 @@ nk_slider_float(struct nk_context *ctx, float min_value, float *value, float max state = nk_widget(&bounds, ctx); if (!state) return ret; - in = (/*state == NK_WIDGET_ROM || */ layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (/*state == NK_WIDGET_ROM || */ state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; old_value = *value; *value = nk_do_slider(&ctx->last_widget_state, &win->buffer, bounds, min_value, diff --git a/src/nuklear_style.c b/src/nuklear_style.c index 0e0851e..be9026b 100644 --- a/src/nuklear_style.c +++ b/src/nuklear_style.c @@ -113,6 +113,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) text = &style->text; text->color = table[NK_COLOR_TEXT]; text->padding = nk_vec2(0,0); + text->color_factor = 1.0f; + text->disabled_factor = 0.5f; /* default button */ button = &style->button; @@ -132,6 +134,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 1.0f; button->rounding = 4.0f; + button->color_factor = 1.0f; + button->disabled_factor = 0.5f; button->draw_begin = 0; button->draw_end = 0; @@ -152,6 +156,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor = 1.0f; + button->disabled_factor = 0.5f; button->draw_begin = 0; button->draw_end = 0; @@ -172,6 +178,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 1.0f; + button->color_factor = 1.0f; + button->disabled_factor = 0.5f; button->draw_begin = 0; button->draw_end = 0; @@ -193,6 +201,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) toggle->border_color = nk_rgba(0,0,0,0); toggle->border = 0.0f; toggle->spacing = 4; + toggle->color_factor = 1.0f; + toggle->disabled_factor = 0.5f; /* option toggle */ toggle = &style->option; @@ -212,6 +222,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) toggle->border_color = nk_rgba(0,0,0,0); toggle->border = 0.0f; toggle->spacing = 4; + toggle->color_factor = 1.0f; + toggle->disabled_factor = 0.5f; /* selectable */ select = &style->selectable; @@ -233,6 +245,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) select->touch_padding = nk_vec2(0,0); select->userdata = nk_handle_ptr(0); select->rounding = 0.0f; + select->color_factor = 1.0f; + select->disabled_factor = 0.5f; select->draw_begin = 0; select->draw_end = 0; @@ -258,6 +272,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) slider->show_buttons = nk_false; slider->bar_height = 8; slider->rounding = 0; + slider->color_factor = 1.0f; + slider->disabled_factor = 0.5f; slider->draw_begin = 0; slider->draw_end = 0; @@ -277,6 +293,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 1.0f; button->rounding = 0.0f; + button->color_factor = 1.0f; + button->disabled_factor = 0.5f; button->draw_begin = 0; button->draw_end = 0; style->slider.dec_button = style->slider.inc_button; @@ -298,6 +316,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) prog->border = 0; prog->cursor_rounding = 0; prog->cursor_border = 0; + prog->color_factor = 1.0f; + prog->disabled_factor = 0.5f; prog->draw_begin = 0; prog->draw_end = 0; @@ -321,6 +341,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) scroll->rounding = 0; scroll->border_cursor = 0; scroll->rounding_cursor = 0; + scroll->color_factor = 1.0f; + scroll->disabled_factor = 0.5f; scroll->draw_begin = 0; scroll->draw_end = 0; style->scrollv = style->scrollh; @@ -341,6 +363,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 1.0f; button->rounding = 0.0f; + button->color_factor = 1.0f; + button->disabled_factor = 0.5f; button->draw_begin = 0; button->draw_end = 0; style->scrollh.dec_button = style->scrollh.inc_button; @@ -372,6 +396,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) edit->cursor_size = 4; edit->border = 1; edit->rounding = 0; + edit->color_factor = 1.0f; + edit->disabled_factor = 0.5f; /* property */ property = &style->property; @@ -391,6 +417,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) property->rounding = 10; property->draw_begin = 0; property->draw_end = 0; + property->color_factor = 1.0f; + property->disabled_factor = 0.5f; /* property buttons */ button = &style->property.dec_button; @@ -409,6 +437,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor = 1.0f; + button->disabled_factor = 0.5f; button->draw_begin = 0; button->draw_end = 0; style->property.inc_button = style->property.dec_button; @@ -435,6 +465,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) edit->cursor_size = 8; edit->border = 0; edit->rounding = 0; + edit->color_factor = 1.0f; + edit->disabled_factor = 0.5f; /* chart */ chart = &style->chart; @@ -446,6 +478,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) chart->padding = nk_vec2(4,4); chart->border = 0; chart->rounding = 0; + chart->color_factor = 1.0f; + chart->disabled_factor = 0.5f; /* combo */ combo = &style->combo; @@ -464,6 +498,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) combo->spacing = nk_vec2(4,0); combo->border = 1; combo->rounding = 0; + combo->color_factor = 1.0f; + combo->disabled_factor = 0.5f; /* combo button */ button = &style->combo.button; @@ -482,6 +518,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor = 1.0f; + button->disabled_factor = 0.5f; button->draw_begin = 0; button->draw_end = 0; @@ -497,6 +535,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) tab->indent = 10.0f; tab->border = 1; tab->rounding = 0; + tab->color_factor = 1.0f; + tab->disabled_factor = 0.5f; /* tab button */ button = &style->tab.tab_minimize_button; @@ -515,6 +555,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor = 1.0f; + button->disabled_factor = 0.5f; button->draw_begin = 0; button->draw_end = 0; style->tab.tab_maximize_button =*button; @@ -536,6 +578,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor = 1.0f; + button->disabled_factor = 0.5f; button->draw_begin = 0; button->draw_end = 0; style->tab.node_maximize_button =*button; @@ -573,6 +617,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor = 1.0f; + button->disabled_factor = 0.5f; button->draw_begin = 0; button->draw_end = 0; @@ -593,6 +639,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor = 1.0f; + button->disabled_factor = 0.5f; button->draw_begin = 0; button->draw_end = 0; diff --git a/src/nuklear_text.c b/src/nuklear_text.c index 1ed967e..3df9149 100644 --- a/src/nuklear_text.c +++ b/src/nuklear_text.c @@ -114,7 +114,7 @@ nk_text_colored(struct nk_context *ctx, const char *str, int len, text.padding.x = item_padding.x; text.padding.y = item_padding.y; text.background = style->window.background; - text.text = color; + text.text = nk_rgb_factor(color, style->text.color_factor); nk_widget_text(&win->buffer, bounds, str, len, &text, alignment, style->font); } NK_API void @@ -141,7 +141,7 @@ nk_text_wrap_colored(struct nk_context *ctx, const char *str, text.padding.x = item_padding.x; text.padding.y = item_padding.y; text.background = style->window.background; - text.text = color; + text.text = nk_rgb_factor(color, style->text.color_factor); nk_widget_text_wrap(&win->buffer, bounds, str, len, &text, style->font); } #ifdef NK_INCLUDE_STANDARD_VARARGS diff --git a/src/nuklear_toggle.c b/src/nuklear_toggle.c index 0644a80..41121c3 100644 --- a/src/nuklear_toggle.c +++ b/src/nuklear_toggle.c @@ -47,14 +47,16 @@ nk_draw_checkbox(struct nk_command_buffer *out, text.text = style->text_normal; } + text.text = nk_rgb_factor(text.text, style->color_factor); + /* draw background and cursor */ if (background->type == NK_STYLE_ITEM_COLOR) { - nk_fill_rect(out, *selector, 0, style->border_color); - nk_fill_rect(out, nk_shrink_rect(*selector, style->border), 0, background->data.color); - } else nk_draw_image(out, *selector, &background->data.image, nk_white); + nk_fill_rect(out, *selector, 0, nk_rgb_factor(style->border_color, style->color_factor)); + nk_fill_rect(out, nk_shrink_rect(*selector, style->border), 0, nk_rgb_factor(background->data.color, style->color_factor)); + } else nk_draw_image(out, *selector, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); if (active) { if (cursor->type == NK_STYLE_ITEM_IMAGE) - nk_draw_image(out, *cursors, &cursor->data.image, nk_white); + nk_draw_image(out, *cursors, &cursor->data.image, nk_rgb_factor(nk_white, style->color_factor)); else nk_fill_rect(out, *cursors, 0, cursor->data.color); } @@ -89,14 +91,16 @@ nk_draw_option(struct nk_command_buffer *out, text.text = style->text_normal; } + text.text = nk_rgb_factor(text.text, style->color_factor); + /* draw background and cursor */ if (background->type == NK_STYLE_ITEM_COLOR) { - nk_fill_circle(out, *selector, style->border_color); - nk_fill_circle(out, nk_shrink_rect(*selector, style->border), background->data.color); - } else nk_draw_image(out, *selector, &background->data.image, nk_white); + nk_fill_circle(out, *selector, nk_rgb_factor(style->border_color, style->color_factor)); + nk_fill_circle(out, nk_shrink_rect(*selector, style->border), nk_rgb_factor(background->data.color, style->color_factor)); + } else nk_draw_image(out, *selector, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); if (active) { if (cursor->type == NK_STYLE_ITEM_IMAGE) - nk_draw_image(out, *cursors, &cursor->data.image, nk_white); + nk_draw_image(out, *cursors, &cursor->data.image, nk_rgb_factor(nk_white, style->color_factor)); else nk_fill_circle(out, *cursors, cursor->data.color); } @@ -195,7 +199,7 @@ nk_check_text(struct nk_context *ctx, const char *text, int len, nk_bool active) state = nk_widget(&bounds, ctx); if (!state) return active; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &active, text, len, NK_TOGGLE_CHECK, &style->checkbox, in, style->font); return active; @@ -290,7 +294,7 @@ nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_act state = nk_widget(&bounds, ctx); if (!state) return (int)state; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &is_active, text, len, NK_TOGGLE_OPTION, &style->option, in, style->font); return is_active; diff --git a/src/nuklear_widget.c b/src/nuklear_widget.c index 2e78cd5..f2a243c 100644 --- a/src/nuklear_widget.c +++ b/src/nuklear_widget.c @@ -175,6 +175,8 @@ nk_widget(struct nk_rect *bounds, const struct nk_context *ctx) nk_unify(&v, &c, bounds->x, bounds->y, bounds->x + bounds->w, bounds->y + bounds->h); if (!NK_INTERSECT(c.x, c.y, c.w, c.h, bounds->x, bounds->y, bounds->w, bounds->h)) return NK_WIDGET_INVALID; + if (win->widgets_disabled) + return NK_WIDGET_DISABLED; if (!NK_INBOX(in->mouse.pos.x, in->mouse.pos.y, v.x, v.y, v.w, v.h)) return NK_WIDGET_ROM; return NK_WIDGET_VALID; @@ -227,4 +229,101 @@ nk_spacing(struct nk_context *ctx, int cols) nk_panel_alloc_space(&none, ctx); } layout->row.index = index; } +NK_API void +nk_widget_disable_begin(struct nk_context* ctx) +{ + struct nk_window* win; + struct nk_style* style; + NK_ASSERT(ctx); + NK_ASSERT(ctx->current); + + if (!ctx || !ctx->current) + return; + + win = ctx->current; + style = &ctx->style; + + win->widgets_disabled = nk_true; + + style->button.color_factor = style->button.disabled_factor; + style->chart.color_factor = style->chart.disabled_factor; + style->checkbox.color_factor = style->checkbox.disabled_factor; + style->combo.color_factor = style->combo.disabled_factor; + style->combo.button.color_factor = style->combo.button.disabled_factor; + style->contextual_button.color_factor = style->contextual_button.disabled_factor; + style->edit.color_factor = style->edit.disabled_factor; + style->edit.scrollbar.color_factor = style->edit.scrollbar.disabled_factor; + style->menu_button.color_factor = style->menu_button.disabled_factor; + style->option.color_factor = style->option.disabled_factor; + style->progress.color_factor = style->progress.disabled_factor; + style->property.color_factor = style->property.disabled_factor; + style->property.inc_button.color_factor = style->property.inc_button.disabled_factor; + style->property.dec_button.color_factor = style->property.dec_button.disabled_factor; + style->property.edit.color_factor = style->property.edit.disabled_factor; + style->scrollh.color_factor = style->scrollh.disabled_factor; + style->scrollh.inc_button.color_factor = style->scrollh.inc_button.disabled_factor; + style->scrollh.dec_button.color_factor = style->scrollh.dec_button.disabled_factor; + style->scrollv.color_factor = style->scrollv.disabled_factor; + style->scrollv.inc_button.color_factor = style->scrollv.inc_button.disabled_factor; + style->scrollv.dec_button.color_factor = style->scrollv.dec_button.disabled_factor; + style->selectable.color_factor = style->selectable.disabled_factor; + style->slider.color_factor = style->slider.disabled_factor; + style->slider.inc_button.color_factor = style->slider.inc_button.disabled_factor; + style->slider.dec_button.color_factor = style->slider.dec_button.disabled_factor; + style->tab.color_factor = style->tab.disabled_factor; + style->tab.node_maximize_button.color_factor = style->tab.node_maximize_button.disabled_factor; + style->tab.node_minimize_button.color_factor = style->tab.node_minimize_button.disabled_factor; + style->tab.tab_maximize_button.color_factor = style->tab.tab_maximize_button.disabled_factor; + style->tab.tab_minimize_button.color_factor = style->tab.tab_minimize_button.disabled_factor; + style->text.color_factor = style->text.disabled_factor; +} +NK_API void +nk_widget_disable_end(struct nk_context* ctx) +{ + struct nk_window* win; + struct nk_style* style; + + NK_ASSERT(ctx); + NK_ASSERT(ctx->current); + + if (!ctx || !ctx->current) + return; + + win = ctx->current; + style = &ctx->style; + + win->widgets_disabled = nk_false; + + style->button.color_factor = 1.0f; + style->chart.color_factor = 1.0f; + style->checkbox.color_factor = 1.0f; + style->combo.color_factor = 1.0f; + style->combo.button.color_factor = 1.0f; + style->contextual_button.color_factor = 1.0f; + style->edit.color_factor = 1.0f; + style->edit.scrollbar.color_factor = 1.0f; + style->menu_button.color_factor = 1.0f; + style->option.color_factor = 1.0f; + style->progress.color_factor = 1.0f; + style->property.color_factor = 1.0f; + style->property.inc_button.color_factor = 1.0f; + style->property.dec_button.color_factor = 1.0f; + style->property.edit.color_factor = 1.0f; + style->scrollh.color_factor = 1.0f; + style->scrollh.inc_button.color_factor = 1.0f; + style->scrollh.dec_button.color_factor = 1.0f; + style->scrollv.color_factor = 1.0f; + style->scrollv.inc_button.color_factor = 1.0f; + style->scrollv.dec_button.color_factor = 1.0f; + style->selectable.color_factor = 1.0f; + style->slider.color_factor = 1.0f; + style->slider.inc_button.color_factor = 1.0f; + style->slider.dec_button.color_factor = 1.0f; + style->tab.color_factor = 1.0f; + style->tab.node_maximize_button.color_factor = 1.0f; + style->tab.node_minimize_button.color_factor = 1.0f; + style->tab.tab_maximize_button.color_factor = 1.0f; + style->tab.tab_minimize_button.color_factor = 1.0f; + style->text.color_factor = 1.0f; +} diff --git a/src/nuklear_window.c b/src/nuklear_window.c index 486b912..240604d 100644 --- a/src/nuklear_window.c +++ b/src/nuklear_window.c @@ -180,6 +180,7 @@ nk_begin_titled(struct nk_context *ctx, const char *name, const char *title, NK_MEMCPY(win->name_string, name, name_length); win->name_string[name_length] = 0; win->popup.win = 0; + win->widgets_disabled = false; if (!ctx->active) ctx->active = win; } else { From 25cda15319d77c53ef763a233c7801381057caab Mon Sep 17 00:00:00 2001 From: Yukyduky Date: Fri, 13 Oct 2023 11:48:59 +0200 Subject: [PATCH 048/106] Fixed two copy paste mistakes --- nuklear.h | 5 +++-- src/nuklear_button.c | 2 +- src/nuklear_chart.c | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/nuklear.h b/nuklear.h index 0d9b9a2..0604017 100644 --- a/nuklear.h +++ b/nuklear.h @@ -24023,7 +24023,7 @@ nk_draw_button(struct nk_command_buffer *out, nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_rgb_factor(nk_white, style->color_factor), style->color_factor)); + nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); @@ -28421,7 +28421,7 @@ nk_chart_begin_colored(struct nk_context *ctx, enum nk_chart_type type, nk_draw_image(&win->buffer, bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_image(&win->buffer, bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); + nk_draw_nine_slice(&win->buffer, bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: nk_fill_rect(&win->buffer, bounds, style->rounding, nk_rgb_factor(style->border_color, style->color_factor)); @@ -29905,6 +29905,7 @@ nk_tooltipfv(struct nk_context *ctx, const char *fmt, va_list args) /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// +/// - 2023/10/11 (4.11.0) - Added nk_widget_disable_begin() and nk_widget_disable_end() /// - 2022/12/23 (4.10.6) - Fix incorrect glyph index in nk_font_bake() /// - 2022/12/17 (4.10.5) - Fix nk_font_bake_pack() using TTC font offset incorrectly /// - 2022/10/24 (4.10.4) - Fix nk_str_{append,insert}_str_utf8 always returning 0 diff --git a/src/nuklear_button.c b/src/nuklear_button.c index 98c2057..423e0df 100644 --- a/src/nuklear_button.c +++ b/src/nuklear_button.c @@ -103,7 +103,7 @@ nk_draw_button(struct nk_command_buffer *out, nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_rgb_factor(nk_white, style->color_factor), style->color_factor)); + nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); diff --git a/src/nuklear_chart.c b/src/nuklear_chart.c index ba886e2..b71caf2 100644 --- a/src/nuklear_chart.c +++ b/src/nuklear_chart.c @@ -62,7 +62,7 @@ nk_chart_begin_colored(struct nk_context *ctx, enum nk_chart_type type, nk_draw_image(&win->buffer, bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_image(&win->buffer, bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); + nk_draw_nine_slice(&win->buffer, bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: nk_fill_rect(&win->buffer, bounds, style->rounding, nk_rgb_factor(style->border_color, style->color_factor)); From 6319e8f787f4d33d4378e08dfc9234b249ffdf7f Mon Sep 17 00:00:00 2001 From: Andrew Kravchuk Date: Mon, 16 Oct 2023 14:01:07 +0200 Subject: [PATCH 049/106] Fixed broken link in Allegro5 backend readme --- demo/allegro5/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demo/allegro5/Readme.md b/demo/allegro5/Readme.md index 71a4840..e5dcce2 100644 --- a/demo/allegro5/Readme.md +++ b/demo/allegro5/Readme.md @@ -1,6 +1,6 @@ # Allegro v5 nuklear backend -This backend provides support for [Allegro version 5](http://liballeg.org/). It works on on all supported platforms with an OpenGL backend, including iOS and Android. +This backend provides support for [Allegro version 5](https://liballeg.github.io). It works on on all supported platforms with an OpenGL backend, including iOS and Android. Touch support is provided by handling the first touch (ignoring any extra simultaneous touches) and emitting nuklear mouse events. nuklear will handle only the first touch like a single left-mouse click. Dragging the touch screen emits mouse-move events. From 2ec96be4b94a51da9604ff00a0120127df5fdf56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wladislav=20=E3=83=B4=E3=83=A9=E3=83=89=20Artsimovich?= Date: Tue, 17 Oct 2023 11:37:30 +0900 Subject: [PATCH 050/106] Add horizontal rule demo --- demo/common/overview.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/demo/common/overview.c b/demo/common/overview.c index 86cb9f2..00042d5 100644 --- a/demo/common/overview.c +++ b/demo/common/overview.c @@ -590,6 +590,18 @@ overview(struct nk_context *ctx) } nk_tree_pop(ctx); } + + if (nk_tree_push(ctx, NK_TREE_NODE, "Horizontal Rule", NK_MINIMIZED)) + { + nk_layout_row_dynamic(ctx, 12, 1); + nk_label(ctx, "Use this subdivide spaces visually", NK_TEXT_LEFT); + nk_layout_row_dynamic(ctx, 4, 1); + nk_rule_horizontal(ctx, nk_white, nk_true); + nk_layout_row_dynamic(ctx, 75, 1); + nk_label_wrap(ctx, "Best used in 'Card' layouts, with a bigger title font on top. Takes on the size of the previous layout definition. Rounding optional."); + nk_tree_pop(ctx); + } + nk_tree_pop(ctx); } From 7384f0ed673ca92b2b056c9f54c203406188bb0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wladislav=20=E3=83=B4=E3=83=A9=E3=83=89=20Artsimovich?= Date: Tue, 17 Oct 2023 11:41:11 +0900 Subject: [PATCH 051/106] Regenerate Nuklear.h --- nuklear.h | 1 + 1 file changed, 1 insertion(+) diff --git a/nuklear.h b/nuklear.h index ec03865..06e7fee 100644 --- a/nuklear.h +++ b/nuklear.h @@ -29702,6 +29702,7 @@ nk_tooltipfv(struct nk_context *ctx, const char *fmt, va_list args) /// - 2022/08/01 (4.10.1) - Fix cursor jumping back to beginning of text when typing more than /// nk_edit_xxx limit /// - 2022/05/27 (4.10.0) - Add nk_input_has_mouse_click_in_button_rect() to fix window move bug +/// - 2022/04/19 (4.9.8) - Added nk_rule_horizontal() widget /// - 2022/04/18 (4.9.7) - Change button behavior when NK_BUTTON_TRIGGER_ON_RELEASE is defined to /// only trigger when the mouse position was inside the same button on down /// - 2022/02/03 (4.9.6) - Allow overriding the NK_INV_SQRT function, similar to NK_SIN and NK_COS From 57d1f210561a943cf786bf70526c4a0a608a8712 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wladislav=20=E3=83=B4=E3=83=A9=E3=83=89=20Artsimovich?= Date: Tue, 17 Oct 2023 11:43:21 +0900 Subject: [PATCH 052/106] Fix demo typo --- demo/common/overview.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/demo/common/overview.c b/demo/common/overview.c index 00042d5..ab66c84 100644 --- a/demo/common/overview.c +++ b/demo/common/overview.c @@ -594,11 +594,11 @@ overview(struct nk_context *ctx) if (nk_tree_push(ctx, NK_TREE_NODE, "Horizontal Rule", NK_MINIMIZED)) { nk_layout_row_dynamic(ctx, 12, 1); - nk_label(ctx, "Use this subdivide spaces visually", NK_TEXT_LEFT); + nk_label(ctx, "Use this to subdivide spaces visually", NK_TEXT_LEFT); nk_layout_row_dynamic(ctx, 4, 1); nk_rule_horizontal(ctx, nk_white, nk_true); nk_layout_row_dynamic(ctx, 75, 1); - nk_label_wrap(ctx, "Best used in 'Card' layouts, with a bigger title font on top. Takes on the size of the previous layout definition. Rounding optional."); + nk_label_wrap(ctx, "Best used in 'Card'-like layouts, with a bigger title font on top. Takes on the size of the previous layout definition. Rounding optional."); nk_tree_pop(ctx); } From bed81e2f4e810d833a56dd2139d353ed93924bee Mon Sep 17 00:00:00 2001 From: Rob Loach Date: Tue, 17 Oct 2023 01:57:25 -0400 Subject: [PATCH 053/106] Allow disabling STB_*_IMPLEMENTATION (#578) When having stb_rect_pack or stb_truetype used elsewhere in your project, Nuklear could cause conflicts. This change adds `NK_NO_STB_RECT_PACK_IMPLEMENTATION` or `NK_NO_STB_TRUETYPE_IMPLEMENTATION` to allow disabling adding `STB_RECT_PACK_IMPLEMENTATION` or `STB_TRUETYPE_IMPLEMENTATION`. --- nuklear.h | 15 +++++++++++++++ src/nuklear_internal.h | 15 +++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/nuklear.h b/nuklear.h index a3b82fa..c2edb75 100644 --- a/nuklear.h +++ b/nuklear.h @@ -6103,8 +6103,23 @@ NK_LIB void nk_property(struct nk_context *ctx, const char *name, struct nk_prop #ifdef NK_INCLUDE_FONT_BAKING +/** + * @def NK_NO_STB_RECT_PACK_IMPLEMENTATION + * + * When defined, will avoid enabling STB_RECT_PACK_IMPLEMENTATION for when stb_rect_pack.h is already implemented elsewhere. + */ +#ifndef NK_NO_STB_RECT_PACK_IMPLEMENTATION #define STB_RECT_PACK_IMPLEMENTATION +#endif /* NK_NO_STB_RECT_PACK_IMPLEMENTATION */ + +/** + * @def NK_NO_STB_TRUETYPE_IMPLEMENTATION + * + * When defined, will avoid enabling STB_TRUETYPE_IMPLEMENTATION for when stb_truetype.h is already implemented elsewhere. + */ +#ifndef NK_NO_STB_TRUETYPE_IMPLEMENTATION #define STB_TRUETYPE_IMPLEMENTATION +#endif /* NK_NO_STB_TRUETYPE_IMPLEMENTATION */ /* Allow consumer to define own STBTT_malloc/STBTT_free, and use the font atlas' allocator otherwise */ #ifndef STBTT_malloc diff --git a/src/nuklear_internal.h b/src/nuklear_internal.h index 8d1b785..4f71f30 100644 --- a/src/nuklear_internal.h +++ b/src/nuklear_internal.h @@ -328,8 +328,23 @@ NK_LIB void nk_property(struct nk_context *ctx, const char *name, struct nk_prop #ifdef NK_INCLUDE_FONT_BAKING +/** + * @def NK_NO_STB_RECT_PACK_IMPLEMENTATION + * + * When defined, will avoid enabling STB_RECT_PACK_IMPLEMENTATION for when stb_rect_pack.h is already implemented elsewhere. + */ +#ifndef NK_NO_STB_RECT_PACK_IMPLEMENTATION #define STB_RECT_PACK_IMPLEMENTATION +#endif /* NK_NO_STB_RECT_PACK_IMPLEMENTATION */ + +/** + * @def NK_NO_STB_TRUETYPE_IMPLEMENTATION + * + * When defined, will avoid enabling STB_TRUETYPE_IMPLEMENTATION for when stb_truetype.h is already implemented elsewhere. + */ +#ifndef NK_NO_STB_TRUETYPE_IMPLEMENTATION #define STB_TRUETYPE_IMPLEMENTATION +#endif /* NK_NO_STB_TRUETYPE_IMPLEMENTATION */ /* Allow consumer to define own STBTT_malloc/STBTT_free, and use the font atlas' allocator otherwise */ #ifndef STBTT_malloc From 5a6569a2c9bde51b2dbe3b62d9a41091ec036adb Mon Sep 17 00:00:00 2001 From: Yukyduky Date: Tue, 17 Oct 2023 20:04:14 +0200 Subject: [PATCH 054/106] Added disabled factor & performance improvement Added NK_WIDGET_DISABLED_FACTOR, global factor for disabled color --- nuklear.h | 67 +++++++++++++++++++++++---------------------- src/nuklear.h | 5 +++- src/nuklear_color.c | 14 +++++----- src/nuklear_style.c | 48 ++++++++++++++++---------------- 4 files changed, 70 insertions(+), 64 deletions(-) diff --git a/nuklear.h b/nuklear.h index dec674b..ec1569e 100644 --- a/nuklear.h +++ b/nuklear.h @@ -3609,6 +3609,9 @@ NK_API void nk_menu_end(struct nk_context*); * STYLE * * ============================================================================= */ + +#define NK_WIDGET_DISABLED_FACTOR 0.5f + enum nk_style_colors { NK_COLOR_TEXT, NK_COLOR_WINDOW, @@ -3685,7 +3688,7 @@ NK_API struct nk_color nk_rgb_f(float r, float g, float b); NK_API struct nk_color nk_rgb_fv(const float *rgb); NK_API struct nk_color nk_rgb_cf(struct nk_colorf c); NK_API struct nk_color nk_rgb_hex(const char *rgb); -NK_API struct nk_color nk_rgb_factor(const struct nk_color col, const float factor); +NK_API struct nk_color nk_rgb_factor(struct nk_color col, const float factor); NK_API struct nk_color nk_rgba(int r, int g, int b, int a); NK_API struct nk_color nk_rgba_u32(nk_uint); @@ -7632,14 +7635,14 @@ nk_parse_hex(const char *p, int length) return i; } NK_API struct nk_color -nk_rgb_factor(const struct nk_color col, const float factor) +nk_rgb_factor(struct nk_color col, const float factor) { - struct nk_color ret; - ret.r = col.r * factor; - ret.g = col.g * factor; - ret.b = col.b * factor; - ret.a = col.a; - return ret; + if (factor == 1.0f) + return col; + col.r *= factor; + col.g *= factor; + col.b *= factor; + return col; } NK_API struct nk_color nk_rgba(int r, int g, int b, int a) @@ -18280,7 +18283,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) text->color = table[NK_COLOR_TEXT]; text->padding = nk_vec2(0,0); text->color_factor = 1.0f; - text->disabled_factor = 0.5f; + text->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* default button */ button = &style->button; @@ -18301,7 +18304,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->border = 1.0f; button->rounding = 4.0f; button->color_factor = 1.0f; - button->disabled_factor = 0.5f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -18323,7 +18326,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->border = 0.0f; button->rounding = 0.0f; button->color_factor = 1.0f; - button->disabled_factor = 0.5f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -18345,7 +18348,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->border = 0.0f; button->rounding = 1.0f; button->color_factor = 1.0f; - button->disabled_factor = 0.5f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -18368,7 +18371,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) toggle->border = 0.0f; toggle->spacing = 4; toggle->color_factor = 1.0f; - toggle->disabled_factor = 0.5f; + toggle->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* option toggle */ toggle = &style->option; @@ -18389,7 +18392,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) toggle->border = 0.0f; toggle->spacing = 4; toggle->color_factor = 1.0f; - toggle->disabled_factor = 0.5f; + toggle->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* selectable */ select = &style->selectable; @@ -18412,7 +18415,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) select->userdata = nk_handle_ptr(0); select->rounding = 0.0f; select->color_factor = 1.0f; - select->disabled_factor = 0.5f; + select->disabled_factor = NK_WIDGET_DISABLED_FACTOR; select->draw_begin = 0; select->draw_end = 0; @@ -18439,7 +18442,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) slider->bar_height = 8; slider->rounding = 0; slider->color_factor = 1.0f; - slider->disabled_factor = 0.5f; + slider->disabled_factor = NK_WIDGET_DISABLED_FACTOR; slider->draw_begin = 0; slider->draw_end = 0; @@ -18460,7 +18463,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->border = 1.0f; button->rounding = 0.0f; button->color_factor = 1.0f; - button->disabled_factor = 0.5f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; style->slider.dec_button = style->slider.inc_button; @@ -18483,7 +18486,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) prog->cursor_rounding = 0; prog->cursor_border = 0; prog->color_factor = 1.0f; - prog->disabled_factor = 0.5f; + prog->disabled_factor = NK_WIDGET_DISABLED_FACTOR; prog->draw_begin = 0; prog->draw_end = 0; @@ -18508,7 +18511,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) scroll->border_cursor = 0; scroll->rounding_cursor = 0; scroll->color_factor = 1.0f; - scroll->disabled_factor = 0.5f; + scroll->disabled_factor = NK_WIDGET_DISABLED_FACTOR; scroll->draw_begin = 0; scroll->draw_end = 0; style->scrollv = style->scrollh; @@ -18530,7 +18533,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->border = 1.0f; button->rounding = 0.0f; button->color_factor = 1.0f; - button->disabled_factor = 0.5f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; style->scrollh.dec_button = style->scrollh.inc_button; @@ -18563,7 +18566,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) edit->border = 1; edit->rounding = 0; edit->color_factor = 1.0f; - edit->disabled_factor = 0.5f; + edit->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* property */ property = &style->property; @@ -18584,7 +18587,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) property->draw_begin = 0; property->draw_end = 0; property->color_factor = 1.0f; - property->disabled_factor = 0.5f; + property->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* property buttons */ button = &style->property.dec_button; @@ -18604,7 +18607,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->border = 0.0f; button->rounding = 0.0f; button->color_factor = 1.0f; - button->disabled_factor = 0.5f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; style->property.inc_button = style->property.dec_button; @@ -18632,7 +18635,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) edit->border = 0; edit->rounding = 0; edit->color_factor = 1.0f; - edit->disabled_factor = 0.5f; + edit->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* chart */ chart = &style->chart; @@ -18645,7 +18648,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) chart->border = 0; chart->rounding = 0; chart->color_factor = 1.0f; - chart->disabled_factor = 0.5f; + chart->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* combo */ combo = &style->combo; @@ -18665,7 +18668,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) combo->border = 1; combo->rounding = 0; combo->color_factor = 1.0f; - combo->disabled_factor = 0.5f; + combo->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* combo button */ button = &style->combo.button; @@ -18685,7 +18688,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->border = 0.0f; button->rounding = 0.0f; button->color_factor = 1.0f; - button->disabled_factor = 0.5f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -18702,7 +18705,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) tab->border = 1; tab->rounding = 0; tab->color_factor = 1.0f; - tab->disabled_factor = 0.5f; + tab->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* tab button */ button = &style->tab.tab_minimize_button; @@ -18722,7 +18725,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->border = 0.0f; button->rounding = 0.0f; button->color_factor = 1.0f; - button->disabled_factor = 0.5f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; style->tab.tab_maximize_button =*button; @@ -18745,7 +18748,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->border = 0.0f; button->rounding = 0.0f; button->color_factor = 1.0f; - button->disabled_factor = 0.5f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; style->tab.node_maximize_button =*button; @@ -18784,7 +18787,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->border = 0.0f; button->rounding = 0.0f; button->color_factor = 1.0f; - button->disabled_factor = 0.5f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -18806,7 +18809,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->border = 0.0f; button->rounding = 0.0f; button->color_factor = 1.0f; - button->disabled_factor = 0.5f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; diff --git a/src/nuklear.h b/src/nuklear.h index 7dc90ab..a16607b 100644 --- a/src/nuklear.h +++ b/src/nuklear.h @@ -3387,6 +3387,9 @@ NK_API void nk_menu_end(struct nk_context*); * STYLE * * ============================================================================= */ + +#define NK_WIDGET_DISABLED_FACTOR 0.5f + enum nk_style_colors { NK_COLOR_TEXT, NK_COLOR_WINDOW, @@ -3463,7 +3466,7 @@ NK_API struct nk_color nk_rgb_f(float r, float g, float b); NK_API struct nk_color nk_rgb_fv(const float *rgb); NK_API struct nk_color nk_rgb_cf(struct nk_colorf c); NK_API struct nk_color nk_rgb_hex(const char *rgb); -NK_API struct nk_color nk_rgb_factor(const struct nk_color col, const float factor); +NK_API struct nk_color nk_rgb_factor(struct nk_color col, const float factor); NK_API struct nk_color nk_rgba(int r, int g, int b, int a); NK_API struct nk_color nk_rgba_u32(nk_uint); diff --git a/src/nuklear_color.c b/src/nuklear_color.c index dc2e7fc..17969f3 100644 --- a/src/nuklear_color.c +++ b/src/nuklear_color.c @@ -23,14 +23,14 @@ nk_parse_hex(const char *p, int length) return i; } NK_API struct nk_color -nk_rgb_factor(const struct nk_color col, const float factor) +nk_rgb_factor(struct nk_color col, const float factor) { - struct nk_color ret; - ret.r = col.r * factor; - ret.g = col.g * factor; - ret.b = col.b * factor; - ret.a = col.a; - return ret; + if (factor == 1.0f) + return col; + col.r *= factor; + col.g *= factor; + col.b *= factor; + return col; } NK_API struct nk_color nk_rgba(int r, int g, int b, int a) diff --git a/src/nuklear_style.c b/src/nuklear_style.c index be9026b..b97ad71 100644 --- a/src/nuklear_style.c +++ b/src/nuklear_style.c @@ -114,7 +114,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) text->color = table[NK_COLOR_TEXT]; text->padding = nk_vec2(0,0); text->color_factor = 1.0f; - text->disabled_factor = 0.5f; + text->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* default button */ button = &style->button; @@ -135,7 +135,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->border = 1.0f; button->rounding = 4.0f; button->color_factor = 1.0f; - button->disabled_factor = 0.5f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -157,7 +157,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->border = 0.0f; button->rounding = 0.0f; button->color_factor = 1.0f; - button->disabled_factor = 0.5f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -179,7 +179,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->border = 0.0f; button->rounding = 1.0f; button->color_factor = 1.0f; - button->disabled_factor = 0.5f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -202,7 +202,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) toggle->border = 0.0f; toggle->spacing = 4; toggle->color_factor = 1.0f; - toggle->disabled_factor = 0.5f; + toggle->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* option toggle */ toggle = &style->option; @@ -223,7 +223,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) toggle->border = 0.0f; toggle->spacing = 4; toggle->color_factor = 1.0f; - toggle->disabled_factor = 0.5f; + toggle->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* selectable */ select = &style->selectable; @@ -246,7 +246,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) select->userdata = nk_handle_ptr(0); select->rounding = 0.0f; select->color_factor = 1.0f; - select->disabled_factor = 0.5f; + select->disabled_factor = NK_WIDGET_DISABLED_FACTOR; select->draw_begin = 0; select->draw_end = 0; @@ -273,7 +273,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) slider->bar_height = 8; slider->rounding = 0; slider->color_factor = 1.0f; - slider->disabled_factor = 0.5f; + slider->disabled_factor = NK_WIDGET_DISABLED_FACTOR; slider->draw_begin = 0; slider->draw_end = 0; @@ -294,7 +294,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->border = 1.0f; button->rounding = 0.0f; button->color_factor = 1.0f; - button->disabled_factor = 0.5f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; style->slider.dec_button = style->slider.inc_button; @@ -317,7 +317,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) prog->cursor_rounding = 0; prog->cursor_border = 0; prog->color_factor = 1.0f; - prog->disabled_factor = 0.5f; + prog->disabled_factor = NK_WIDGET_DISABLED_FACTOR; prog->draw_begin = 0; prog->draw_end = 0; @@ -342,7 +342,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) scroll->border_cursor = 0; scroll->rounding_cursor = 0; scroll->color_factor = 1.0f; - scroll->disabled_factor = 0.5f; + scroll->disabled_factor = NK_WIDGET_DISABLED_FACTOR; scroll->draw_begin = 0; scroll->draw_end = 0; style->scrollv = style->scrollh; @@ -364,7 +364,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->border = 1.0f; button->rounding = 0.0f; button->color_factor = 1.0f; - button->disabled_factor = 0.5f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; style->scrollh.dec_button = style->scrollh.inc_button; @@ -397,7 +397,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) edit->border = 1; edit->rounding = 0; edit->color_factor = 1.0f; - edit->disabled_factor = 0.5f; + edit->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* property */ property = &style->property; @@ -418,7 +418,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) property->draw_begin = 0; property->draw_end = 0; property->color_factor = 1.0f; - property->disabled_factor = 0.5f; + property->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* property buttons */ button = &style->property.dec_button; @@ -438,7 +438,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->border = 0.0f; button->rounding = 0.0f; button->color_factor = 1.0f; - button->disabled_factor = 0.5f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; style->property.inc_button = style->property.dec_button; @@ -466,7 +466,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) edit->border = 0; edit->rounding = 0; edit->color_factor = 1.0f; - edit->disabled_factor = 0.5f; + edit->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* chart */ chart = &style->chart; @@ -479,7 +479,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) chart->border = 0; chart->rounding = 0; chart->color_factor = 1.0f; - chart->disabled_factor = 0.5f; + chart->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* combo */ combo = &style->combo; @@ -499,7 +499,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) combo->border = 1; combo->rounding = 0; combo->color_factor = 1.0f; - combo->disabled_factor = 0.5f; + combo->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* combo button */ button = &style->combo.button; @@ -519,7 +519,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->border = 0.0f; button->rounding = 0.0f; button->color_factor = 1.0f; - button->disabled_factor = 0.5f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -536,7 +536,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) tab->border = 1; tab->rounding = 0; tab->color_factor = 1.0f; - tab->disabled_factor = 0.5f; + tab->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* tab button */ button = &style->tab.tab_minimize_button; @@ -556,7 +556,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->border = 0.0f; button->rounding = 0.0f; button->color_factor = 1.0f; - button->disabled_factor = 0.5f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; style->tab.tab_maximize_button =*button; @@ -579,7 +579,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->border = 0.0f; button->rounding = 0.0f; button->color_factor = 1.0f; - button->disabled_factor = 0.5f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; style->tab.node_maximize_button =*button; @@ -618,7 +618,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->border = 0.0f; button->rounding = 0.0f; button->color_factor = 1.0f; - button->disabled_factor = 0.5f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -640,7 +640,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->border = 0.0f; button->rounding = 0.0f; button->color_factor = 1.0f; - button->disabled_factor = 0.5f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; From b1fcf9244fe316ea53592f6f6af1acad6ee8667b Mon Sep 17 00:00:00 2001 From: Yukyduky Date: Wed, 18 Oct 2023 22:33:05 +0200 Subject: [PATCH 055/106] Changed a false to an nk_false --- nuklear.h | 2 +- src/nuklear_window.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nuklear.h b/nuklear.h index ec1569e..cf70358 100644 --- a/nuklear.h +++ b/nuklear.h @@ -20359,7 +20359,7 @@ nk_begin_titled(struct nk_context *ctx, const char *name, const char *title, NK_MEMCPY(win->name_string, name, name_length); win->name_string[name_length] = 0; win->popup.win = 0; - win->widgets_disabled = false; + win->widgets_disabled = nk_false; if (!ctx->active) ctx->active = win; } else { diff --git a/src/nuklear_window.c b/src/nuklear_window.c index d771e21..2e382b2 100644 --- a/src/nuklear_window.c +++ b/src/nuklear_window.c @@ -180,7 +180,7 @@ nk_begin_titled(struct nk_context *ctx, const char *name, const char *title, NK_MEMCPY(win->name_string, name, name_length); win->name_string[name_length] = 0; win->popup.win = 0; - win->widgets_disabled = false; + win->widgets_disabled = nk_false; if (!ctx->active) ctx->active = win; } else { From b65f1aa28e3132fcf3286c176f840c1c53f3c9c1 Mon Sep 17 00:00:00 2001 From: Andreas Streichardt Date: Sun, 22 Oct 2023 12:02:26 +0200 Subject: [PATCH 056/106] =?UTF-8?q?=E2=9C=A8=20add=20vulkan=20demo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- demo/glfw_vulkan/.clang-format | 4 + demo/glfw_vulkan/.gitignore | 2 + demo/glfw_vulkan/Makefile | 29 + demo/glfw_vulkan/README.md | 52 + demo/glfw_vulkan/main.c | 2225 +++++++++++++++++ demo/glfw_vulkan/nuklear_glfw_vulkan.h | 1647 ++++++++++++ demo/glfw_vulkan/shaders/demo.frag | 12 + demo/glfw_vulkan/shaders/demo.frag.spv | Bin 0 -> 664 bytes demo/glfw_vulkan/shaders/demo.vert | 10 + demo/glfw_vulkan/shaders/demo.vert.spv | Bin 0 -> 1284 bytes demo/glfw_vulkan/src/Makefile | 11 + demo/glfw_vulkan/src/README.md | 5 + demo/glfw_vulkan/src/nuklear_glfw_vulkan.in.h | 1424 +++++++++++ .../src/nuklearshaders/nuklear.frag | 13 + .../src/nuklearshaders/nuklear.vert | 23 + 15 files changed, 5457 insertions(+) create mode 100644 demo/glfw_vulkan/.clang-format create mode 100644 demo/glfw_vulkan/.gitignore create mode 100644 demo/glfw_vulkan/Makefile create mode 100644 demo/glfw_vulkan/README.md create mode 100644 demo/glfw_vulkan/main.c create mode 100644 demo/glfw_vulkan/nuklear_glfw_vulkan.h create mode 100644 demo/glfw_vulkan/shaders/demo.frag create mode 100644 demo/glfw_vulkan/shaders/demo.frag.spv create mode 100644 demo/glfw_vulkan/shaders/demo.vert create mode 100644 demo/glfw_vulkan/shaders/demo.vert.spv create mode 100644 demo/glfw_vulkan/src/Makefile create mode 100644 demo/glfw_vulkan/src/README.md create mode 100644 demo/glfw_vulkan/src/nuklear_glfw_vulkan.in.h create mode 100644 demo/glfw_vulkan/src/nuklearshaders/nuklear.frag create mode 100644 demo/glfw_vulkan/src/nuklearshaders/nuklear.vert diff --git a/demo/glfw_vulkan/.clang-format b/demo/glfw_vulkan/.clang-format new file mode 100644 index 0000000..3fa531e --- /dev/null +++ b/demo/glfw_vulkan/.clang-format @@ -0,0 +1,4 @@ +--- +BasedOnStyle: LLVM +# same as .editorconfig +IndentWidth: 4 diff --git a/demo/glfw_vulkan/.gitignore b/demo/glfw_vulkan/.gitignore new file mode 100644 index 0000000..76e4086 --- /dev/null +++ b/demo/glfw_vulkan/.gitignore @@ -0,0 +1,2 @@ +src/nuklearshaders/*.spv +src/nuklear_glfw_vulkan.h diff --git a/demo/glfw_vulkan/Makefile b/demo/glfw_vulkan/Makefile new file mode 100644 index 0000000..57675fd --- /dev/null +++ b/demo/glfw_vulkan/Makefile @@ -0,0 +1,29 @@ +# Install +BIN = demo + +# Flags +CFLAGS += -std=c89 -Wall -Wextra -pedantic -O2 + +SRC = main.c +OBJ = $(SRC:.c=.o) + +ifeq ($(OS),Windows_NT) +BIN := $(BIN).exe +LIBS = -lglfw3 -lvulkan -lm +else + UNAME_S := $(shell uname -s) + GLFW3 := $(shell pkg-config --libs glfw3) + LIBS = $(GLFW3) -lvulkan -lm +endif + + +$(BIN): shaders/demo.vert.spv shaders/demo.frag.spv + @mkdir -p bin + rm -f bin/$(BIN) $(OBJS) + $(CC) $(SRC) $(CFLAGS) -o bin/$(BIN) $(LIBS) + +shaders/demo.vert.spv: shaders/demo.vert + glslc --target-env=vulkan shaders/demo.vert -o shaders/demo.vert.spv + +shaders/demo.frag.spv: shaders/demo.frag + glslc --target-env=vulkan shaders/demo.frag -o shaders/demo.frag.spv diff --git a/demo/glfw_vulkan/README.md b/demo/glfw_vulkan/README.md new file mode 100644 index 0000000..ff0a2fc --- /dev/null +++ b/demo/glfw_vulkan/README.md @@ -0,0 +1,52 @@ +# nuklear glfw vulkan + +## Theory of operation + +The nuklear glfw vulkan integration creates an independent graphics pipeline that will render the nuklear UI to separate render targets. +The application is responsible to fully manage these render targets. So it must ensure they are properly sized (and resized when requested). + +Furthermore it is assumed that you will have a swap chain in place and the number of nuklear overlay images and number of swap chain images match. + +This is how you can integrate it in your application: + +``` +/* +Setup: overlay_images have been created and their number match with the number +of the swap_chain_images of your application. The overlay_images in this +example have the same format as your swap_chain images (optional) +*/ + struct nk_context *ctx = nk_glfw3_init( + demo.win, demo.device, demo.physical_device, demo.indices.graphics, + demo.overlay_image_views, demo.swap_chain_images_len, + demo.swap_chain_image_format, NK_GLFW3_INSTALL_CALLBACKS, + MAX_VERTEX_BUFFER, MAX_ELEMENT_BUFFER); +[...] +/* +in your draw loop draw you can then render to the overlay image at +`image_index` +your own application can then wait for the semaphore and produce +the swap_chain_image at `image_index` +this should simply sample from the overlay_image (see example) +*/ +nk_semaphore semaphore = + nk_glfw3_render(demo.graphics_queue, image_index, + demo.image_available, NK_ANTI_ALIASING_ON); + if (!render(&demo, &bg, nk_semaphore, image_index)) { + fprintf(stderr, "render failed\n"); + return false; + } +``` + +You must call `nk_glfw3_resize` whenever the size of the overlay_images resize. + +## Using images + +Images can be used by providing a VkImageView as an nk_image_ptr to nuklear: + +``` +img = nk_image_ptr(demo.demo_texture_image_view); +``` + +Note that they must have SHADER_READ_OPTIMAL layout + +It is currently not possible to specify how they are being sampled. The nuklear glfw vulkan integration uses a fixed sampler that does linear filtering. diff --git a/demo/glfw_vulkan/main.c b/demo/glfw_vulkan/main.c new file mode 100644 index 0000000..8e0b39d --- /dev/null +++ b/demo/glfw_vulkan/main.c @@ -0,0 +1,2225 @@ +/* nuklear - 1.32.0 - public domain */ +#include +#include +#include +#include +#include +#include + +#define GLFW_INCLUDE_VULKAN +#include + +#define NK_INCLUDE_FIXED_TYPES +#define NK_INCLUDE_STANDARD_IO +#define NK_INCLUDE_STANDARD_VARARGS +#define NK_INCLUDE_DEFAULT_ALLOCATOR +#define NK_INCLUDE_VERTEX_BUFFER_OUTPUT +#define NK_INCLUDE_FONT_BAKING +#define NK_INCLUDE_DEFAULT_FONT +#define NK_IMPLEMENTATION +#define NK_GLFW_VULKAN_IMPLEMENTATION +#define NK_KEYSTATE_BASED_INPUT +#include "../../nuklear.h" +#include "nuklear_glfw_vulkan.h" + +#define WINDOW_WIDTH 1200 +#define WINDOW_HEIGHT 800 + +#define MAX_VERTEX_BUFFER 512 * 1024 +#define MAX_ELEMENT_BUFFER 128 * 1024 + +/* =============================================================== + * + * EXAMPLE + * + * ===============================================================*/ +/* This are some code examples to provide a small overview of what can be + * done with this library. To try out an example uncomment the defines */ +#define INCLUDE_ALL +/*#define INCLUDE_STYLE */ +/*#define INCLUDE_CALCULATOR */ +/*#define INCLUDE_CANVAS */ +/*#define INCLUDE_OVERVIEW*/ +/*#define INCLUDE_NODE_EDITOR */ + +#ifdef INCLUDE_ALL +#define INCLUDE_STYLE +#define INCLUDE_CALCULATOR +#define INCLUDE_CANVAS +#define INCLUDE_OVERVIEW +#define INCLUDE_NODE_EDITOR +#endif + +#ifdef INCLUDE_STYLE +#include "../../demo/common/style.c" +#endif +#ifdef INCLUDE_CALCULATOR +#include "../../demo/common/calculator.c" +#endif +#ifdef INCLUDE_CANVAS +#include "../../demo/common/canvas.c" +#endif +#ifdef INCLUDE_OVERVIEW +#include "../../demo/common/overview.c" +#endif +#ifdef INCLUDE_NODE_EDITOR +#include "../../demo/common/node_editor.c" +#endif + +/* =============================================================== + * + * DEMO + * + * ===============================================================*/ + +static const char *validation_layer_name = "VK_LAYER_KHRONOS_validation"; + +struct queue_family_indices { + int graphics; + int present; +}; + +struct swap_chain_support_details { + VkSurfaceCapabilitiesKHR capabilities; + VkSurfaceFormatKHR *formats; + uint32_t formats_len; + VkPresentModeKHR *present_modes; + uint32_t present_modes_len; +}; + +void swap_chain_support_details_free( + struct swap_chain_support_details *swap_chain_support) { + if (swap_chain_support->formats_len > 0) { + free(swap_chain_support->formats); + swap_chain_support->formats = NULL; + } + if (swap_chain_support->present_modes_len > 0) { + free(swap_chain_support->present_modes); + swap_chain_support->present_modes = NULL; + } +} + +struct vulkan_demo { + GLFWwindow *win; + VkInstance instance; + VkDebugUtilsMessengerEXT debugMessenger; + VkSurfaceKHR surface; + VkPhysicalDevice physical_device; + struct queue_family_indices indices; + VkDevice device; + VkQueue graphics_queue; + VkQueue present_queue; + VkSampler sampler; + + VkSwapchainKHR swap_chain; + VkImage *swap_chain_images; + uint32_t swap_chain_images_len; + VkImageView *swap_chain_image_views; + VkFormat swap_chain_image_format; + VkExtent2D swap_chain_image_extent; + + VkImage *overlay_images; + VkImageView *overlay_image_views; + VkDeviceMemory *overlay_image_memories; + + VkRenderPass render_pass; + VkFramebuffer *framebuffers; + VkDescriptorSetLayout descriptor_set_layout; + VkDescriptorPool descriptor_pool; + VkDescriptorSet *descriptor_sets; + VkPipelineLayout pipeline_layout; + VkPipeline pipeline; + VkCommandPool command_pool; + VkCommandBuffer *command_buffers; + VkSemaphore image_available; + VkSemaphore render_finished; + + VkImage demo_texture_image; + VkImageView demo_texture_image_view; + VkDeviceMemory demo_texture_memory; + + VkFence render_fence; +}; + +static void glfw_error_callback(int e, const char *d) { + fprintf(stderr, "Error %d: %s\n", e, d); +} + +VKAPI_ATTR VkBool32 VKAPI_CALL +vulkan_debug_callback(VkDebugUtilsMessageSeverityFlagBitsEXT message_severity, + VkDebugUtilsMessageTypeFlagsEXT message_type, + const VkDebugUtilsMessengerCallbackDataEXT *callback_data, + void *user_data) { + (void)message_severity; + (void)message_type; + (void)user_data; + fprintf(stderr, "validation layer: %s\n", callback_data->pMessage); + + return VK_FALSE; +} + +bool check_validation_layer_support() { + uint32_t layer_count; + bool ret = false; + VkResult result; + uint32_t i; + VkLayerProperties *available_layers = NULL; + + result = vkEnumerateInstanceLayerProperties(&layer_count, NULL); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkEnumerateInstanceLayerProperties failed: %d\n", + result); + return ret; + } + + available_layers = malloc(layer_count * sizeof(VkLayerProperties)); + result = vkEnumerateInstanceLayerProperties(&layer_count, available_layers); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkEnumerateInstanceLayerProperties failed: %d\n", + result); + goto cleanup; + } + + printf("Available vulkan layers:\n"); + for (i = 0; i < layer_count; i++) { + printf(" %s\n", available_layers[i].layerName); + if (strcmp(validation_layer_name, available_layers[i].layerName) == 0) { + ret = true; + break; + } + } +cleanup: + free(available_layers); + return ret; +} + +bool create_instance(struct vulkan_demo *demo) { + uint32_t i; + uint32_t available_instance_extension_count; + VkResult result; + VkExtensionProperties *available_instance_extensions = NULL; + bool ret = false; + VkApplicationInfo app_info; + VkInstanceCreateInfo create_info; + uint32_t glfw_extension_count; + const char **glfw_extensions; + uint32_t enabled_extension_count; + const char **enabled_extensions = NULL; + + if (!check_validation_layer_support()) { + fprintf(stderr, "Couldn't find validation layer %s\n", + validation_layer_name); + return ret; + } + result = vkEnumerateInstanceExtensionProperties( + NULL, &available_instance_extension_count, NULL); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkEnumerateInstanceExtensionProperties failed %d\n", + result); + return ret; + } + + available_instance_extensions = malloc(available_instance_extension_count * + sizeof(VkExtensionProperties)); + + result = vkEnumerateInstanceExtensionProperties( + NULL, &available_instance_extension_count, + available_instance_extensions); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkEnumerateInstanceExtensionProperties failed %d\n", + result); + goto cleanup; + } + + printf("available instance extensions:\n"); + for (i = 0; i < available_instance_extension_count; i++) { + printf(" %s\n", available_instance_extensions[i].extensionName); + } + + glfw_extensions = glfwGetRequiredInstanceExtensions(&glfw_extension_count); + + enabled_extension_count = glfw_extension_count + 1; + enabled_extensions = malloc(enabled_extension_count * sizeof(char *)); + memcpy(enabled_extensions, glfw_extensions, + glfw_extension_count * sizeof(char *)); + enabled_extensions[glfw_extension_count] = + VK_EXT_DEBUG_UTILS_EXTENSION_NAME; + + printf("Trying to enable the following instance extensions: "); + for (i = 0; i < enabled_extension_count; i++) { + if (i > 0) { + printf(", "); + } + printf(enabled_extensions[i]); + } + printf("\n"); + for (i = 0; i < enabled_extension_count; i++) { + int extension_missing = 1; + uint32_t j; + for (j = 0; j < available_instance_extension_count; j++) { + if (strcmp(enabled_extensions[i], + available_instance_extensions[j].extensionName) == 0) { + extension_missing = 0; + break; + } + } + if (extension_missing) { + fprintf(stderr, "Extension %s is missing\n", enabled_extensions[i]); + return ret; + } + } + + memset(&app_info, 0, sizeof(VkApplicationInfo)); + app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; + app_info.pApplicationName = "Demo"; + app_info.applicationVersion = VK_MAKE_VERSION(1, 0, 0); + app_info.pEngineName = "No Engine"; + app_info.engineVersion = VK_MAKE_VERSION(1, 0, 0); + app_info.apiVersion = VK_API_VERSION_1_0; + + memset(&create_info, 0, sizeof(VkInstanceCreateInfo)); + create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; + create_info.pApplicationInfo = &app_info; + create_info.enabledExtensionCount = enabled_extension_count; + create_info.ppEnabledExtensionNames = enabled_extensions; + create_info.enabledLayerCount = 1; + create_info.ppEnabledLayerNames = &validation_layer_name; + result = vkCreateInstance(&create_info, NULL, &demo->instance); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateInstance result %d\n", result); + return ret; + } + ret = true; + +cleanup: + if (available_instance_extensions) { + free(available_instance_extensions); + } + if (enabled_extensions) { + free(enabled_extensions); + } + + return ret; +} + +VkResult create_debug_utils_messenger_ext( + VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT *pCreateInfo, + const VkAllocationCallbacks *pAllocator, + VkDebugUtilsMessengerEXT *pDebugMessenger) { + PFN_vkCreateDebugUtilsMessengerEXT func = + (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr( + instance, "vkCreateDebugUtilsMessengerEXT"); + if (func != NULL) { + return func(instance, pCreateInfo, pAllocator, pDebugMessenger); + } else { + return VK_ERROR_EXTENSION_NOT_PRESENT; + } +} + +bool create_debug_callback(struct vulkan_demo *demo) { + VkResult result; + + VkDebugUtilsMessengerCreateInfoEXT create_info; + memset(&create_info, 0, sizeof(VkDebugUtilsMessengerCreateInfoEXT)); + create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT; + create_info.messageSeverity = + VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | + VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; + create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | + VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | + VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; + create_info.pfnUserCallback = vulkan_debug_callback; + + result = create_debug_utils_messenger_ext(demo->instance, &create_info, + NULL, &demo->debugMessenger); + if (result != VK_SUCCESS) { + fprintf(stderr, "create_debug_utils_messenger_ext failed %d\n", result); + return false; + } + return true; +} + +bool create_surface(struct vulkan_demo *demo) { + VkResult result; + result = glfwCreateWindowSurface(demo->instance, demo->win, NULL, + &demo->surface); + if (result != VK_SUCCESS) { + fprintf(stderr, "creating vulkan surface failed: %d\n", result); + return false; + } + return true; +} + +bool find_queue_families(VkPhysicalDevice physical_device, VkSurfaceKHR surface, + struct queue_family_indices *indices) { + VkResult result; + uint32_t queue_family_count = 0; + uint32_t i = 0; + bool ret = false; + VkQueueFamilyProperties *queue_family_properties; + VkBool32 present_support; + + vkGetPhysicalDeviceQueueFamilyProperties(physical_device, + &queue_family_count, NULL); + + queue_family_properties = + malloc(queue_family_count * sizeof(VkQueueFamilyProperties)); + vkGetPhysicalDeviceQueueFamilyProperties( + physical_device, &queue_family_count, queue_family_properties); + + for (i = 0; i < queue_family_count; i++) { + if (queue_family_properties[i].queueCount == 0) { + continue; + } + if (queue_family_properties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) { + indices->graphics = i; + } + + result = vkGetPhysicalDeviceSurfaceSupportKHR( + physical_device, i, surface, &present_support); + if (result != VK_SUCCESS) { + fprintf(stderr, + "vkGetPhysicalDeviceSurfaceSupportKHR failed with %d\n", + result); + goto cleanup; + } + if (present_support == VK_TRUE) { + indices->present = i; + } + if (indices->graphics >= 0 && indices->present >= 0) { + break; + } + } + ret = true; +cleanup: + free(queue_family_properties); + return ret; +} + +bool query_swap_chain_support( + VkPhysicalDevice device, VkSurfaceKHR surface, + struct swap_chain_support_details *swap_chain_support) { + VkResult result; + + result = vkGetPhysicalDeviceSurfaceCapabilitiesKHR( + device, surface, &swap_chain_support->capabilities); + if (result != VK_SUCCESS) { + fprintf(stderr, + "vkGetPhysicalDeviceSurfaceCapabilitiesKHR failed: %d\n", + result); + return false; + } + + result = vkGetPhysicalDeviceSurfaceFormatsKHR( + device, surface, &swap_chain_support->formats_len, NULL); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkGetPhysicalDeviceSurfaceFormatsKHR failed: %d\n", + result); + return false; + } + + if (swap_chain_support->formats_len != 0) { + swap_chain_support->formats = malloc(swap_chain_support->formats_len * + sizeof(VkSurfaceFormatKHR)); + result = vkGetPhysicalDeviceSurfaceFormatsKHR( + device, surface, &swap_chain_support->formats_len, + swap_chain_support->formats); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkGetPhysicalDeviceSurfaceFormatsKHR failed: %d\n", + result); + return false; + } + } + + result = vkGetPhysicalDeviceSurfacePresentModesKHR( + device, surface, &swap_chain_support->present_modes_len, NULL); + + if (result != VK_SUCCESS) { + fprintf(stderr, + "vkGetPhysicalDeviceSurfacePresentModesKHR failed: %d\n", + result); + return false; + } + + if (swap_chain_support->present_modes_len != 0) { + swap_chain_support->present_modes = malloc( + swap_chain_support->present_modes_len * sizeof(VkPresentModeKHR)); + result = vkGetPhysicalDeviceSurfacePresentModesKHR( + device, surface, &swap_chain_support->present_modes_len, + swap_chain_support->present_modes); + + if (result != VK_SUCCESS) { + fprintf(stderr, + "vkGetPhysicalDeviceSurfacePresentModesKHR failed: %d\n", + result); + return false; + } + } + + return true; +} + +bool is_suitable_physical_device(VkPhysicalDevice physical_device, + VkSurfaceKHR surface, + struct queue_family_indices *indices) { + VkResult result; + uint32_t device_extension_count; + uint32_t i; + VkExtensionProperties *device_extensions; + bool ret = false; + struct swap_chain_support_details swap_chain_support; + int found_khr_surface = 0; + + VkPhysicalDeviceProperties device_properties; + vkGetPhysicalDeviceProperties(physical_device, &device_properties); + + printf("Probing physical device %s\n", device_properties.deviceName); + + result = vkEnumerateDeviceExtensionProperties( + physical_device, NULL, &device_extension_count, NULL); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkEnumerateDeviceExtensionProperties failed: %d\n", + result); + return false; + } + + device_extensions = + malloc(device_extension_count * sizeof(VkExtensionProperties)); + + result = vkEnumerateDeviceExtensionProperties( + physical_device, NULL, &device_extension_count, device_extensions); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkEnumerateDeviceExtensionProperties failed: %d\n", + result); + goto cleanup; + } + + printf(" Supported device extensions:\n"); + + for (i = 0; i < device_extension_count; i++) { + printf(" %s\n", device_extensions[i].extensionName); + if (strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, + device_extensions[i].extensionName) == 0) { + found_khr_surface = 1; + break; + } + } + if (!found_khr_surface) { + printf(" Device doesnt support %s\n", VK_KHR_SWAPCHAIN_EXTENSION_NAME); + goto cleanup; + } + if (!find_queue_families(physical_device, surface, indices)) { + goto cleanup; + } + if (indices->graphics < 0 || indices->present < 0) { + printf(" Device is missing graphics and/or present support. graphics: " + "%d, present: %d\n", + indices->graphics, indices->present); + goto cleanup; + } + + if (!query_swap_chain_support(physical_device, surface, + &swap_chain_support)) { + goto cleanup; + } + + if (swap_chain_support.formats_len == 0) { + printf(" Device doesn't support any swap chain formats\n"); + goto cleanup; + } + + if (swap_chain_support.present_modes_len == 0) { + printf(" Device doesn't support any swap chain present modes\n"); + goto cleanup; + } + ret = true; + +cleanup: + free(device_extensions); + swap_chain_support_details_free(&swap_chain_support); + + return ret; +} + +bool create_physical_device(struct vulkan_demo *demo) { + uint32_t device_count = 0; + VkPhysicalDevice *physical_devices; + VkResult result; + uint32_t i; + bool ret = false; + + result = vkEnumeratePhysicalDevices(demo->instance, &device_count, NULL); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkEnumeratePhysicalDevices failed: %d\n", result); + return ret; + } + if (device_count == 0) { + fprintf(stderr, "no vulkan capable GPU found!"); + return ret; + } + + physical_devices = malloc(device_count * sizeof(VkPhysicalDevice)); + result = vkEnumeratePhysicalDevices(demo->instance, &device_count, + physical_devices); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkEnumeratePhysicalDevices failed: %d\n", result); + goto cleanup; + } + + for (i = 0; i < device_count; i++) { + struct queue_family_indices indices = {-1, -1}; + if (is_suitable_physical_device(physical_devices[i], demo->surface, + &indices)) { + printf(" Selecting this device for rendering. Queue families: " + "graphics: %d, present: %d!\n", + indices.graphics, indices.present); + demo->physical_device = physical_devices[i]; + demo->indices = indices; + break; + } + } + if (demo->physical_device == NULL) { + fprintf(stderr, "failed to find a suitable GPU!\n"); + } else { + ret = true; + } +cleanup: + free(physical_devices); + return ret; +} + +bool create_logical_device(struct vulkan_demo *demo) { + VkResult result; + bool ret = false; + float queuePriority = 1.0f; + uint32_t num_queues = 1; + VkDeviceQueueCreateInfo *queue_create_infos; + VkDeviceCreateInfo create_info; + const char *swap_chain_extension_name = VK_KHR_SWAPCHAIN_EXTENSION_NAME; + + queue_create_infos = calloc(2, sizeof(VkDeviceQueueCreateInfo)); + queue_create_infos[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; + queue_create_infos[0].queueFamilyIndex = demo->indices.graphics; + queue_create_infos[0].queueCount = 1; + queue_create_infos[0].pQueuePriorities = &queuePriority; + + if (demo->indices.present != demo->indices.graphics) { + queue_create_infos[1].sType = + VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; + queue_create_infos[1].queueFamilyIndex = demo->indices.present; + queue_create_infos[1].queueCount = 1; + queue_create_infos[1].pQueuePriorities = &queuePriority; + num_queues = 2; + } + + memset(&create_info, 0, sizeof(VkDeviceCreateInfo)); + create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; + create_info.queueCreateInfoCount = num_queues; + create_info.pQueueCreateInfos = queue_create_infos; + create_info.enabledExtensionCount = 1; + create_info.ppEnabledExtensionNames = &swap_chain_extension_name; + + result = vkCreateDevice(demo->physical_device, &create_info, NULL, + &demo->device); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateDevice failed: %d\n", result); + goto cleanup; + } + + vkGetDeviceQueue(demo->device, demo->indices.graphics, 0, + &demo->graphics_queue); + vkGetDeviceQueue(demo->device, demo->indices.present, 0, + &demo->present_queue); + ret = true; +cleanup: + free(queue_create_infos); + return ret; +} + +bool create_sampler(struct vulkan_demo *demo) { + VkResult result; + VkSamplerCreateInfo sampler_info; + + memset(&sampler_info, 0, sizeof(VkSamplerCreateInfo)); + sampler_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; + sampler_info.pNext = NULL; + sampler_info.maxAnisotropy = 1.0; + sampler_info.magFilter = VK_FILTER_LINEAR; + sampler_info.minFilter = VK_FILTER_LINEAR; + sampler_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; + sampler_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; + sampler_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; + sampler_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; + sampler_info.mipLodBias = 0.0f; + sampler_info.compareEnable = VK_FALSE; + sampler_info.compareOp = VK_COMPARE_OP_ALWAYS; + sampler_info.minLod = 0.0f; + sampler_info.maxLod = 0.0f; + sampler_info.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK; + + result = vkCreateSampler(demo->device, &sampler_info, NULL, &demo->sampler); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateSampler failed: %d\n", result); + return false; + } + return true; +} + +VkSurfaceFormatKHR +choose_swap_surface_format(VkSurfaceFormatKHR *available_formats, + uint32_t available_formats_len) { + VkSurfaceFormatKHR undefined_format = {VK_FORMAT_B8G8R8A8_UNORM, + VK_COLOR_SPACE_SRGB_NONLINEAR_KHR}; + uint32_t i; + if (available_formats_len == 1 && + available_formats[0].format == VK_FORMAT_UNDEFINED) { + return undefined_format; + } + + for (i = 0; i < available_formats_len; i++) { + if (available_formats[i].format == VK_FORMAT_B8G8R8A8_UNORM && + available_formats[i].colorSpace == + VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { + return available_formats[i]; + } + } + + return available_formats[0]; +} + +VkPresentModeKHR +choose_swap_present_mode(VkPresentModeKHR *available_present_modes, + uint32_t available_present_modes_len) { + uint32_t i; + for (i = 0; i < available_present_modes_len; i++) { + /* + best mode to ensure good input latency while ensuring we are not + producing tearing + */ + if (available_present_modes[i] == VK_PRESENT_MODE_MAILBOX_KHR) { + return available_present_modes[i]; + } + } + + /* must be supported */ + return VK_PRESENT_MODE_FIFO_KHR; +} + +VkExtent2D choose_swap_extent(struct vulkan_demo *demo, + VkSurfaceCapabilitiesKHR *capabilities) { + int width, height; + VkExtent2D actual_extent; + if (capabilities->currentExtent.width != 0xFFFFFFFF) { + return capabilities->currentExtent; + } else { + /* not window size! */ + glfwGetFramebufferSize(demo->win, &width, &height); + + actual_extent.width = (uint32_t)width; + actual_extent.height = (uint32_t)height; + + actual_extent.width = NK_MAX( + capabilities->minImageExtent.width, + NK_MIN(capabilities->maxImageExtent.width, actual_extent.width)); + actual_extent.height = NK_MAX( + capabilities->minImageExtent.height, + NK_MIN(capabilities->maxImageExtent.height, actual_extent.height)); + + return actual_extent; + } +} + +bool create_swap_chain(struct vulkan_demo *demo) { + struct swap_chain_support_details swap_chain_support; + VkSurfaceFormatKHR surface_format; + VkPresentModeKHR present_mode; + VkExtent2D extent; + VkResult result; + VkSwapchainCreateInfoKHR create_info; + uint32_t queue_family_indices[2]; + uint32_t old_swap_chain_images_len; + bool ret = false; + + queue_family_indices[0] = (uint32_t)demo->indices.graphics; + queue_family_indices[1] = (uint32_t)demo->indices.present; + + if (!query_swap_chain_support(demo->physical_device, demo->surface, + &swap_chain_support)) { + goto cleanup; + } + surface_format = choose_swap_surface_format(swap_chain_support.formats, + swap_chain_support.formats_len); + present_mode = choose_swap_present_mode( + swap_chain_support.present_modes, swap_chain_support.present_modes_len); + extent = choose_swap_extent(demo, &swap_chain_support.capabilities); + + demo->swap_chain_images_len = + swap_chain_support.capabilities.minImageCount + 1; + if (swap_chain_support.capabilities.maxImageCount > 0 && + demo->swap_chain_images_len > + swap_chain_support.capabilities.maxImageCount) { + demo->swap_chain_images_len = + swap_chain_support.capabilities.maxImageCount; + } + + memset(&create_info, 0, sizeof(VkSwapchainCreateInfoKHR)); + create_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; + create_info.surface = demo->surface; + + create_info.minImageCount = demo->swap_chain_images_len; + create_info.imageFormat = surface_format.format; + create_info.imageColorSpace = surface_format.colorSpace; + create_info.imageExtent = extent; + create_info.imageArrayLayers = 1; + create_info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + + if (demo->indices.graphics != demo->indices.present) { + create_info.imageSharingMode = VK_SHARING_MODE_CONCURRENT; + create_info.queueFamilyIndexCount = 2; + create_info.pQueueFamilyIndices = queue_family_indices; + } else { + create_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; + } + + create_info.preTransform = swap_chain_support.capabilities.currentTransform; + create_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; + create_info.presentMode = present_mode; + create_info.clipped = VK_TRUE; + + result = vkCreateSwapchainKHR(demo->device, &create_info, NULL, + &demo->swap_chain); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateSwapchainKHR failed: %d\n", result); + goto cleanup; + } + + old_swap_chain_images_len = demo->swap_chain_images_len; + result = vkGetSwapchainImagesKHR(demo->device, demo->swap_chain, + &demo->swap_chain_images_len, NULL); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkGetSwapchainImagesKHR failed: %d\n", result); + goto cleanup; + } + if (old_swap_chain_images_len > 0 && + old_swap_chain_images_len != demo->swap_chain_images_len) { + fprintf(stderr, + "number of assigned swap chain images changed between " + "runs. old: %u, new: %u\n", + (unsigned)old_swap_chain_images_len, + (unsigned)demo->swap_chain_images_len); + goto cleanup; + } + if (demo->swap_chain_images == NULL) { + demo->swap_chain_images = + malloc(demo->swap_chain_images_len * sizeof(VkImage)); + } + result = vkGetSwapchainImagesKHR(demo->device, demo->swap_chain, + &demo->swap_chain_images_len, + demo->swap_chain_images); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkGetSwapchainImagesKHR failed: %d\n", result); + return false; + } + + demo->swap_chain_image_format = surface_format.format; + demo->swap_chain_image_extent = extent; + + ret = true; +cleanup: + swap_chain_support_details_free(&swap_chain_support); + + return ret; +} + +bool create_swap_chain_image_views(struct vulkan_demo *demo) { + uint32_t i; + VkResult result; + VkImageViewCreateInfo create_info; + + memset(&create_info, 0, sizeof(VkImageViewCreateInfo)); + create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + create_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + create_info.format = demo->swap_chain_image_format; + create_info.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; + create_info.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; + create_info.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; + create_info.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; + create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + create_info.subresourceRange.baseMipLevel = 0; + create_info.subresourceRange.levelCount = 1; + create_info.subresourceRange.baseArrayLayer = 0; + create_info.subresourceRange.layerCount = 1; + + if (!demo->swap_chain_image_views) { + demo->swap_chain_image_views = + malloc(demo->swap_chain_images_len * sizeof(VkImageView)); + } + + for (i = 0; i < demo->swap_chain_images_len; i++) { + create_info.image = demo->swap_chain_images[i]; + result = vkCreateImageView(demo->device, &create_info, NULL, + &demo->swap_chain_image_views[i]); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateImageView failed: %d\n", result); + return false; + } + } + return true; +} + +bool create_overlay_images(struct vulkan_demo *demo) { + uint32_t i, j; + VkResult result; + VkMemoryRequirements mem_requirements; + VkPhysicalDeviceMemoryProperties mem_properties; + int found; + VkImageCreateInfo image_info; + VkMemoryAllocateInfo alloc_info; + VkImageViewCreateInfo image_view_info; + + memset(&image_info, 0, sizeof(VkImageCreateInfo)); + image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + image_info.imageType = VK_IMAGE_TYPE_2D; + image_info.extent.width = demo->swap_chain_image_extent.width; + image_info.extent.height = demo->swap_chain_image_extent.height; + image_info.extent.depth = 1; + image_info.mipLevels = 1; + image_info.arrayLayers = 1; + image_info.format = demo->swap_chain_image_format; + image_info.tiling = VK_IMAGE_TILING_OPTIMAL; + image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + image_info.usage = + VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + image_info.samples = VK_SAMPLE_COUNT_1_BIT; + image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + + memset(&alloc_info, 0, sizeof(VkMemoryAllocateInfo)); + alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + + memset(&image_view_info, 0, sizeof(VkImageViewCreateInfo)); + image_view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + image_view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + image_view_info.format = demo->swap_chain_image_format; + image_view_info.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; + image_view_info.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; + image_view_info.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; + image_view_info.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; + image_view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + image_view_info.subresourceRange.baseMipLevel = 0; + image_view_info.subresourceRange.levelCount = 1; + image_view_info.subresourceRange.baseArrayLayer = 0; + image_view_info.subresourceRange.layerCount = 1; + + if (!demo->overlay_images) { + demo->overlay_images = + malloc(demo->swap_chain_images_len * sizeof(VkImage)); + } + + if (!demo->overlay_image_memories) { + demo->overlay_image_memories = + malloc(demo->swap_chain_images_len * sizeof(VkDeviceMemory)); + } + if (!demo->overlay_image_views) { + demo->overlay_image_views = + malloc(demo->swap_chain_images_len * sizeof(VkImageView)); + } + + for (i = 0; i < demo->swap_chain_images_len; i++) { + result = vkCreateImage(demo->device, &image_info, NULL, + &demo->overlay_images[i]); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateImage failed for index %lu: %d\n", + (unsigned long)i, result); + return false; + } + + vkGetImageMemoryRequirements(demo->device, demo->overlay_images[i], + &mem_requirements); + + alloc_info.allocationSize = mem_requirements.size; + + vkGetPhysicalDeviceMemoryProperties(demo->physical_device, + &mem_properties); + found = 0; + for (j = 0; j < mem_properties.memoryTypeCount; j++) { + if ((mem_requirements.memoryTypeBits & (1 << j)) && + (mem_properties.memoryTypes[j].propertyFlags & + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) { + found = 1; + break; + } + } + if (!found) { + fprintf(stderr, + "failed to find suitable memory type for index %lu!\n", + (unsigned long)i); + return false; + } + alloc_info.memoryTypeIndex = j; + result = vkAllocateMemory(demo->device, &alloc_info, NULL, + &demo->overlay_image_memories[i]); + if (result != VK_SUCCESS) { + fprintf(stderr, + "failed to allocate vulkan memory for index %lu: %d!\n", + (unsigned long)i, result); + return false; + } + result = vkBindImageMemory(demo->device, demo->overlay_images[i], + demo->overlay_image_memories[i], 0); + if (result != VK_SUCCESS) { + fprintf(stderr, "Couldn't bind image memory for index %lu: %d\n", + (unsigned long)i, result); + return false; + } + + image_view_info.image = demo->overlay_images[i]; + result = vkCreateImageView(demo->device, &image_view_info, NULL, + &demo->overlay_image_views[i]); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateImageView failed for index %lu: %d\n", + (unsigned long)i, result); + return false; + } + } + return true; +} + +bool create_render_pass(struct vulkan_demo *demo) { + VkAttachmentDescription attachment; + VkAttachmentReference color_attachment_ref; + VkSubpassDescription subpass; + VkSubpassDependency dependency; + VkRenderPassCreateInfo render_pass_info; + VkResult result; + + memset(&attachment, 0, sizeof(VkAttachmentDescription)); + attachment.format = demo->swap_chain_image_format; + attachment.samples = VK_SAMPLE_COUNT_1_BIT; + attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; + attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; + attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + + memset(&color_attachment_ref, 0, sizeof(VkAttachmentReference)); + color_attachment_ref.attachment = 0; + color_attachment_ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + + memset(&subpass, 0, sizeof(VkSubpassDescription)); + subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; + subpass.colorAttachmentCount = 1; + subpass.pColorAttachments = &color_attachment_ref; + + memset(&dependency, 0, sizeof(VkSubpassDependency)); + dependency.srcSubpass = VK_SUBPASS_EXTERNAL; + dependency.dstSubpass = 0; + dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + dependency.srcAccessMask = 0; + dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | + VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + + memset(&render_pass_info, 0, sizeof(VkRenderPassCreateInfo)); + render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; + render_pass_info.attachmentCount = 1; + render_pass_info.pAttachments = &attachment; + render_pass_info.subpassCount = 1; + render_pass_info.pSubpasses = &subpass; + render_pass_info.dependencyCount = 1; + render_pass_info.pDependencies = &dependency; + + result = vkCreateRenderPass(demo->device, &render_pass_info, NULL, + &demo->render_pass); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateRenderPass failed: %d\n", result); + return false; + } + return true; +} + +bool create_framebuffers(struct vulkan_demo *demo) { + uint32_t i; + VkResult result; + VkFramebufferCreateInfo framebuffer_info; + + if (!demo->framebuffers) { + demo->framebuffers = + malloc(demo->swap_chain_images_len * sizeof(VkFramebuffer)); + } + + memset(&framebuffer_info, 0, sizeof(VkFramebufferCreateInfo)); + framebuffer_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; + framebuffer_info.renderPass = demo->render_pass; + framebuffer_info.attachmentCount = 1; + framebuffer_info.width = demo->swap_chain_image_extent.width; + framebuffer_info.height = demo->swap_chain_image_extent.height; + framebuffer_info.layers = 1; + + for (i = 0; i < demo->swap_chain_images_len; i++) { + framebuffer_info.pAttachments = &demo->swap_chain_image_views[i]; + + result = vkCreateFramebuffer(demo->device, &framebuffer_info, NULL, + &demo->framebuffers[i]); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateFramebuffer failed from index %lu: %d\n", + (unsigned long)i, result); + return false; + } + } + return true; +} + +bool create_descriptor_set_layout(struct vulkan_demo *demo) { + VkDescriptorSetLayoutBinding overlay_layout_binding; + VkDescriptorSetLayoutCreateInfo descriptor_set_layout_create_nfo; + VkResult result; + + memset(&overlay_layout_binding, 0, sizeof(VkDescriptorSetLayoutBinding)); + overlay_layout_binding.binding = 0; + overlay_layout_binding.descriptorCount = 1; + overlay_layout_binding.descriptorType = + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + overlay_layout_binding.pImmutableSamplers = NULL; + overlay_layout_binding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; + + memset(&descriptor_set_layout_create_nfo, 0, + sizeof(VkDescriptorSetLayoutCreateInfo)); + descriptor_set_layout_create_nfo.sType = + VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + descriptor_set_layout_create_nfo.bindingCount = 1; + descriptor_set_layout_create_nfo.pBindings = &overlay_layout_binding; + + result = vkCreateDescriptorSetLayout(demo->device, + &descriptor_set_layout_create_nfo, + NULL, &demo->descriptor_set_layout); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateDescriptorSetLayout failed: %d\n", result); + return false; + } + return true; +} + +bool create_descriptor_pool(struct vulkan_demo *demo) { + VkDescriptorPoolSize pool_size; + VkDescriptorPoolCreateInfo pool_info; + VkResult result; + + memset(&pool_size, 0, sizeof(VkDescriptorPoolSize)); + pool_size.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + pool_size.descriptorCount = demo->swap_chain_images_len; + + memset(&pool_info, 0, sizeof(VkDescriptorPoolCreateInfo)); + pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; + pool_info.poolSizeCount = 1; + pool_info.pPoolSizes = &pool_size; + pool_info.maxSets = demo->swap_chain_images_len; + result = vkCreateDescriptorPool(demo->device, &pool_info, NULL, + &demo->descriptor_pool); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateDescriptorPool failed: %d\n", result); + return false; + } + return true; +} + +void update_descriptor_sets(struct vulkan_demo *demo) { + uint32_t i; + VkDescriptorImageInfo descriptor_image_info; + VkWriteDescriptorSet descriptor_write; + + memset(&descriptor_image_info, 0, sizeof(VkDescriptorImageInfo)); + descriptor_image_info.imageLayout = + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + descriptor_image_info.sampler = demo->sampler; + + memset(&descriptor_write, 0, sizeof(VkWriteDescriptorSet)); + descriptor_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptor_write.dstBinding = 0; + descriptor_write.dstArrayElement = 0; + descriptor_write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + descriptor_write.descriptorCount = 1; + descriptor_write.pImageInfo = &descriptor_image_info; + + for (i = 0; i < demo->swap_chain_images_len; i++) { + descriptor_write.dstSet = demo->descriptor_sets[i]; + descriptor_image_info.imageView = demo->overlay_image_views[i]; + + vkUpdateDescriptorSets(demo->device, 1, &descriptor_write, 0, NULL); + } +} + +bool create_descriptor_sets(struct vulkan_demo *demo) { + bool ret = false; + VkDescriptorSetLayout *descriptor_set_layouts; + VkDescriptorSetAllocateInfo alloc_info; + uint32_t i; + VkResult result; + + demo->descriptor_sets = + malloc(demo->swap_chain_images_len * sizeof(VkDescriptorSet)); + descriptor_set_layouts = + malloc(demo->swap_chain_images_len * sizeof(VkDescriptorSetLayout)); + + for (i = 0; i < demo->swap_chain_images_len; i++) { + descriptor_set_layouts[i] = demo->descriptor_set_layout; + } + + memset(&alloc_info, 0, sizeof(VkDescriptorSetAllocateInfo)); + alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + alloc_info.descriptorPool = demo->descriptor_pool; + alloc_info.descriptorSetCount = demo->swap_chain_images_len; + alloc_info.pSetLayouts = descriptor_set_layouts; + result = vkAllocateDescriptorSets(demo->device, &alloc_info, + demo->descriptor_sets); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkAllocateDescriptorSets failed: %d\n", result); + goto cleanup; + } + + update_descriptor_sets(demo); + + ret = true; +cleanup: + free(descriptor_set_layouts); + + return ret; +} + +bool create_shader_module(VkDevice device, char *shader_buffer, + size_t shader_buffer_len, + VkShaderModule *shader_module) { + VkShaderModuleCreateInfo create_info; + VkResult result; + + memset(&create_info, 0, sizeof(VkShaderModuleCreateInfo)); + create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + create_info.codeSize = shader_buffer_len; + create_info.pCode = (const uint32_t *)shader_buffer; + + result = vkCreateShaderModule(device, &create_info, NULL, shader_module); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateShaderModule failed: %d\n", result); + return false; + } + + return true; +} + +bool create_graphics_pipeline(struct vulkan_demo *demo) { + bool ret = false; + char *vert_shader_code = NULL; + char *frag_shader_code = NULL; + VkShaderModule vert_shader_module; + VkShaderModule frag_shader_module; + FILE *fp; + size_t file_len; + VkPipelineShaderStageCreateInfo vert_shader_stage_info; + VkPipelineShaderStageCreateInfo frag_shader_stage_info; + VkPipelineShaderStageCreateInfo shader_stages[2]; + VkPipelineVertexInputStateCreateInfo vertex_input_info; + VkPipelineInputAssemblyStateCreateInfo input_assembly; + VkViewport viewport; + VkRect2D scissor; + VkPipelineViewportStateCreateInfo viewport_state; + VkPipelineRasterizationStateCreateInfo rasterizer; + VkPipelineMultisampleStateCreateInfo multisampling; + VkPipelineColorBlendAttachmentState color_blend_attachment; + VkPipelineColorBlendStateCreateInfo color_blending; + VkPipelineLayoutCreateInfo pipeline_layout_info; + VkResult result; + VkGraphicsPipelineCreateInfo pipeline_info; + + fp = fopen("shaders/demo.vert.spv", "r"); + if (!fp) { + fprintf(stderr, "Couldn't open shaders/demo.vert.spv\n"); + return false; + } + fseek(fp, 0, SEEK_END); + file_len = ftell(fp); + vert_shader_code = malloc(file_len); + fseek(fp, 0, 0); + fread(vert_shader_code, 1, file_len, fp); + fclose(fp); + + if (!create_shader_module(demo->device, vert_shader_code, file_len, + &vert_shader_module)) { + goto cleanup; + } + + fp = fopen("shaders/demo.frag.spv", "r"); + if (!fp) { + fprintf(stderr, "Couldn't open shaders/demo.frag.spv\n"); + return false; + } + fseek(fp, 0, SEEK_END); + file_len = ftell(fp); + frag_shader_code = malloc(file_len); + fseek(fp, 0, 0); + fread(frag_shader_code, 1, file_len, fp); + fclose(fp); + + if (!create_shader_module(demo->device, frag_shader_code, file_len, + &frag_shader_module)) { + goto cleanup; + } + + memset(&vert_shader_stage_info, 0, sizeof(VkPipelineShaderStageCreateInfo)); + vert_shader_stage_info.sType = + VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + vert_shader_stage_info.stage = VK_SHADER_STAGE_VERTEX_BIT; + vert_shader_stage_info.module = vert_shader_module; + vert_shader_stage_info.pName = "main"; + + memset(&frag_shader_stage_info, 0, sizeof(VkPipelineShaderStageCreateInfo)); + frag_shader_stage_info.sType = + VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + frag_shader_stage_info.stage = VK_SHADER_STAGE_FRAGMENT_BIT; + frag_shader_stage_info.module = frag_shader_module; + frag_shader_stage_info.pName = "main"; + + shader_stages[0] = vert_shader_stage_info; + shader_stages[1] = frag_shader_stage_info; + + memset(&vertex_input_info, 0, sizeof(VkPipelineVertexInputStateCreateInfo)); + vertex_input_info.sType = + VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; + + memset(&input_assembly, 0, sizeof(VkPipelineInputAssemblyStateCreateInfo)); + input_assembly.sType = + VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; + input_assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + input_assembly.primitiveRestartEnable = VK_FALSE; + + memset(&viewport, 0, sizeof(VkViewport)); + viewport.x = 0.0f; + viewport.y = 0.0f; + viewport.width = (float)demo->swap_chain_image_extent.width; + viewport.height = (float)demo->swap_chain_image_extent.height; + viewport.minDepth = 0.0f; + viewport.maxDepth = 1.0f; + + memset(&scissor, 0, sizeof(VkRect2D)); + scissor.extent.width = demo->swap_chain_image_extent.width; + scissor.extent.height = demo->swap_chain_image_extent.height; + + memset(&viewport_state, 0, sizeof(VkPipelineViewportStateCreateInfo)); + viewport_state.sType = + VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; + viewport_state.viewportCount = 1; + viewport_state.pViewports = &viewport; + viewport_state.scissorCount = 1; + viewport_state.pScissors = &scissor; + + memset(&rasterizer, 0, sizeof(VkPipelineRasterizationStateCreateInfo)); + rasterizer.sType = + VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + rasterizer.depthClampEnable = VK_FALSE; + rasterizer.rasterizerDiscardEnable = VK_FALSE; + rasterizer.polygonMode = VK_POLYGON_MODE_FILL; + rasterizer.lineWidth = 1.0f; + rasterizer.cullMode = VK_CULL_MODE_FRONT_BIT; + rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + rasterizer.depthBiasEnable = VK_FALSE; + + memset(&multisampling, 0, sizeof(VkPipelineMultisampleStateCreateInfo)); + multisampling.sType = + VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; + multisampling.sampleShadingEnable = VK_FALSE; + multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + + memset(&color_blend_attachment, 0, + sizeof(VkPipelineColorBlendAttachmentState)); + color_blend_attachment.colorWriteMask = + VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | + VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; + color_blend_attachment.blendEnable = VK_TRUE; + color_blend_attachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; + color_blend_attachment.dstColorBlendFactor = + VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; + color_blend_attachment.colorBlendOp = VK_BLEND_OP_ADD; + color_blend_attachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; + color_blend_attachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; + color_blend_attachment.alphaBlendOp = VK_BLEND_OP_ADD; + + memset(&color_blending, 0, sizeof(VkPipelineColorBlendStateCreateInfo)); + color_blending.sType = + VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; + color_blending.logicOpEnable = VK_FALSE; + color_blending.logicOp = VK_LOGIC_OP_COPY; + color_blending.attachmentCount = 1; + color_blending.pAttachments = &color_blend_attachment; + color_blending.blendConstants[0] = 1.0f; + color_blending.blendConstants[1] = 1.0f; + color_blending.blendConstants[2] = 1.0f; + color_blending.blendConstants[3] = 1.0f; + + memset(&pipeline_layout_info, 0, sizeof(VkPipelineLayoutCreateInfo)); + pipeline_layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + pipeline_layout_info.setLayoutCount = 0; + pipeline_layout_info.pushConstantRangeCount = 0; + pipeline_layout_info.setLayoutCount = 1; + pipeline_layout_info.pSetLayouts = &demo->descriptor_set_layout; + + result = vkCreatePipelineLayout(demo->device, &pipeline_layout_info, NULL, + &demo->pipeline_layout); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreatePipelineLayout failed: %d\n", result); + goto cleanup; + } + + memset(&pipeline_info, 0, sizeof(VkGraphicsPipelineCreateInfo)); + pipeline_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + pipeline_info.stageCount = 2; + pipeline_info.pStages = shader_stages; + pipeline_info.pVertexInputState = &vertex_input_info; + pipeline_info.pInputAssemblyState = &input_assembly; + pipeline_info.pViewportState = &viewport_state; + pipeline_info.pRasterizationState = &rasterizer; + pipeline_info.pMultisampleState = &multisampling; + pipeline_info.pColorBlendState = &color_blending; + pipeline_info.layout = demo->pipeline_layout; + pipeline_info.renderPass = demo->render_pass; + pipeline_info.basePipelineHandle = NULL; + + result = vkCreateGraphicsPipelines(demo->device, NULL, 1, &pipeline_info, + NULL, &demo->pipeline); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateGraphicsPipelines failed: %d\n", result); + goto cleanup; + } + ret = true; +cleanup: + if (frag_shader_module) { + vkDestroyShaderModule(demo->device, frag_shader_module, NULL); + } + if (frag_shader_code) { + free(frag_shader_code); + } + if (vert_shader_module) { + vkDestroyShaderModule(demo->device, vert_shader_module, NULL); + } + if (vert_shader_code) { + free(vert_shader_code); + } + + return ret; +} + +bool create_command_pool(struct vulkan_demo *demo) { + VkCommandPoolCreateInfo pool_info; + VkResult result; + + memset(&pool_info, 0, sizeof(VkCommandPoolCreateInfo)); + pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; + pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + pool_info.queueFamilyIndex = demo->indices.graphics; + + result = vkCreateCommandPool(demo->device, &pool_info, NULL, + &demo->command_pool); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateCommandPool failed: %d\n", result); + return false; + } + return true; +} + +bool create_command_buffers(struct vulkan_demo *demo) { + VkCommandBufferAllocateInfo alloc_info; + VkResult result; + + demo->command_buffers = + malloc(demo->swap_chain_images_len * sizeof(VkCommandBuffer)); + + memset(&alloc_info, 0, sizeof(VkCommandBufferAllocateInfo)); + alloc_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + alloc_info.commandPool = demo->command_pool; + alloc_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + alloc_info.commandBufferCount = demo->swap_chain_images_len; + + result = vkAllocateCommandBuffers(demo->device, &alloc_info, + demo->command_buffers); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkAllocateCommandBuffers failed: %d\n", result); + return false; + } + + return true; +} + +bool create_semaphores(struct vulkan_demo *demo) { + VkSemaphoreCreateInfo semaphore_info; + VkResult result; + + memset(&semaphore_info, 0, sizeof(VkSemaphoreCreateInfo)); + semaphore_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; + result = vkCreateSemaphore(demo->device, &semaphore_info, NULL, + &demo->image_available); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateSemaphore failed: %d\n", result); + return false; + } + result = vkCreateSemaphore(demo->device, &semaphore_info, NULL, + &demo->render_finished); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateSemaphore failed: %d\n", result); + return false; + } + return true; +} + +bool create_fence(struct vulkan_demo *demo) { + VkResult result; + VkFenceCreateInfo fence_create_info; + + memset(&fence_create_info, 0, sizeof(VkFenceCreateInfo)); + fence_create_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; + fence_create_info.flags = VK_FENCE_CREATE_SIGNALED_BIT; + + result = vkCreateFence(demo->device, &fence_create_info, NULL, + &demo->render_fence); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateFence failed: %d\n", result); + return false; + } + return true; +} + +bool create_swap_chain_related_resources(struct vulkan_demo *demo) { + if (!create_swap_chain(demo)) { + return false; + } + if (!create_swap_chain_image_views(demo)) { + return false; + } + if (!create_overlay_images(demo)) { + return false; + } + if (!create_render_pass(demo)) { + return false; + } + if (!create_framebuffers(demo)) { + return false; + } + if (!create_graphics_pipeline(demo)) { + return false; + } + return true; +} + +bool destroy_swap_chain_related_resources(struct vulkan_demo *demo) { + uint32_t i; + VkResult result; + + result = vkQueueWaitIdle(demo->graphics_queue); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkQueueWaitIdle failed: %d\n", result); + return false; + } + + for (i = 0; i < demo->swap_chain_images_len; i++) { + vkDestroyFramebuffer(demo->device, demo->framebuffers[i], NULL); + vkDestroyImageView(demo->device, demo->overlay_image_views[i], NULL); + vkDestroyImage(demo->device, demo->overlay_images[i], NULL); + vkFreeMemory(demo->device, demo->overlay_image_memories[i], NULL); + vkDestroyImageView(demo->device, demo->swap_chain_image_views[i], NULL); + } + vkDestroySwapchainKHR(demo->device, demo->swap_chain, NULL); + vkDestroyRenderPass(demo->device, demo->render_pass, NULL); + vkDestroyPipeline(demo->device, demo->pipeline, NULL); + vkDestroyPipelineLayout(demo->device, demo->pipeline_layout, NULL); + return true; +} + +bool create_demo_texture(struct vulkan_demo *demo) { + VkResult result; + VkMemoryRequirements mem_requirements; + VkPhysicalDeviceMemoryProperties mem_properties; + int found; + uint32_t i; + VkImageCreateInfo image_info; + VkMemoryAllocateInfo alloc_info; + VkImageViewCreateInfo image_view_info; + VkBufferCreateInfo buffer_info; + struct { + VkDeviceMemory memory; + VkBuffer buffer; + } staging_buffer; + void *data; + VkCommandBuffer command_buffer; + VkCommandBufferBeginInfo begin_info; + VkImageMemoryBarrier image_transfer_dst_memory_barrier; + VkBufferImageCopy buffer_copy_region; + VkImageMemoryBarrier image_shader_memory_barrier; + VkFence fence; + VkFenceCreateInfo fence_create; + VkSubmitInfo submit_info; + + memset(&image_info, 0, sizeof(VkImageCreateInfo)); + image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + image_info.imageType = VK_IMAGE_TYPE_2D; + image_info.extent.width = 2; + image_info.extent.height = 2; + image_info.extent.depth = 1; + image_info.mipLevels = 1; + image_info.arrayLayers = 1; + image_info.format = VK_FORMAT_R8_UNORM; + image_info.tiling = VK_IMAGE_TILING_LINEAR; + image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + image_info.usage = + VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; + image_info.samples = VK_SAMPLE_COUNT_1_BIT; + image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + + memset(&alloc_info, 0, sizeof(VkMemoryAllocateInfo)); + alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + + memset(&image_view_info, 0, sizeof(VkImageViewCreateInfo)); + image_view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + image_view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + image_view_info.format = VK_FORMAT_R8_UNORM; + image_view_info.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; + image_view_info.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; + image_view_info.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; + image_view_info.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; + image_view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + image_view_info.subresourceRange.baseMipLevel = 0; + image_view_info.subresourceRange.levelCount = 1; + image_view_info.subresourceRange.baseArrayLayer = 0; + image_view_info.subresourceRange.layerCount = 1; + + result = vkCreateImage(demo->device, &image_info, NULL, + &demo->demo_texture_image); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateImage failed: %d\n", result); + return false; + } + + vkGetImageMemoryRequirements(demo->device, demo->demo_texture_image, + &mem_requirements); + + alloc_info.allocationSize = mem_requirements.size; + + vkGetPhysicalDeviceMemoryProperties(demo->physical_device, &mem_properties); + found = 0; + for (i = 0; i < mem_properties.memoryTypeCount; i++) { + if ((mem_requirements.memoryTypeBits & (1 << i)) && + (mem_properties.memoryTypes[i].propertyFlags & + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) { + found = 1; + break; + } + } + if (!found) { + fprintf(stderr, "failed to find suitable memory for demo texture!\n"); + return false; + } + alloc_info.memoryTypeIndex = i; + result = vkAllocateMemory(demo->device, &alloc_info, NULL, + &demo->demo_texture_memory); + if (result != VK_SUCCESS) { + fprintf(stderr, + "failed to allocate vulkan memory for demo texture: %d!\n", + result); + return false; + } + result = vkBindImageMemory(demo->device, demo->demo_texture_image, + demo->demo_texture_memory, 0); + if (result != VK_SUCCESS) { + fprintf(stderr, "Couldn't bind image memory for demo texture: %d\n", + result); + return false; + } + + image_view_info.image = demo->demo_texture_image; + result = vkCreateImageView(demo->device, &image_view_info, NULL, + &demo->demo_texture_image_view); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateImageView failed for demo texture: %d\n", + result); + return false; + } + + memset(&buffer_info, 0, sizeof(VkBufferCreateInfo)); + buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + buffer_info.size = alloc_info.allocationSize; + buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + + result = vkCreateBuffer(demo->device, &buffer_info, NULL, + &staging_buffer.buffer); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateBuffer failed for demo texture: %d\n", result); + return false; + } + vkGetBufferMemoryRequirements(demo->device, staging_buffer.buffer, + &mem_requirements); + + alloc_info.allocationSize = mem_requirements.size; + found = 0; + for (i = 0; i < mem_properties.memoryTypeCount; i++) { + if ((mem_requirements.memoryTypeBits & (1 << i)) && + (mem_properties.memoryTypes[i].propertyFlags & + (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) == + (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) { + found = 1; + break; + } + } + if (!found) { + fprintf(stderr, "failed to find suitable staging buffer memory for " + "demo texture!\n"); + return false; + } + alloc_info.memoryTypeIndex = i; + result = vkAllocateMemory(demo->device, &alloc_info, NULL, + &staging_buffer.memory); + if (!found) { + fprintf(stderr, "vkAllocateMemory failed for demo texture: %d\n", + result); + return false; + } + result = vkBindBufferMemory(demo->device, staging_buffer.buffer, + staging_buffer.memory, 0); + if (!found) { + fprintf(stderr, "vkBindBufferMemory failed for demo texture: %d\n", + result); + return false; + } + + result = vkMapMemory(demo->device, staging_buffer.memory, 0, + sizeof(uint32_t), 0, &data); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkMapMemory failed for demo texture: %d\n", result); + return false; + } + *((uint32_t *)data) = 0x00FFFF00; + vkUnmapMemory(demo->device, staging_buffer.memory); + + memset(&begin_info, 0, sizeof(VkCommandBufferBeginInfo)); + begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + + command_buffer = demo->command_buffers[0]; + result = vkBeginCommandBuffer(command_buffer, &begin_info); + + memset(&image_transfer_dst_memory_barrier, 0, sizeof(VkImageMemoryBarrier)); + image_transfer_dst_memory_barrier.sType = + VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + image_transfer_dst_memory_barrier.image = demo->demo_texture_image; + image_transfer_dst_memory_barrier.srcQueueFamilyIndex = + VK_QUEUE_FAMILY_IGNORED; + image_transfer_dst_memory_barrier.dstQueueFamilyIndex = + VK_QUEUE_FAMILY_IGNORED; + image_transfer_dst_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + image_transfer_dst_memory_barrier.newLayout = + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + image_transfer_dst_memory_barrier.subresourceRange.aspectMask = + VK_IMAGE_ASPECT_COLOR_BIT; + image_transfer_dst_memory_barrier.subresourceRange.levelCount = 1; + image_transfer_dst_memory_barrier.subresourceRange.layerCount = 1; + image_transfer_dst_memory_barrier.dstAccessMask = + VK_ACCESS_TRANSFER_WRITE_BIT; + + vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, + &image_transfer_dst_memory_barrier); + + memset(&buffer_copy_region, 0, sizeof(VkBufferImageCopy)); + buffer_copy_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + buffer_copy_region.imageSubresource.layerCount = 1; + buffer_copy_region.imageExtent.width = 2; + buffer_copy_region.imageExtent.height = 2; + buffer_copy_region.imageExtent.depth = 1; + + vkCmdCopyBufferToImage( + command_buffer, staging_buffer.buffer, demo->demo_texture_image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &buffer_copy_region); + + memset(&image_shader_memory_barrier, 0, sizeof(VkImageMemoryBarrier)); + image_shader_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + image_shader_memory_barrier.image = demo->demo_texture_image; + image_shader_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + image_shader_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + image_shader_memory_barrier.oldLayout = + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + image_shader_memory_barrier.newLayout = + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + image_shader_memory_barrier.subresourceRange.aspectMask = + VK_IMAGE_ASPECT_COLOR_BIT; + image_shader_memory_barrier.subresourceRange.levelCount = 1; + image_shader_memory_barrier.subresourceRange.layerCount = 1; + image_shader_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + image_shader_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT, + + vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, NULL, 0, + NULL, 1, &image_shader_memory_barrier); + + result = vkEndCommandBuffer(command_buffer); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkEndCommandBuffer failed for demo texture: %d\n", + result); + return false; + } + + memset(&fence_create, 0, sizeof(VkFenceCreateInfo)); + fence_create.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; + result = vkCreateFence(demo->device, &fence_create, NULL, &fence); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateFence failed for demo texture: %d\n", result); + return false; + } + + memset(&submit_info, 0, sizeof(VkSubmitInfo)); + submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submit_info.commandBufferCount = 1; + submit_info.pCommandBuffers = &command_buffer; + + result = vkQueueSubmit(demo->graphics_queue, 1, &submit_info, fence); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkQueueSubmit failed for demo texture: %d\n", result); + return false; + } + result = vkWaitForFences(demo->device, 1, &fence, VK_TRUE, UINT64_MAX); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkWaitForFences failed for demo texture: %d\n", + result); + return false; + } + + vkDestroyBuffer(demo->device, staging_buffer.buffer, NULL); + vkFreeMemory(demo->device, staging_buffer.memory, NULL); + vkDestroyFence(demo->device, fence, NULL); + + return true; +} + +bool create_vulkan_demo(struct vulkan_demo *demo) { + if (!create_instance(demo)) { + return false; + } + if (!create_debug_callback(demo)) { + return false; + } + if (!create_surface(demo)) { + return false; + } + if (!create_physical_device(demo)) { + return false; + } + if (!create_logical_device(demo)) { + return false; + } + if (!create_sampler(demo)) { + return false; + } + if (!create_descriptor_set_layout(demo)) { + return false; + } + if (!create_swap_chain_related_resources(demo)) { + return false; + } + if (!create_descriptor_pool(demo)) { + return false; + } + if (!create_descriptor_sets(demo)) { + return false; + } + if (!create_command_pool(demo)) { + return false; + } + if (!create_command_buffers(demo)) { + return false; + } + if (!create_semaphores(demo)) { + return false; + } + if (!create_fence(demo)) { + return false; + } + if (!create_demo_texture(demo)) { + return false; + } + + return true; +} + +bool recreate_swap_chain(struct vulkan_demo *demo) { + printf("recreating swapchain\n"); + if (!destroy_swap_chain_related_resources(demo)) { + return false; + } + if (!create_swap_chain_related_resources(demo)) { + return false; + } + update_descriptor_sets(demo); + nk_glfw3_resize(demo->swap_chain_image_extent.width, + demo->swap_chain_image_extent.height); + return true; +} + +bool render(struct vulkan_demo *demo, struct nk_colorf *bg, + VkSemaphore wait_semaphore, uint32_t image_index) { + VkCommandBufferBeginInfo command_buffer_begin_info; + VkCommandBuffer command_buffer; + VkRenderPassBeginInfo render_pass_info; + VkSubmitInfo submit_info; + VkPipelineStageFlags wait_stage = + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + VkResult result; + VkPresentInfoKHR present_info; + VkClearValue clear_color; + + memcpy(&clear_color.color, bg, sizeof(VkClearColorValue)); + + memset(&command_buffer_begin_info, 0, sizeof(VkCommandBufferBeginInfo)); + command_buffer_begin_info.sType = + VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + + command_buffer = demo->command_buffers[image_index]; + result = vkBeginCommandBuffer(command_buffer, &command_buffer_begin_info); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkBeginCommandBuffer failed: %d\n", result); + return false; + } + + memset(&render_pass_info, 0, sizeof(VkRenderPassBeginInfo)); + render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + render_pass_info.renderPass = demo->render_pass; + render_pass_info.framebuffer = demo->framebuffers[image_index]; + render_pass_info.renderArea.offset.x = 0; + render_pass_info.renderArea.offset.y = 0; + render_pass_info.renderArea.extent = demo->swap_chain_image_extent; + render_pass_info.clearValueCount = 1; + render_pass_info.pClearValues = &clear_color; + + vkCmdBeginRenderPass(command_buffer, &render_pass_info, + VK_SUBPASS_CONTENTS_INLINE); + + vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, + demo->pipeline); + vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, + demo->pipeline_layout, 0, 1, + &demo->descriptor_sets[image_index], 0, NULL); + vkCmdDraw(command_buffer, 3, 1, 0, 0); + + vkCmdEndRenderPass(command_buffer); + + result = vkEndCommandBuffer(command_buffer); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkEndCommandBuffer failed: %d\n", result); + return false; + } + + memset(&submit_info, 0, sizeof(VkSubmitInfo)); + submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submit_info.waitSemaphoreCount = 1; + submit_info.pWaitSemaphores = &wait_semaphore; + submit_info.pWaitDstStageMask = &wait_stage; + submit_info.commandBufferCount = 1; + submit_info.pCommandBuffers = &demo->command_buffers[image_index]; + submit_info.signalSemaphoreCount = 1; + submit_info.pSignalSemaphores = &demo->render_finished; + + result = vkQueueSubmit(demo->graphics_queue, 1, &submit_info, + demo->render_fence); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkQueueSubmit failed: %d\n", result); + return false; + } + + memset(&present_info, 0, sizeof(VkPresentInfoKHR)); + present_info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; + present_info.waitSemaphoreCount = 1; + present_info.pWaitSemaphores = &demo->render_finished; + present_info.swapchainCount = 1; + present_info.pSwapchains = &demo->swap_chain; + present_info.pImageIndices = &image_index; + + result = vkQueuePresentKHR(demo->present_queue, &present_info); + + if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR) { + recreate_swap_chain(demo); + } else if (result != VK_SUCCESS) { + fprintf(stderr, "vkQueuePresentKHR failed: %d\n", result); + return false; + } + return true; +} + +VkResult +destroy_debug_utils_messenger_ext(VkInstance instance, + VkDebugUtilsMessengerEXT debugMessenger, + const VkAllocationCallbacks *pAllocator) { + PFN_vkDestroyDebugUtilsMessengerEXT func = + (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr( + instance, "vkDestroyDebugUtilsMessengerEXT"); + if (func != NULL) { + func(instance, debugMessenger, pAllocator); + return VK_SUCCESS; + } else { + return VK_ERROR_EXTENSION_NOT_PRESENT; + } +} + +bool cleanup(struct vulkan_demo *demo) { + VkResult result; + + printf("cleaning up\n"); + result = vkDeviceWaitIdle(demo->device); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkDeviceWaitIdle failed: %d\n", result); + return false; + } + + destroy_swap_chain_related_resources(demo); + + vkFreeCommandBuffers(demo->device, demo->command_pool, + demo->swap_chain_images_len, demo->command_buffers); + vkDestroyCommandPool(demo->device, demo->command_pool, NULL); + vkDestroySampler(demo->device, demo->sampler, NULL); + vkDestroySemaphore(demo->device, demo->render_finished, NULL); + vkDestroySemaphore(demo->device, demo->image_available, NULL); + vkDestroyFence(demo->device, demo->render_fence, NULL); + + vkDestroyImage(demo->device, demo->demo_texture_image, NULL); + vkDestroyImageView(demo->device, demo->demo_texture_image_view, NULL); + vkFreeMemory(demo->device, demo->demo_texture_memory, NULL); + + vkDestroyDescriptorSetLayout(demo->device, demo->descriptor_set_layout, + NULL); + vkDestroyDescriptorPool(demo->device, demo->descriptor_pool, NULL); + + vkDestroyDevice(demo->device, NULL); + vkDestroySurfaceKHR(demo->instance, demo->surface, NULL); + + result = destroy_debug_utils_messenger_ext(demo->instance, + demo->debugMessenger, NULL); + if (result != VK_SUCCESS) { + fprintf(stderr, "Couldn't destroy debug messenger: %d\n", result); + return false; + } + vkDestroyInstance(demo->instance, NULL); + if (demo->swap_chain_images) { + free(demo->swap_chain_images); + } + if (demo->swap_chain_image_views) { + free(demo->swap_chain_image_views); + } + + if (demo->overlay_images) { + free(demo->overlay_images); + } + if (demo->overlay_image_views) { + free(demo->overlay_image_views); + } + if (demo->overlay_image_memories) { + free(demo->overlay_image_memories); + } + + if (demo->descriptor_sets) { + free(demo->descriptor_sets); + } + if (demo->framebuffers) { + free(demo->framebuffers); + } + if (demo->command_buffers) { + free(demo->command_buffers); + } + + return true; +} + +int main(void) { + struct vulkan_demo demo; + struct nk_context *ctx; + struct nk_colorf bg; + struct nk_image img; + uint32_t image_index; + VkResult result; + VkSemaphore nk_semaphore; + + glfwSetErrorCallback(glfw_error_callback); + if (!glfwInit()) { + fprintf(stderr, "[GFLW] failed to init!\n"); + exit(1); + } + glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); + memset(&demo, 0, sizeof(struct vulkan_demo)); + demo.win = + glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Demo", NULL, NULL); + + if (!create_vulkan_demo(&demo)) { + fprintf(stderr, "failed to create vulkan demo!\n"); + exit(1); + } + ctx = nk_glfw3_init( + demo.win, demo.device, demo.physical_device, demo.indices.graphics, + demo.overlay_image_views, demo.swap_chain_images_len, + demo.swap_chain_image_format, NK_GLFW3_INSTALL_CALLBACKS, + MAX_VERTEX_BUFFER, MAX_ELEMENT_BUFFER); + /* Load Fonts: if none of these are loaded a default font will be used */ + /* Load Cursor: if you uncomment cursor loading please hide the cursor */ + { + struct nk_font_atlas *atlas; + nk_glfw3_font_stash_begin(&atlas); + /*struct nk_font *droid = nk_font_atlas_add_from_file(atlas, + * "../../../extra_font/DroidSans.ttf", 14, 0);*/ + /*struct nk_font *roboto = nk_font_atlas_add_from_file(atlas, + * "../../../extra_font/Roboto-Regular.ttf", 14, 0);*/ + /*struct nk_font *future = nk_font_atlas_add_from_file(atlas, + * "../../../extra_font/kenvector_future_thin.ttf", 13, 0);*/ + /*struct nk_font *clean = nk_font_atlas_add_from_file(atlas, + * "../../../extra_font/ProggyClean.ttf", 12, 0);*/ + /*struct nk_font *tiny = nk_font_atlas_add_from_file(atlas, + * "../../../extra_font/ProggyTiny.ttf", 10, 0);*/ + /*struct nk_font *cousine = nk_font_atlas_add_from_file(atlas, + * "../../../extra_font/Cousine-Regular.ttf", 13, 0);*/ + nk_glfw3_font_stash_end(demo.graphics_queue); + /*nk_style_load_all_cursors(ctx, atlas->cursors);*/ + /*nk_style_set_font(ctx, &droid->handle);*/} + +#ifdef INCLUDE_STYLE + /* ease regression testing during Nuklear release process; not needed for + * anything else */ +#ifdef STYLE_WHITE + set_style(ctx, THEME_WHITE); +#elif defined(STYLE_RED) + set_style(ctx, THEME_RED); +#elif defined(STYLE_BLUE) + set_style(ctx, THEME_BLUE); +#elif defined(STYLE_DARK) + set_style(ctx, THEME_DARK); +#endif +#endif + + img = nk_image_ptr(demo.demo_texture_image_view); + bg.r = 0.10f, bg.g = 0.18f, bg.b = 0.24f, bg.a = 1.0f; + while (!glfwWindowShouldClose(demo.win)) { + /* Input */ + glfwPollEvents(); + nk_glfw3_new_frame(); + + /* GUI */ + if (nk_begin(ctx, "Demo", nk_rect(50, 50, 230, 250), + NK_WINDOW_BORDER | NK_WINDOW_MOVABLE | NK_WINDOW_SCALABLE | + NK_WINDOW_MINIMIZABLE | NK_WINDOW_TITLE)) { + enum { EASY, HARD }; + static int op = EASY; + static int property = 20; + nk_layout_row_static(ctx, 30, 80, 1); + if (nk_button_label(ctx, "button")) + fprintf(stdout, "button pressed\n"); + + nk_layout_row_dynamic(ctx, 30, 2); + if (nk_option_label(ctx, "easy", op == EASY)) + op = EASY; + if (nk_option_label(ctx, "hard", op == HARD)) + op = HARD; + + nk_layout_row_dynamic(ctx, 25, 1); + nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); + + nk_layout_row_dynamic(ctx, 20, 1); + nk_label(ctx, "background:", NK_TEXT_LEFT); + nk_layout_row_dynamic(ctx, 25, 1); + if (nk_combo_begin_color(ctx, nk_rgb_cf(bg), + nk_vec2(nk_widget_width(ctx), 400))) { + nk_layout_row_dynamic(ctx, 120, 1); + bg = nk_color_picker(ctx, bg, NK_RGBA); + nk_layout_row_dynamic(ctx, 25, 1); + bg.r = nk_propertyf(ctx, "#R:", 0, bg.r, 1.0f, 0.01f, 0.005f); + bg.g = nk_propertyf(ctx, "#G:", 0, bg.g, 1.0f, 0.01f, 0.005f); + bg.b = nk_propertyf(ctx, "#B:", 0, bg.b, 1.0f, 0.01f, 0.005f); + bg.a = nk_propertyf(ctx, "#A:", 0, bg.a, 1.0f, 0.01f, 0.005f); + nk_combo_end(ctx); + } + } + nk_end(ctx); + + /* Bindless Texture */ + if (nk_begin(ctx, "Texture", nk_rect(500, 300, 200, 200), + NK_WINDOW_BORDER | NK_WINDOW_MOVABLE | NK_WINDOW_SCALABLE | + NK_WINDOW_MINIMIZABLE | NK_WINDOW_TITLE)) { + struct nk_command_buffer *canvas = nk_window_get_canvas(ctx); + struct nk_rect total_space = nk_window_get_content_region(ctx); + nk_draw_image(canvas, total_space, &img, nk_white); + } + nk_end(ctx); + + /* -------------- EXAMPLES ---------------- */ +#ifdef INCLUDE_CALCULATOR + calculator(ctx); +#endif +#ifdef INCLUDE_CANVAS + canvas(ctx); +#endif +#ifdef INCLUDE_OVERVIEW + overview(ctx); +#endif +#ifdef INCLUDE_NODE_EDITOR + node_editor(ctx); +#endif + /* ----------------------------------------- */ + + result = vkWaitForFences(demo.device, 1, &demo.render_fence, VK_TRUE, + UINT64_MAX); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkWaitForFences failed: %d\n", result); + return false; + } + + result = vkResetFences(demo.device, 1, &demo.render_fence); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkResetFences failed: %d\n", result); + return false; + } + + result = + vkAcquireNextImageKHR(demo.device, demo.swap_chain, UINT64_MAX, + demo.image_available, NULL, &image_index); + + if (result == VK_ERROR_OUT_OF_DATE_KHR) { + continue; + } + if (result != VK_SUCCESS) { + fprintf(stderr, "vkAcquireNextImageKHR failed: %d\n", result); + return false; + } + + /* Draw */ + nk_semaphore = + nk_glfw3_render(demo.graphics_queue, image_index, + demo.image_available, NK_ANTI_ALIASING_ON); + if (!render(&demo, &bg, nk_semaphore, image_index)) { + fprintf(stderr, "render failed\n"); + return false; + } + } + nk_glfw3_shutdown(); + cleanup(&demo); + glfwTerminate(); + return 0; +} diff --git a/demo/glfw_vulkan/nuklear_glfw_vulkan.h b/demo/glfw_vulkan/nuklear_glfw_vulkan.h new file mode 100644 index 0000000..f411872 --- /dev/null +++ b/demo/glfw_vulkan/nuklear_glfw_vulkan.h @@ -0,0 +1,1647 @@ +/* + * Nuklear - 1.32.0 - public domain + * no warrenty implied; use at your own risk. + * authored from 2015-2016 by Micha Mettke + */ +/* + * ============================================================== + * + * API + * + * =============================================================== + */ +#ifndef NK_GLFW_VULKAN_H_ +#define NK_GLFW_VULKAN_H_ + +unsigned char nuklearshaders_nuklear_vert_spv[] = { + 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0b, 0x00, 0x0d, 0x00, + 0x45, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x47, 0x4c, 0x53, 0x4c, 0x2e, 0x73, 0x74, 0x64, 0x2e, 0x34, 0x35, 0x30, + 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00, + 0x0a, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x27, 0x00, 0x00, 0x00, + 0x2a, 0x00, 0x00, 0x00, 0x42, 0x00, 0x00, 0x00, 0x43, 0x00, 0x00, 0x00, + 0x03, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x00, 0xc2, 0x01, 0x00, 0x00, + 0x04, 0x00, 0x09, 0x00, 0x47, 0x4c, 0x5f, 0x41, 0x52, 0x42, 0x5f, 0x73, + 0x65, 0x70, 0x61, 0x72, 0x61, 0x74, 0x65, 0x5f, 0x73, 0x68, 0x61, 0x64, + 0x65, 0x72, 0x5f, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x00, 0x00, + 0x04, 0x00, 0x0a, 0x00, 0x47, 0x4c, 0x5f, 0x47, 0x4f, 0x4f, 0x47, 0x4c, + 0x45, 0x5f, 0x63, 0x70, 0x70, 0x5f, 0x73, 0x74, 0x79, 0x6c, 0x65, 0x5f, + 0x6c, 0x69, 0x6e, 0x65, 0x5f, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x69, + 0x76, 0x65, 0x00, 0x00, 0x04, 0x00, 0x08, 0x00, 0x47, 0x4c, 0x5f, 0x47, + 0x4f, 0x4f, 0x47, 0x4c, 0x45, 0x5f, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, + 0x65, 0x5f, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x69, 0x76, 0x65, 0x00, + 0x05, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, + 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x06, 0x00, 0x08, 0x00, 0x00, 0x00, + 0x67, 0x6c, 0x5f, 0x50, 0x65, 0x72, 0x56, 0x65, 0x72, 0x74, 0x65, 0x78, + 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x06, 0x00, 0x08, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x67, 0x6c, 0x5f, 0x50, 0x6f, 0x73, 0x69, 0x74, + 0x69, 0x6f, 0x6e, 0x00, 0x05, 0x00, 0x03, 0x00, 0x0a, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x07, 0x00, 0x0e, 0x00, 0x00, 0x00, + 0x55, 0x6e, 0x69, 0x66, 0x6f, 0x72, 0x6d, 0x42, 0x75, 0x66, 0x66, 0x65, + 0x72, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x00, 0x06, 0x00, 0x06, 0x00, + 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x72, 0x6f, 0x6a, + 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00, + 0x10, 0x00, 0x00, 0x00, 0x75, 0x62, 0x6f, 0x00, 0x05, 0x00, 0x05, 0x00, + 0x16, 0x00, 0x00, 0x00, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, + 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x27, 0x00, 0x00, 0x00, + 0x66, 0x72, 0x61, 0x67, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x04, 0x00, 0x2a, 0x00, 0x00, 0x00, 0x63, 0x6f, 0x6c, 0x6f, + 0x72, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x42, 0x00, 0x00, 0x00, + 0x66, 0x72, 0x61, 0x67, 0x55, 0x76, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00, + 0x43, 0x00, 0x00, 0x00, 0x75, 0x76, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, + 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x03, 0x00, 0x08, 0x00, 0x00, 0x00, + 0x02, 0x00, 0x00, 0x00, 0x48, 0x00, 0x04, 0x00, 0x0e, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, + 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, 0x0e, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, + 0x47, 0x00, 0x03, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, + 0x47, 0x00, 0x04, 0x00, 0x10, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x10, 0x00, 0x00, 0x00, + 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, + 0x16, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x47, 0x00, 0x04, 0x00, 0x27, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x2a, 0x00, 0x00, 0x00, + 0x1e, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, + 0x42, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x47, 0x00, 0x04, 0x00, 0x43, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x13, 0x00, 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, + 0x21, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, + 0x16, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, + 0x17, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x03, 0x00, 0x08, 0x00, 0x00, 0x00, + 0x07, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x09, 0x00, 0x00, 0x00, + 0x03, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, + 0x09, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, + 0x15, 0x00, 0x04, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x0b, 0x00, 0x00, 0x00, + 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x04, 0x00, + 0x0d, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, + 0x1e, 0x00, 0x03, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, + 0x20, 0x00, 0x04, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, + 0x0e, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x0f, 0x00, 0x00, 0x00, + 0x10, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, + 0x11, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, + 0x17, 0x00, 0x04, 0x00, 0x14, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, + 0x02, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x15, 0x00, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, + 0x15, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x2b, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, + 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f, 0x20, 0x00, 0x04, 0x00, + 0x1e, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, + 0x15, 0x00, 0x04, 0x00, 0x20, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x20, 0x00, 0x00, 0x00, + 0x21, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, + 0x22, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, + 0x3b, 0x00, 0x04, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x27, 0x00, 0x00, 0x00, + 0x03, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, 0x28, 0x00, 0x00, 0x00, + 0x20, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, + 0x29, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, + 0x3b, 0x00, 0x04, 0x00, 0x29, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x20, 0x00, 0x00, 0x00, + 0x2b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, + 0x2c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, + 0x2b, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x7f, 0x43, 0x2b, 0x00, 0x04, 0x00, 0x20, 0x00, 0x00, 0x00, + 0x36, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, + 0x20, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, + 0x20, 0x00, 0x04, 0x00, 0x41, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, + 0x14, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x41, 0x00, 0x00, 0x00, + 0x42, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, + 0x15, 0x00, 0x00, 0x00, 0x43, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x36, 0x00, 0x05, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x41, 0x00, 0x05, 0x00, 0x11, 0x00, 0x00, 0x00, + 0x12, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, + 0x3d, 0x00, 0x04, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, + 0x12, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x14, 0x00, 0x00, 0x00, + 0x17, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00, + 0x1b, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x50, 0x00, 0x07, 0x00, 0x07, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, + 0x1a, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, + 0x19, 0x00, 0x00, 0x00, 0x91, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, + 0x1d, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, + 0x41, 0x00, 0x05, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00, + 0x0a, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00, + 0x1f, 0x00, 0x00, 0x00, 0x1d, 0x00, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, + 0x22, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, + 0x0c, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, + 0x7f, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x25, 0x00, 0x00, 0x00, + 0x24, 0x00, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, 0x22, 0x00, 0x00, 0x00, + 0x26, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, + 0x21, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00, 0x26, 0x00, 0x00, 0x00, + 0x25, 0x00, 0x00, 0x00, 0x41, 0x00, 0x05, 0x00, 0x2c, 0x00, 0x00, 0x00, + 0x2d, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x00, 0x00, + 0x3d, 0x00, 0x04, 0x00, 0x20, 0x00, 0x00, 0x00, 0x2e, 0x00, 0x00, 0x00, + 0x2d, 0x00, 0x00, 0x00, 0x70, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, + 0x2f, 0x00, 0x00, 0x00, 0x2e, 0x00, 0x00, 0x00, 0x88, 0x00, 0x05, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x31, 0x00, 0x00, 0x00, 0x2f, 0x00, 0x00, 0x00, + 0x30, 0x00, 0x00, 0x00, 0x41, 0x00, 0x05, 0x00, 0x2c, 0x00, 0x00, 0x00, + 0x32, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, + 0x3d, 0x00, 0x04, 0x00, 0x20, 0x00, 0x00, 0x00, 0x33, 0x00, 0x00, 0x00, + 0x32, 0x00, 0x00, 0x00, 0x70, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, + 0x34, 0x00, 0x00, 0x00, 0x33, 0x00, 0x00, 0x00, 0x88, 0x00, 0x05, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x35, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00, + 0x30, 0x00, 0x00, 0x00, 0x41, 0x00, 0x05, 0x00, 0x2c, 0x00, 0x00, 0x00, + 0x37, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x00, + 0x3d, 0x00, 0x04, 0x00, 0x20, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, + 0x37, 0x00, 0x00, 0x00, 0x70, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, + 0x39, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x88, 0x00, 0x05, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x3a, 0x00, 0x00, 0x00, 0x39, 0x00, 0x00, 0x00, + 0x30, 0x00, 0x00, 0x00, 0x41, 0x00, 0x05, 0x00, 0x2c, 0x00, 0x00, 0x00, + 0x3c, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x00, 0x00, + 0x3d, 0x00, 0x04, 0x00, 0x20, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x00, 0x00, + 0x3c, 0x00, 0x00, 0x00, 0x70, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, + 0x3e, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x00, 0x00, 0x88, 0x00, 0x05, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, + 0x30, 0x00, 0x00, 0x00, 0x50, 0x00, 0x07, 0x00, 0x07, 0x00, 0x00, 0x00, + 0x40, 0x00, 0x00, 0x00, 0x31, 0x00, 0x00, 0x00, 0x35, 0x00, 0x00, 0x00, + 0x3a, 0x00, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00, + 0x27, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, + 0x14, 0x00, 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, 0x43, 0x00, 0x00, 0x00, + 0x3e, 0x00, 0x03, 0x00, 0x42, 0x00, 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, + 0xfd, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00 +}; +unsigned int nuklearshaders_nuklear_vert_spv_len = 1856; +unsigned char nuklearshaders_nuklear_frag_spv[] = { + 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0b, 0x00, 0x0d, 0x00, + 0x1b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x47, 0x4c, 0x53, 0x4c, 0x2e, 0x73, 0x74, 0x64, 0x2e, 0x34, 0x35, 0x30, + 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x08, 0x00, 0x04, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00, + 0x11, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, + 0x10, 0x00, 0x03, 0x00, 0x04, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, + 0x03, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x00, 0xc2, 0x01, 0x00, 0x00, + 0x04, 0x00, 0x09, 0x00, 0x47, 0x4c, 0x5f, 0x41, 0x52, 0x42, 0x5f, 0x73, + 0x65, 0x70, 0x61, 0x72, 0x61, 0x74, 0x65, 0x5f, 0x73, 0x68, 0x61, 0x64, + 0x65, 0x72, 0x5f, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x00, 0x00, + 0x04, 0x00, 0x0a, 0x00, 0x47, 0x4c, 0x5f, 0x47, 0x4f, 0x4f, 0x47, 0x4c, + 0x45, 0x5f, 0x63, 0x70, 0x70, 0x5f, 0x73, 0x74, 0x79, 0x6c, 0x65, 0x5f, + 0x6c, 0x69, 0x6e, 0x65, 0x5f, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x69, + 0x76, 0x65, 0x00, 0x00, 0x04, 0x00, 0x08, 0x00, 0x47, 0x4c, 0x5f, 0x47, + 0x4f, 0x4f, 0x47, 0x4c, 0x45, 0x5f, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, + 0x65, 0x5f, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x69, 0x76, 0x65, 0x00, + 0x05, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, + 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x09, 0x00, 0x00, 0x00, + 0x74, 0x65, 0x78, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x06, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x63, 0x75, 0x72, 0x72, + 0x65, 0x6e, 0x74, 0x54, 0x65, 0x78, 0x74, 0x75, 0x72, 0x65, 0x00, 0x00, + 0x05, 0x00, 0x04, 0x00, 0x11, 0x00, 0x00, 0x00, 0x66, 0x72, 0x61, 0x67, + 0x55, 0x76, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x15, 0x00, 0x00, 0x00, + 0x6f, 0x75, 0x74, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x05, 0x00, 0x17, 0x00, 0x00, 0x00, 0x66, 0x72, 0x61, 0x67, + 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, + 0x0d, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x47, 0x00, 0x04, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x11, 0x00, 0x00, 0x00, + 0x1e, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, + 0x15, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x47, 0x00, 0x04, 0x00, 0x17, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x13, 0x00, 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, + 0x21, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, + 0x16, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, + 0x17, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, + 0x07, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x19, 0x00, 0x09, 0x00, + 0x0a, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x03, 0x00, + 0x0b, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, + 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, + 0x3b, 0x00, 0x04, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, 0x0f, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, + 0x10, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, + 0x3b, 0x00, 0x04, 0x00, 0x10, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x14, 0x00, 0x00, 0x00, + 0x03, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, + 0x14, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, + 0x20, 0x00, 0x04, 0x00, 0x16, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x16, 0x00, 0x00, 0x00, + 0x17, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x36, 0x00, 0x05, 0x00, + 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x03, 0x00, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, 0x05, 0x00, 0x00, 0x00, + 0x3b, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, + 0x07, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x0b, 0x00, 0x00, 0x00, + 0x0e, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, + 0x0f, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, + 0x57, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, + 0x0e, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00, + 0x09, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, + 0x07, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, + 0x3d, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x19, 0x00, 0x00, 0x00, + 0x09, 0x00, 0x00, 0x00, 0x85, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, + 0x1a, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x19, 0x00, 0x00, 0x00, + 0x3e, 0x00, 0x03, 0x00, 0x15, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x00, 0x00, + 0xfd, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00 +}; +unsigned int nuklearshaders_nuklear_frag_spv_len = 860; + +#include +#include +#define GLFW_INCLUDE_VULKAN +#include + +enum nk_glfw_init_state { NK_GLFW3_DEFAULT = 0, NK_GLFW3_INSTALL_CALLBACKS }; + +NK_API struct nk_context * +nk_glfw3_init(GLFWwindow *win, VkDevice logical_device, + VkPhysicalDevice physical_device, + uint32_t graphics_queue_family_index, VkImageView *image_views, + uint32_t image_views_len, VkFormat color_format, + enum nk_glfw_init_state init_state, + VkDeviceSize max_vertex_buffer, VkDeviceSize max_element_buffer); +NK_API void nk_glfw3_shutdown(void); +NK_API void nk_glfw3_font_stash_begin(struct nk_font_atlas **atlas); +NK_API void nk_glfw3_font_stash_end(VkQueue graphics_queue); +NK_API void nk_glfw3_new_frame(); +NK_API VkSemaphore nk_glfw3_render(VkQueue graphics_queue, + uint32_t buffer_index, + VkSemaphore wait_semaphore, + enum nk_anti_aliasing AA); +NK_API void nk_glfw3_resize(uint32_t framebuffer_width, + uint32_t framebuffer_height); +NK_API void nk_glfw3_device_destroy(void); +NK_API void nk_glfw3_device_create( + VkDevice logical_device, VkPhysicalDevice physical_device, + uint32_t graphics_queue_family_index, VkImageView *image_views, + uint32_t image_views_len, VkFormat color_format, + VkDeviceSize max_vertex_buffer, VkDeviceSize max_element_buffer, + uint32_t framebuffer_width, uint32_t framebuffer_height); + +NK_API void nk_glfw3_char_callback(GLFWwindow *win, unsigned int codepoint); +NK_API void nk_gflw3_scroll_callback(GLFWwindow *win, double xoff, double yoff); +NK_API void nk_glfw3_mouse_button_callback(GLFWwindow *win, int button, + int action, int mods); + +#endif +/* + * ============================================================== + * + * IMPLEMENTATION + * + * =============================================================== + */ +#ifdef NK_GLFW_VULKAN_IMPLEMENTATION +#undef NK_GLFW_VULKAN_IMPLEMENTATION + +#ifndef NK_GLFW_TEXT_MAX +#define NK_GLFW_TEXT_MAX 256 +#endif +#ifndef NK_GLFW_DOUBLE_CLICK_LO +#define NK_GLFW_DOUBLE_CLICK_LO 0.02 +#endif +#ifndef NK_GLFW_DOUBLE_CLICK_HI +#define NK_GLFW_DOUBLE_CLICK_HI 0.2 +#endif +#ifndef NK_GLFW_MAX_TEXTURES +#define NK_GLFW_MAX_TEXTURES 256 +#endif + +#define VK_COLOR_COMPONENT_MASK_RGBA \ + VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | \ + VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT + +struct nk_glfw_vertex { + float position[2]; + float uv[2]; + nk_byte col[4]; +}; + +struct nk_vulkan_texture_descriptor_set { + VkImageView image_view; + VkDescriptorSet descriptor_set; +}; + +struct nk_glfw_device { + struct nk_buffer cmds; + struct nk_draw_null_texture tex_null; + int max_vertex_buffer; + int max_element_buffer; + VkDevice logical_device; + VkPhysicalDevice physical_device; + VkImageView *image_views; + uint32_t image_views_len; + VkFormat color_format; + VkFramebuffer *framebuffers; + uint32_t framebuffers_len; + VkCommandBuffer *command_buffers; + uint32_t command_buffers_len; + VkSampler sampler; + VkCommandPool command_pool; + VkSemaphore render_completed; + VkBuffer vertex_buffer; + VkDeviceMemory vertex_memory; + void *mapped_vertex; + VkBuffer index_buffer; + VkDeviceMemory index_memory; + void *mapped_index; + VkBuffer uniform_buffer; + VkDeviceMemory uniform_memory; + void *mapped_uniform; + VkRenderPass render_pass; + VkDescriptorPool descriptor_pool; + VkDescriptorSetLayout uniform_descriptor_set_layout; + VkDescriptorSet uniform_descriptor_set; + VkDescriptorSetLayout texture_descriptor_set_layout; + struct nk_vulkan_texture_descriptor_set *texture_descriptor_sets; + uint32_t texture_descriptor_sets_len; + VkPipelineLayout pipeline_layout; + VkPipeline pipeline; + VkImage font_image; + VkImageView font_image_view; + VkDeviceMemory font_memory; +}; + +static struct nk_glfw { + GLFWwindow *win; + int width, height; + int display_width, display_height; + struct nk_glfw_device vulkan; + struct nk_context ctx; + struct nk_font_atlas atlas; + struct nk_vec2 fb_scale; + unsigned int text[NK_GLFW_TEXT_MAX]; + int text_len; + struct nk_vec2 scroll; + double last_button_click; + int is_double_click_down; + struct nk_vec2 double_click_pos; +} glfw; + +struct Mat4f { + float m[16]; +}; + +NK_INTERN uint32_t nk_glfw3_find_memory_index( + VkPhysicalDevice physical_device, uint32_t type_filter, + VkMemoryPropertyFlags properties) { + VkPhysicalDeviceMemoryProperties mem_properties; + uint32_t i; + + vkGetPhysicalDeviceMemoryProperties(physical_device, &mem_properties); + for (i = 0; i < mem_properties.memoryTypeCount; i++) { + if ((type_filter & (1 << i)) && + (mem_properties.memoryTypes[i].propertyFlags & properties) == + properties) { + return i; + } + } + + assert(0); + return 0; +} + +NK_INTERN void nk_glfw3_create_sampler(struct nk_glfw_device *dev) { + VkResult result; + VkSamplerCreateInfo sampler_info; + memset(&sampler_info, 0, sizeof(VkSamplerCreateInfo)); + + sampler_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; + sampler_info.pNext = NULL; + sampler_info.maxAnisotropy = 1.0; + sampler_info.magFilter = VK_FILTER_LINEAR; + sampler_info.minFilter = VK_FILTER_LINEAR; + sampler_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; + sampler_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; + sampler_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; + sampler_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; + sampler_info.mipLodBias = 0.0f; + sampler_info.compareEnable = VK_FALSE; + sampler_info.compareOp = VK_COMPARE_OP_ALWAYS; + sampler_info.minLod = 0.0f; + sampler_info.maxLod = 0.0f; + sampler_info.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK; + + result = vkCreateSampler(dev->logical_device, &sampler_info, NULL, + &dev->sampler); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void +nk_glfw3_create_command_pool(struct nk_glfw_device *dev, + uint32_t graphics_queue_family_index) { + VkResult result; + VkCommandPoolCreateInfo pool_info; + memset(&pool_info, 0, sizeof(VkCommandPoolCreateInfo)); + + pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; + pool_info.queueFamilyIndex = graphics_queue_family_index; + pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + result = vkCreateCommandPool(dev->logical_device, &pool_info, NULL, + &dev->command_pool); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void nk_glfw3_create_command_buffers(struct nk_glfw_device *dev) { + VkResult result; + VkCommandBufferAllocateInfo allocate_info; + memset(&allocate_info, 0, sizeof(VkCommandBufferAllocateInfo)); + + dev->command_buffers = (VkCommandBuffer *)malloc(dev->image_views_len * + sizeof(VkCommandBuffer)); + dev->command_buffers_len = dev->image_views_len; + + allocate_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + allocate_info.commandPool = dev->command_pool; + allocate_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + allocate_info.commandBufferCount = dev->command_buffers_len; + + result = vkAllocateCommandBuffers(dev->logical_device, &allocate_info, + dev->command_buffers); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void nk_glfw3_create_semaphore(struct nk_glfw_device *dev) { + VkResult result; + VkSemaphoreCreateInfo semaphore_info; + memset(&semaphore_info, 0, sizeof(VkSemaphoreCreateInfo)); + + semaphore_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; + result = (vkCreateSemaphore(dev->logical_device, &semaphore_info, NULL, + &dev->render_completed)); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void nk_glfw3_create_buffer_and_memory(struct nk_glfw_device *dev, + VkBuffer *buffer, + VkBufferUsageFlags usage, + VkDeviceMemory *memory, + VkDeviceSize size) { + VkMemoryRequirements mem_reqs; + VkResult result; + VkBufferCreateInfo buffer_info; + VkMemoryAllocateInfo alloc_info; + + memset(&buffer_info, 0, sizeof(VkBufferCreateInfo)); + buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + buffer_info.size = size; + buffer_info.usage = usage; + buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + + result = vkCreateBuffer(dev->logical_device, &buffer_info, NULL, buffer); + NK_ASSERT(result == VK_SUCCESS); + + vkGetBufferMemoryRequirements(dev->logical_device, *buffer, &mem_reqs); + + memset(&alloc_info, 0, sizeof(VkMemoryAllocateInfo)); + alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + alloc_info.allocationSize = mem_reqs.size; + alloc_info.memoryTypeIndex = nk_glfw3_find_memory_index( + dev->physical_device, mem_reqs.memoryTypeBits, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + + result = vkAllocateMemory(dev->logical_device, &alloc_info, NULL, memory); + NK_ASSERT(result == VK_SUCCESS); + result = vkBindBufferMemory(dev->logical_device, *buffer, *memory, 0); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void nk_glfw3_create_render_pass(struct nk_glfw_device *dev) { + VkAttachmentDescription attachment; + VkAttachmentReference color_reference; + VkSubpassDependency subpass_dependency; + VkSubpassDescription subpass_description; + VkRenderPassCreateInfo render_pass_info; + VkResult result; + + memset(&attachment, 0, sizeof(VkAttachmentDescription)); + attachment.format = dev->color_format; + attachment.samples = VK_SAMPLE_COUNT_1_BIT; + attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; + attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; + attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + attachment.finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + + memset(&color_reference, 0, sizeof(VkAttachmentReference)); + color_reference.attachment = 0; + color_reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + + memset(&subpass_dependency, 0, sizeof(VkSubpassDependency)); + subpass_dependency.srcSubpass = VK_SUBPASS_EXTERNAL; + subpass_dependency.srcAccessMask = 0; + subpass_dependency.srcStageMask = + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + subpass_dependency.dstSubpass = 0; + subpass_dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | + VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + subpass_dependency.dstStageMask = + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + + memset(&subpass_description, 0, sizeof(VkSubpassDescription)); + subpass_description.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; + subpass_description.colorAttachmentCount = 1; + subpass_description.pColorAttachments = &color_reference; + + memset(&render_pass_info, 0, sizeof(VkRenderPassCreateInfo)); + render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; + render_pass_info.attachmentCount = 1; + render_pass_info.pAttachments = &attachment; + render_pass_info.subpassCount = 1; + render_pass_info.pSubpasses = &subpass_description; + render_pass_info.dependencyCount = 1; + render_pass_info.pDependencies = &subpass_dependency; + + result = vkCreateRenderPass(dev->logical_device, &render_pass_info, NULL, + &dev->render_pass); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void nk_glfw3_create_framebuffers(struct nk_glfw_device *dev, + uint32_t framebuffer_width, + uint32_t framebuffer_height) { + + VkFramebufferCreateInfo framebuffer_create_info; + uint32_t i; + VkResult result; + + dev->framebuffers = + (VkFramebuffer *)malloc(dev->image_views_len * sizeof(VkFramebuffer)); + + memset(&framebuffer_create_info, 0, sizeof(VkFramebufferCreateInfo)); + framebuffer_create_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; + framebuffer_create_info.renderPass = dev->render_pass; + framebuffer_create_info.attachmentCount = 1; + framebuffer_create_info.width = framebuffer_width; + framebuffer_create_info.height = framebuffer_height; + framebuffer_create_info.layers = 1; + for (i = 0; i < dev->image_views_len; i++) { + framebuffer_create_info.pAttachments = &dev->image_views[i]; + result = + vkCreateFramebuffer(dev->logical_device, &framebuffer_create_info, + NULL, &dev->framebuffers[i]); + NK_ASSERT(result == VK_SUCCESS); + } + dev->framebuffers_len = dev->image_views_len; +} + +NK_INTERN void nk_glfw3_create_descriptor_pool(struct nk_glfw_device *dev) { + VkDescriptorPoolSize pool_sizes[2]; + VkDescriptorPoolCreateInfo pool_info; + VkResult result; + + memset(&pool_sizes, 0, sizeof(VkDescriptorPoolSize) * 2); + pool_sizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + pool_sizes[0].descriptorCount = 1; + pool_sizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + pool_sizes[1].descriptorCount = NK_GLFW_MAX_TEXTURES; + + memset(&pool_info, 0, sizeof(VkDescriptorPoolCreateInfo)); + pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; + pool_info.poolSizeCount = 2; + pool_info.pPoolSizes = pool_sizes; + pool_info.maxSets = 1 + NK_GLFW_MAX_TEXTURES; + + result = vkCreateDescriptorPool(dev->logical_device, &pool_info, NULL, + &dev->descriptor_pool); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void +nk_glfw3_create_uniform_descriptor_set_layout(struct nk_glfw_device *dev) { + VkDescriptorSetLayoutBinding binding; + VkDescriptorSetLayoutCreateInfo descriptor_set_info; + VkResult result; + + memset(&binding, 0, sizeof(VkDescriptorSetLayoutBinding)); + binding.binding = 0; + binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + binding.descriptorCount = 1; + binding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; + + memset(&descriptor_set_info, 0, sizeof(VkDescriptorSetLayoutCreateInfo)); + descriptor_set_info.sType = + VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + descriptor_set_info.bindingCount = 1; + descriptor_set_info.pBindings = &binding; + + result = + vkCreateDescriptorSetLayout(dev->logical_device, &descriptor_set_info, + NULL, &dev->uniform_descriptor_set_layout); + + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void +nk_glfw3_create_and_update_uniform_descriptor_set(struct nk_glfw_device *dev) { + VkDescriptorSetAllocateInfo allocate_info; + VkDescriptorBufferInfo buffer_info; + VkWriteDescriptorSet descriptor_write; + VkResult result; + + memset(&allocate_info, 0, sizeof(VkDescriptorSetAllocateInfo)); + allocate_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + allocate_info.descriptorPool = dev->descriptor_pool; + allocate_info.descriptorSetCount = 1; + allocate_info.pSetLayouts = &dev->uniform_descriptor_set_layout; + + result = vkAllocateDescriptorSets(dev->logical_device, &allocate_info, + &dev->uniform_descriptor_set); + NK_ASSERT(result == VK_SUCCESS); + + memset(&buffer_info, 0, sizeof(VkDescriptorBufferInfo)); + buffer_info.buffer = dev->uniform_buffer; + buffer_info.offset = 0; + buffer_info.range = sizeof(struct Mat4f); + + memset(&descriptor_write, 0, sizeof(VkWriteDescriptorSet)); + descriptor_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptor_write.dstSet = dev->uniform_descriptor_set; + descriptor_write.dstBinding = 0; + descriptor_write.dstArrayElement = 0; + descriptor_write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + descriptor_write.descriptorCount = 1; + descriptor_write.pBufferInfo = &buffer_info; + + vkUpdateDescriptorSets(dev->logical_device, 1, &descriptor_write, 0, NULL); +} + +NK_INTERN void +nk_glfw3_create_texture_descriptor_set_layout(struct nk_glfw_device *dev) { + VkDescriptorSetLayoutBinding binding; + VkDescriptorSetLayoutCreateInfo descriptor_set_info; + VkResult result; + + memset(&binding, 0, sizeof(VkDescriptorSetLayoutBinding)); + binding.binding = 0; + binding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + binding.descriptorCount = 1; + binding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; + + memset(&descriptor_set_info, 0, sizeof(VkDescriptorSetLayoutCreateInfo)); + descriptor_set_info.sType = + VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + descriptor_set_info.bindingCount = 1; + descriptor_set_info.pBindings = &binding; + + result = + vkCreateDescriptorSetLayout(dev->logical_device, &descriptor_set_info, + NULL, &dev->texture_descriptor_set_layout); + + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void +nk_glfw3_create_texture_descriptor_sets(struct nk_glfw_device *dev) { + VkDescriptorSetLayout *descriptor_set_layouts; + VkDescriptorSet *descriptor_sets; + VkDescriptorSetAllocateInfo allocate_info; + VkResult result; + int i; + + descriptor_set_layouts = (VkDescriptorSetLayout *)malloc( + NK_GLFW_MAX_TEXTURES * sizeof(VkDescriptorSetLayout)); + descriptor_sets = (VkDescriptorSet *)malloc(NK_GLFW_MAX_TEXTURES * + sizeof(VkDescriptorSet)); + + dev->texture_descriptor_sets = + (struct nk_vulkan_texture_descriptor_set *)malloc( + NK_GLFW_MAX_TEXTURES * + sizeof(struct nk_vulkan_texture_descriptor_set)); + dev->texture_descriptor_sets_len = 0; + + for (i = 0; i < NK_GLFW_MAX_TEXTURES; i++) { + descriptor_set_layouts[i] = dev->texture_descriptor_set_layout; + descriptor_sets[i] = dev->texture_descriptor_sets[i].descriptor_set; + } + + memset(&allocate_info, 0, sizeof(VkDescriptorSetAllocateInfo)); + allocate_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + allocate_info.descriptorPool = dev->descriptor_pool; + allocate_info.descriptorSetCount = NK_GLFW_MAX_TEXTURES; + allocate_info.pSetLayouts = descriptor_set_layouts; + + result = vkAllocateDescriptorSets(dev->logical_device, &allocate_info, + descriptor_sets); + NK_ASSERT(result == VK_SUCCESS); + + for (i = 0; i < NK_GLFW_MAX_TEXTURES; i++) { + dev->texture_descriptor_sets[i].descriptor_set = descriptor_sets[i]; + } + free(descriptor_set_layouts); + free(descriptor_sets); +} + +NK_INTERN void nk_glfw3_create_pipeline_layout(struct nk_glfw_device *dev) { + VkPipelineLayoutCreateInfo pipeline_layout_info; + VkDescriptorSetLayout descriptor_set_layouts[2]; + VkResult result; + + descriptor_set_layouts[0] = dev->uniform_descriptor_set_layout; + descriptor_set_layouts[1] = dev->texture_descriptor_set_layout; + + memset(&pipeline_layout_info, 0, sizeof(VkPipelineLayoutCreateInfo)); + pipeline_layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + pipeline_layout_info.setLayoutCount = 2; + pipeline_layout_info.pSetLayouts = descriptor_set_layouts; + + result = (vkCreatePipelineLayout(dev->logical_device, &pipeline_layout_info, + NULL, &dev->pipeline_layout)); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN VkPipelineShaderStageCreateInfo +nk_glfw3_create_shader(struct nk_glfw_device *dev, unsigned char *spv_shader, + uint32_t size, VkShaderStageFlagBits stage_bit) { + VkShaderModuleCreateInfo create_info; + VkPipelineShaderStageCreateInfo shader_info; + VkShaderModule module = NULL; + VkResult result; + + memset(&create_info, 0, sizeof(VkShaderModuleCreateInfo)); + create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + create_info.codeSize = size; + create_info.pCode = (const uint32_t *)spv_shader; + result = + vkCreateShaderModule(dev->logical_device, &create_info, NULL, &module); + NK_ASSERT(result == VK_SUCCESS); + + memset(&shader_info, 0, sizeof(VkPipelineShaderStageCreateInfo)); + shader_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + shader_info.stage = stage_bit; + shader_info.module = module; + shader_info.pName = "main"; + return shader_info; +} + +NK_INTERN void nk_glfw3_create_pipeline(struct nk_glfw_device *dev) { + VkPipelineInputAssemblyStateCreateInfo input_assembly_state; + VkPipelineRasterizationStateCreateInfo rasterization_state; + VkPipelineColorBlendAttachmentState attachment_state = { + VK_TRUE, + VK_BLEND_FACTOR_SRC_ALPHA, + VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, + VK_BLEND_OP_ADD, + VK_BLEND_FACTOR_SRC_ALPHA, + VK_BLEND_FACTOR_ONE, + VK_BLEND_OP_ADD, + VK_COLOR_COMPONENT_MASK_RGBA, + }; + VkPipelineColorBlendStateCreateInfo color_blend_state; + VkPipelineViewportStateCreateInfo viewport_state; + VkPipelineMultisampleStateCreateInfo multisample_state; + VkDynamicState dynamic_states[2] = {VK_DYNAMIC_STATE_VIEWPORT, + VK_DYNAMIC_STATE_SCISSOR}; + VkPipelineDynamicStateCreateInfo dynamic_state; + VkPipelineShaderStageCreateInfo shader_stages[2]; + VkVertexInputBindingDescription vertex_input_info; + VkVertexInputAttributeDescription vertex_attribute_description[3]; + VkPipelineVertexInputStateCreateInfo vertex_input; + VkGraphicsPipelineCreateInfo pipeline_info; + VkResult result; + + memset(&input_assembly_state, 0, + sizeof(VkPipelineInputAssemblyStateCreateInfo)); + input_assembly_state.sType = + VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; + input_assembly_state.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + input_assembly_state.primitiveRestartEnable = VK_FALSE; + + memset(&rasterization_state, 0, + sizeof(VkPipelineRasterizationStateCreateInfo)); + rasterization_state.sType = + VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + rasterization_state.polygonMode = VK_POLYGON_MODE_FILL; + rasterization_state.cullMode = VK_CULL_MODE_NONE; + rasterization_state.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + rasterization_state.lineWidth = 1.0f; + + memset(&color_blend_state, 0, sizeof(VkPipelineColorBlendStateCreateInfo)); + color_blend_state.sType = + VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; + color_blend_state.attachmentCount = 1; + color_blend_state.pAttachments = &attachment_state; + + memset(&viewport_state, 0, sizeof(VkPipelineViewportStateCreateInfo)); + viewport_state.sType = + VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; + viewport_state.viewportCount = 1; + viewport_state.scissorCount = 1; + + memset(&multisample_state, 0, sizeof(VkPipelineMultisampleStateCreateInfo)); + multisample_state.sType = + VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; + multisample_state.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + + memset(&dynamic_state, 0, sizeof(VkPipelineDynamicStateCreateInfo)); + dynamic_state.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; + dynamic_state.pDynamicStates = dynamic_states; + dynamic_state.dynamicStateCount = 2; + + shader_stages[0] = nk_glfw3_create_shader( + dev, nuklearshaders_nuklear_vert_spv, + nuklearshaders_nuklear_vert_spv_len, VK_SHADER_STAGE_VERTEX_BIT); + shader_stages[1] = nk_glfw3_create_shader( + dev, nuklearshaders_nuklear_frag_spv, + nuklearshaders_nuklear_frag_spv_len, VK_SHADER_STAGE_FRAGMENT_BIT); + + memset(&vertex_input_info, 0, sizeof(VkVertexInputBindingDescription)); + vertex_input_info.binding = 0; + vertex_input_info.stride = sizeof(struct nk_glfw_vertex); + vertex_input_info.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; + + memset(&vertex_attribute_description, 0, + sizeof(VkVertexInputAttributeDescription) * 3); + vertex_attribute_description[0].location = 0; + vertex_attribute_description[0].format = VK_FORMAT_R32G32_SFLOAT; + vertex_attribute_description[0].offset = + NK_OFFSETOF(struct nk_glfw_vertex, position); + vertex_attribute_description[1].location = 1; + vertex_attribute_description[1].format = VK_FORMAT_R32G32_SFLOAT; + vertex_attribute_description[1].offset = + NK_OFFSETOF(struct nk_glfw_vertex, uv); + vertex_attribute_description[2].location = 2; + vertex_attribute_description[2].format = VK_FORMAT_R8G8B8A8_UINT; + vertex_attribute_description[2].offset = + NK_OFFSETOF(struct nk_glfw_vertex, col); + + memset(&vertex_input, 0, sizeof(VkPipelineVertexInputStateCreateInfo)); + vertex_input.sType = + VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; + vertex_input.vertexBindingDescriptionCount = 1; + vertex_input.pVertexBindingDescriptions = &vertex_input_info; + vertex_input.vertexAttributeDescriptionCount = 3; + vertex_input.pVertexAttributeDescriptions = vertex_attribute_description; + + memset(&pipeline_info, 0, sizeof(VkGraphicsPipelineCreateInfo)); + pipeline_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + pipeline_info.flags = 0; + pipeline_info.stageCount = 2; + pipeline_info.pStages = shader_stages; + pipeline_info.pVertexInputState = &vertex_input; + pipeline_info.pInputAssemblyState = &input_assembly_state; + pipeline_info.pViewportState = &viewport_state; + pipeline_info.pRasterizationState = &rasterization_state; + pipeline_info.pMultisampleState = &multisample_state; + pipeline_info.pColorBlendState = &color_blend_state; + pipeline_info.pDynamicState = &dynamic_state; + pipeline_info.layout = dev->pipeline_layout; + pipeline_info.renderPass = dev->render_pass; + pipeline_info.basePipelineIndex = -1; + pipeline_info.basePipelineHandle = NULL; + + result = vkCreateGraphicsPipelines(dev->logical_device, NULL, 1, + &pipeline_info, NULL, &dev->pipeline); + NK_ASSERT(result == VK_SUCCESS); + + vkDestroyShaderModule(dev->logical_device, shader_stages[0].module, NULL); + vkDestroyShaderModule(dev->logical_device, shader_stages[1].module, NULL); +} + +NK_INTERN void nk_glfw3_create_render_resources(struct nk_glfw_device *dev, + uint32_t framebuffer_width, + uint32_t framebuffer_height) { + nk_glfw3_create_render_pass(dev); + nk_glfw3_create_framebuffers(dev, framebuffer_width, framebuffer_height); + nk_glfw3_create_descriptor_pool(dev); + nk_glfw3_create_uniform_descriptor_set_layout(dev); + nk_glfw3_create_and_update_uniform_descriptor_set(dev); + nk_glfw3_create_texture_descriptor_set_layout(dev); + nk_glfw3_create_texture_descriptor_sets(dev); + nk_glfw3_create_pipeline_layout(dev); + nk_glfw3_create_pipeline(dev); +} + +NK_API void nk_glfw3_device_create( + VkDevice logical_device, VkPhysicalDevice physical_device, + uint32_t graphics_queue_family_index, VkImageView *image_views, + uint32_t image_views_len, VkFormat color_format, + VkDeviceSize max_vertex_buffer, VkDeviceSize max_element_buffer, + uint32_t framebuffer_width, uint32_t framebuffer_height) { + struct nk_glfw_device *dev = &glfw.vulkan; + dev->max_vertex_buffer = max_vertex_buffer; + dev->max_element_buffer = max_element_buffer; + nk_buffer_init_default(&dev->cmds); + dev->logical_device = logical_device; + dev->physical_device = physical_device; + dev->image_views = image_views; + dev->image_views_len = image_views_len; + dev->color_format = color_format; + dev->framebuffers = NULL; + dev->framebuffers_len = 0; + + nk_glfw3_create_sampler(dev); + nk_glfw3_create_command_pool(dev, graphics_queue_family_index); + nk_glfw3_create_command_buffers(dev); + nk_glfw3_create_semaphore(dev); + + nk_glfw3_create_buffer_and_memory(dev, &dev->vertex_buffer, + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, + &dev->vertex_memory, max_vertex_buffer); + nk_glfw3_create_buffer_and_memory(dev, &dev->index_buffer, + VK_BUFFER_USAGE_INDEX_BUFFER_BIT, + &dev->index_memory, max_element_buffer); + nk_glfw3_create_buffer_and_memory( + dev, &dev->uniform_buffer, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, + &dev->uniform_memory, sizeof(struct Mat4f)); + + vkMapMemory(dev->logical_device, dev->vertex_memory, 0, max_vertex_buffer, + 0, &dev->mapped_vertex); + vkMapMemory(dev->logical_device, dev->index_memory, 0, max_element_buffer, + 0, &dev->mapped_index); + vkMapMemory(dev->logical_device, dev->uniform_memory, 0, + sizeof(struct Mat4f), 0, &dev->mapped_uniform); + + nk_glfw3_create_render_resources(dev, framebuffer_width, + framebuffer_height); +} + +NK_INTERN void nk_glfw3_device_upload_atlas(VkQueue graphics_queue, + const void *image, int width, + int height) { + struct nk_glfw_device *dev = &glfw.vulkan; + + VkImageCreateInfo image_info; + VkResult result; + VkMemoryRequirements mem_reqs; + VkMemoryAllocateInfo alloc_info; + VkBufferCreateInfo buffer_info; + uint8_t *data = 0; + VkCommandBufferBeginInfo begin_info; + VkCommandBuffer command_buffer; + VkImageMemoryBarrier image_memory_barrier; + VkBufferImageCopy buffer_copy_region; + VkImageMemoryBarrier image_shader_memory_barrier; + VkFence fence; + VkFenceCreateInfo fence_create; + VkSubmitInfo submit_info; + VkImageViewCreateInfo image_view_info; + struct { + VkDeviceMemory memory; + VkBuffer buffer; + } staging_buffer; + + memset(&image_info, 0, sizeof(VkImageCreateInfo)); + image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + image_info.imageType = VK_IMAGE_TYPE_2D; + image_info.format = VK_FORMAT_R8G8B8A8_UNORM; + image_info.extent.width = (uint32_t)width; + image_info.extent.height = (uint32_t)height; + image_info.extent.depth = 1; + image_info.mipLevels = 1; + image_info.arrayLayers = 1; + image_info.samples = VK_SAMPLE_COUNT_1_BIT; + image_info.tiling = VK_IMAGE_TILING_OPTIMAL; + image_info.usage = + VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; + image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + + result = + vkCreateImage(dev->logical_device, &image_info, NULL, &dev->font_image); + NK_ASSERT(result == VK_SUCCESS); + + vkGetImageMemoryRequirements(dev->logical_device, dev->font_image, + &mem_reqs); + + memset(&alloc_info, 0, sizeof(VkMemoryAllocateInfo)); + alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + alloc_info.allocationSize = mem_reqs.size; + alloc_info.memoryTypeIndex = nk_glfw3_find_memory_index( + dev->physical_device, mem_reqs.memoryTypeBits, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + + result = vkAllocateMemory(dev->logical_device, &alloc_info, NULL, + &dev->font_memory); + NK_ASSERT(result == VK_SUCCESS); + result = vkBindImageMemory(dev->logical_device, dev->font_image, + dev->font_memory, 0); + NK_ASSERT(result == VK_SUCCESS); + + memset(&buffer_info, 0, sizeof(VkBufferCreateInfo)); + buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + buffer_info.size = alloc_info.allocationSize; + buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + + result = vkCreateBuffer(dev->logical_device, &buffer_info, NULL, + &staging_buffer.buffer); + NK_ASSERT(result == VK_SUCCESS); + vkGetBufferMemoryRequirements(dev->logical_device, staging_buffer.buffer, + &mem_reqs); + + alloc_info.allocationSize = mem_reqs.size; + alloc_info.memoryTypeIndex = nk_glfw3_find_memory_index( + dev->physical_device, mem_reqs.memoryTypeBits, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + + result = vkAllocateMemory(dev->logical_device, &alloc_info, NULL, + &staging_buffer.memory); + NK_ASSERT(result == VK_SUCCESS); + result = vkBindBufferMemory(dev->logical_device, staging_buffer.buffer, + staging_buffer.memory, 0); + NK_ASSERT(result == VK_SUCCESS); + + result = vkMapMemory(dev->logical_device, staging_buffer.memory, 0, + alloc_info.allocationSize, 0, (void **)&data); + NK_ASSERT(result == VK_SUCCESS); + memcpy(data, image, width * height * 4); + vkUnmapMemory(dev->logical_device, staging_buffer.memory); + + memset(&begin_info, 0, sizeof(VkCommandBufferBeginInfo)); + begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + + NK_ASSERT(dev->command_buffers_len > 0); + /* + use the same command buffer as for render as we are regenerating the + buffer during render anyway + */ + command_buffer = dev->command_buffers[0]; + result = vkBeginCommandBuffer(command_buffer, &begin_info); + NK_ASSERT(result == VK_SUCCESS); + + memset(&image_memory_barrier, 0, sizeof(VkImageMemoryBarrier)); + image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + image_memory_barrier.image = dev->font_image; + image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + image_memory_barrier.subresourceRange.aspectMask = + VK_IMAGE_ASPECT_COLOR_BIT; + image_memory_barrier.subresourceRange.levelCount = 1; + image_memory_barrier.subresourceRange.layerCount = 1; + image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + + vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, + &image_memory_barrier); + + memset(&buffer_copy_region, 0, sizeof(VkBufferImageCopy)); + buffer_copy_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + buffer_copy_region.imageSubresource.layerCount = 1; + buffer_copy_region.imageExtent.width = (uint32_t)width; + buffer_copy_region.imageExtent.height = (uint32_t)height; + buffer_copy_region.imageExtent.depth = 1; + + vkCmdCopyBufferToImage( + command_buffer, staging_buffer.buffer, dev->font_image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &buffer_copy_region); + + memset(&image_shader_memory_barrier, 0, sizeof(VkImageMemoryBarrier)); + image_shader_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + image_shader_memory_barrier.image = dev->font_image; + image_shader_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + image_shader_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + image_shader_memory_barrier.oldLayout = + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + image_shader_memory_barrier.newLayout = + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + image_shader_memory_barrier.subresourceRange.aspectMask = + VK_IMAGE_ASPECT_COLOR_BIT; + image_shader_memory_barrier.subresourceRange.levelCount = 1; + image_shader_memory_barrier.subresourceRange.layerCount = 1; + image_shader_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + image_shader_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT, + + vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, NULL, 0, + NULL, 1, &image_shader_memory_barrier); + + result = vkEndCommandBuffer(command_buffer); + NK_ASSERT(result == VK_SUCCESS); + + memset(&fence_create, 0, sizeof(VkFenceCreateInfo)); + fence_create.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; + + result = vkCreateFence(dev->logical_device, &fence_create, NULL, &fence); + NK_ASSERT(result == VK_SUCCESS); + + memset(&submit_info, 0, sizeof(VkSubmitInfo)); + submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submit_info.commandBufferCount = 1; + submit_info.pCommandBuffers = &command_buffer; + + result = vkQueueSubmit(graphics_queue, 1, &submit_info, fence); + NK_ASSERT(result == VK_SUCCESS); + result = + vkWaitForFences(dev->logical_device, 1, &fence, VK_TRUE, UINT64_MAX); + NK_ASSERT(result == VK_SUCCESS); + + vkDestroyFence(dev->logical_device, fence, NULL); + + vkFreeMemory(dev->logical_device, staging_buffer.memory, NULL); + vkDestroyBuffer(dev->logical_device, staging_buffer.buffer, NULL); + + memset(&image_view_info, 0, sizeof(VkImageViewCreateInfo)); + image_view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + image_view_info.image = dev->font_image; + image_view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + image_view_info.format = image_info.format; + image_view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + image_view_info.subresourceRange.layerCount = 1; + image_view_info.subresourceRange.levelCount = 1; + + result = vkCreateImageView(dev->logical_device, &image_view_info, NULL, + &dev->font_image_view); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void nk_glfw3_destroy_render_resources(struct nk_glfw_device *dev) { + uint32_t i; + + vkDestroyPipeline(dev->logical_device, dev->pipeline, NULL); + vkDestroyPipelineLayout(dev->logical_device, dev->pipeline_layout, NULL); + vkDestroyDescriptorSetLayout(dev->logical_device, + dev->texture_descriptor_set_layout, NULL); + vkDestroyDescriptorSetLayout(dev->logical_device, + dev->uniform_descriptor_set_layout, NULL); + vkDestroyDescriptorPool(dev->logical_device, dev->descriptor_pool, NULL); + for (i = 0; i < dev->framebuffers_len; i++) { + vkDestroyFramebuffer(dev->logical_device, dev->framebuffers[i], NULL); + } + free(dev->framebuffers); + dev->framebuffers_len = 0; + free(dev->texture_descriptor_sets); + dev->texture_descriptor_sets_len = 0; + vkDestroyRenderPass(dev->logical_device, dev->render_pass, NULL); +} + +NK_API void nk_glfw3_resize(uint32_t framebuffer_width, + uint32_t framebuffer_height) { + struct nk_glfw_device *dev = &glfw.vulkan; + glfwGetWindowSize(glfw.win, &glfw.width, &glfw.height); + glfwGetFramebufferSize(glfw.win, &glfw.display_width, &glfw.display_height); + glfw.fb_scale.x = (float)glfw.display_width / (float)glfw.width; + glfw.fb_scale.y = (float)glfw.display_height / (float)glfw.height; + + nk_glfw3_destroy_render_resources(dev); + nk_glfw3_create_render_resources(dev, framebuffer_width, + framebuffer_height); +} + +NK_API void nk_glfw3_device_destroy(void) { + struct nk_glfw_device *dev = &glfw.vulkan; + + vkDeviceWaitIdle(dev->logical_device); + + nk_glfw3_destroy_render_resources(dev); + + vkFreeCommandBuffers(dev->logical_device, dev->command_pool, + dev->command_buffers_len, dev->command_buffers); + vkDestroyCommandPool(dev->logical_device, dev->command_pool, NULL); + vkDestroySemaphore(dev->logical_device, dev->render_completed, NULL); + + vkUnmapMemory(dev->logical_device, dev->vertex_memory); + vkUnmapMemory(dev->logical_device, dev->index_memory); + vkUnmapMemory(dev->logical_device, dev->uniform_memory); + + vkFreeMemory(dev->logical_device, dev->vertex_memory, NULL); + vkFreeMemory(dev->logical_device, dev->index_memory, NULL); + vkFreeMemory(dev->logical_device, dev->uniform_memory, NULL); + + vkDestroyBuffer(dev->logical_device, dev->vertex_buffer, NULL); + vkDestroyBuffer(dev->logical_device, dev->index_buffer, NULL); + vkDestroyBuffer(dev->logical_device, dev->uniform_buffer, NULL); + + vkDestroySampler(dev->logical_device, dev->sampler, NULL); + + vkFreeMemory(dev->logical_device, dev->font_memory, NULL); + vkDestroyImage(dev->logical_device, dev->font_image, NULL); + vkDestroyImageView(dev->logical_device, dev->font_image_view, NULL); + + free(dev->command_buffers); + nk_buffer_free(&dev->cmds); +} + +NK_API +void nk_glfw3_shutdown(void) { + nk_font_atlas_clear(&glfw.atlas); + nk_free(&glfw.ctx); + nk_glfw3_device_destroy(); + memset(&glfw, 0, sizeof(glfw)); +} + +NK_API void nk_glfw3_font_stash_begin(struct nk_font_atlas **atlas) { + nk_font_atlas_init_default(&glfw.atlas); + nk_font_atlas_begin(&glfw.atlas); + *atlas = &glfw.atlas; +} + +NK_API void nk_glfw3_font_stash_end(VkQueue graphics_queue) { + struct nk_glfw_device *dev = &glfw.vulkan; + + const void *image; + int w, h; + image = nk_font_atlas_bake(&glfw.atlas, &w, &h, NK_FONT_ATLAS_RGBA32); + nk_glfw3_device_upload_atlas(graphics_queue, image, w, h); + nk_font_atlas_end(&glfw.atlas, nk_handle_ptr(dev->font_image_view), + &dev->tex_null); + if (glfw.atlas.default_font) { + nk_style_set_font(&glfw.ctx, &glfw.atlas.default_font->handle); + } +} + +NK_API void nk_glfw3_new_frame(void) { + int i; + double x, y; + struct nk_context *ctx = &glfw.ctx; + struct GLFWwindow *win = glfw.win; + + nk_input_begin(ctx); + for (i = 0; i < glfw.text_len; ++i) + nk_input_unicode(ctx, glfw.text[i]); + +#ifdef NK_GLFW_GL4_MOUSE_GRABBING + /* optional grabbing behavior */ + if (ctx->input.mouse.grab) + glfwSetInputMode(glfw.win, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); + else if (ctx->input.mouse.ungrab) + glfwSetInputMode(glfw.win, GLFW_CURSOR, GLFW_CURSOR_NORMAL); +#endif + + nk_input_key(ctx, NK_KEY_DEL, + glfwGetKey(win, GLFW_KEY_DELETE) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_ENTER, + glfwGetKey(win, GLFW_KEY_ENTER) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TAB, glfwGetKey(win, GLFW_KEY_TAB) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_BACKSPACE, + glfwGetKey(win, GLFW_KEY_BACKSPACE) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_UP, glfwGetKey(win, GLFW_KEY_UP) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_DOWN, + glfwGetKey(win, GLFW_KEY_DOWN) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_START, + glfwGetKey(win, GLFW_KEY_HOME) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_END, + glfwGetKey(win, GLFW_KEY_END) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_SCROLL_START, + glfwGetKey(win, GLFW_KEY_HOME) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_SCROLL_END, + glfwGetKey(win, GLFW_KEY_END) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_SCROLL_DOWN, + glfwGetKey(win, GLFW_KEY_PAGE_DOWN) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_SCROLL_UP, + glfwGetKey(win, GLFW_KEY_PAGE_UP) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_SHIFT, + glfwGetKey(win, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || + glfwGetKey(win, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS); + + if (glfwGetKey(win, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS || + glfwGetKey(win, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS) { + nk_input_key(ctx, NK_KEY_COPY, + glfwGetKey(win, GLFW_KEY_C) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_PASTE, + glfwGetKey(win, GLFW_KEY_V) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_CUT, + glfwGetKey(win, GLFW_KEY_X) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_UNDO, + glfwGetKey(win, GLFW_KEY_Z) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_REDO, + glfwGetKey(win, GLFW_KEY_R) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_WORD_LEFT, + glfwGetKey(win, GLFW_KEY_LEFT) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_WORD_RIGHT, + glfwGetKey(win, GLFW_KEY_RIGHT) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_LINE_START, + glfwGetKey(win, GLFW_KEY_B) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_LINE_END, + glfwGetKey(win, GLFW_KEY_E) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_SELECT_ALL, + glfwGetKey(win, GLFW_KEY_A) == GLFW_PRESS); + } else { + nk_input_key(ctx, NK_KEY_LEFT, + glfwGetKey(win, GLFW_KEY_LEFT) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_RIGHT, + glfwGetKey(win, GLFW_KEY_RIGHT) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_COPY, 0); + nk_input_key(ctx, NK_KEY_PASTE, 0); + nk_input_key(ctx, NK_KEY_CUT, 0); + nk_input_key(ctx, NK_KEY_SHIFT, 0); + } + + glfwGetCursorPos(win, &x, &y); + nk_input_motion(ctx, (int)x, (int)y); +#ifdef NK_GLFW_GL4_MOUSE_GRABBING + if (ctx->input.mouse.grabbed) { + glfwSetCursorPos(glfw.win, ctx->input.mouse.prev.x, + ctx->input.mouse.prev.y); + ctx->input.mouse.pos.x = ctx->input.mouse.prev.x; + ctx->input.mouse.pos.y = ctx->input.mouse.prev.y; + } +#endif + nk_input_button(ctx, NK_BUTTON_LEFT, (int)x, (int)y, + glfwGetMouseButton(win, GLFW_MOUSE_BUTTON_LEFT) == + GLFW_PRESS); + nk_input_button(ctx, NK_BUTTON_MIDDLE, (int)x, (int)y, + glfwGetMouseButton(win, GLFW_MOUSE_BUTTON_MIDDLE) == + GLFW_PRESS); + nk_input_button(ctx, NK_BUTTON_RIGHT, (int)x, (int)y, + glfwGetMouseButton(win, GLFW_MOUSE_BUTTON_RIGHT) == + GLFW_PRESS); + nk_input_button(ctx, NK_BUTTON_DOUBLE, (int)glfw.double_click_pos.x, + (int)glfw.double_click_pos.y, glfw.is_double_click_down); + nk_input_scroll(ctx, glfw.scroll); + nk_input_end(&glfw.ctx); + glfw.text_len = 0; + glfw.scroll = nk_vec2(0, 0); +} + +NK_INTERN void update_texture_descriptor_set( + struct nk_glfw_device *dev, + struct nk_vulkan_texture_descriptor_set *texture_descriptor_set, + VkImageView image_view) { + VkDescriptorImageInfo descriptor_image_info; + VkWriteDescriptorSet descriptor_write; + + texture_descriptor_set->image_view = image_view; + + memset(&descriptor_image_info, 0, sizeof(VkDescriptorImageInfo)); + descriptor_image_info.sampler = dev->sampler; + descriptor_image_info.imageView = texture_descriptor_set->image_view; + descriptor_image_info.imageLayout = + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + + memset(&descriptor_write, 0, sizeof(VkWriteDescriptorSet)); + descriptor_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptor_write.dstSet = texture_descriptor_set->descriptor_set; + descriptor_write.dstBinding = 0; + descriptor_write.dstArrayElement = 0; + descriptor_write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + descriptor_write.descriptorCount = 1; + descriptor_write.pImageInfo = &descriptor_image_info; + + vkUpdateDescriptorSets(dev->logical_device, 1, &descriptor_write, 0, NULL); +} + +NK_API +VkSemaphore nk_glfw3_render(VkQueue graphics_queue, uint32_t buffer_index, + VkSemaphore wait_semaphore, + enum nk_anti_aliasing AA) { + struct nk_glfw_device *dev = &glfw.vulkan; + struct nk_buffer vbuf, ebuf; + + struct Mat4f projection = { + {2.0f, 0.0f, 0.0f, 0.0f, 0.0f, -2.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, + 0.0f, -1.0f, 1.0f, 0.0f, 1.0f}, + }; + + VkCommandBufferBeginInfo begin_info; + VkClearValue clear_value = {{{0.0f, 0.0f, 0.0f, 0.0f}}}; + VkRenderPassBeginInfo render_pass_begin_nfo; + VkCommandBuffer command_buffer; + VkResult result; + VkViewport viewport; + + VkDeviceSize doffset = 0; + VkImageView current_texture = NULL; + uint32_t index_offset = 0; + VkRect2D scissor; + uint32_t wait_semaphore_count; + VkSemaphore *wait_semaphores; + VkPipelineStageFlags wait_stage = + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + VkSubmitInfo submit_info; + + projection.m[0] /= glfw.width; + projection.m[5] /= glfw.height; + + memcpy(dev->mapped_uniform, &projection, sizeof(projection)); + + memset(&begin_info, 0, sizeof(VkCommandBufferBeginInfo)); + begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + + memset(&render_pass_begin_nfo, 0, sizeof(VkRenderPassBeginInfo)); + render_pass_begin_nfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + render_pass_begin_nfo.renderPass = dev->render_pass; + render_pass_begin_nfo.renderArea.extent.width = (uint32_t)glfw.width; + render_pass_begin_nfo.renderArea.extent.height = (uint32_t)glfw.height; + render_pass_begin_nfo.clearValueCount = 1; + render_pass_begin_nfo.pClearValues = &clear_value; + render_pass_begin_nfo.framebuffer = dev->framebuffers[buffer_index]; + + command_buffer = dev->command_buffers[buffer_index]; + + result = vkBeginCommandBuffer(command_buffer, &begin_info); + NK_ASSERT(result == VK_SUCCESS); + vkCmdBeginRenderPass(command_buffer, &render_pass_begin_nfo, + VK_SUBPASS_CONTENTS_INLINE); + + memset(&viewport, 0, sizeof(VkViewport)); + viewport.width = (float)glfw.width; + viewport.height = (float)glfw.height; + viewport.maxDepth = 1.0f; + vkCmdSetViewport(command_buffer, 0, 1, &viewport); + + vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, + dev->pipeline); + vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, + dev->pipeline_layout, 0, 1, + &dev->uniform_descriptor_set, 0, NULL); + { + /* convert from command queue into draw list and draw to screen */ + const struct nk_draw_command *cmd; + /* load draw vertices & elements directly into vertex + element buffer + */ + { + /* fill convert configuration */ + struct nk_convert_config config; + static const struct nk_draw_vertex_layout_element vertex_layout[] = + {{NK_VERTEX_POSITION, NK_FORMAT_FLOAT, + NK_OFFSETOF(struct nk_glfw_vertex, position)}, + {NK_VERTEX_TEXCOORD, NK_FORMAT_FLOAT, + NK_OFFSETOF(struct nk_glfw_vertex, uv)}, + {NK_VERTEX_COLOR, NK_FORMAT_R8G8B8A8, + NK_OFFSETOF(struct nk_glfw_vertex, col)}, + {NK_VERTEX_LAYOUT_END}}; + NK_MEMSET(&config, 0, sizeof(config)); + config.vertex_layout = vertex_layout; + config.vertex_size = sizeof(struct nk_glfw_vertex); + config.vertex_alignment = NK_ALIGNOF(struct nk_glfw_vertex); + config.tex_null = dev->tex_null; + config.circle_segment_count = 22; + config.curve_segment_count = 22; + config.arc_segment_count = 22; + config.global_alpha = 1.0f; + config.shape_AA = AA; + config.line_AA = AA; + + /* setup buffers to load vertices and elements */ + nk_buffer_init_fixed(&vbuf, dev->mapped_vertex, + (size_t)dev->max_vertex_buffer); + nk_buffer_init_fixed(&ebuf, dev->mapped_index, + (size_t)dev->max_element_buffer); + nk_convert(&glfw.ctx, &dev->cmds, &vbuf, &ebuf, &config); + } + + /* iterate over and execute each draw command */ + + vkCmdBindVertexBuffers(command_buffer, 0, 1, &dev->vertex_buffer, + &doffset); + vkCmdBindIndexBuffer(command_buffer, dev->index_buffer, 0, + VK_INDEX_TYPE_UINT16); + + nk_draw_foreach(cmd, &glfw.ctx, &dev->cmds) { + if (!cmd->texture.ptr) { + continue; + } + if (cmd->texture.ptr && cmd->texture.ptr != current_texture) { + int found = 0; + uint32_t i; + for (i = 0; i < dev->texture_descriptor_sets_len; i++) { + if (dev->texture_descriptor_sets[i].image_view == + cmd->texture.ptr) { + found = 1; + break; + } + } + + if (!found) { + update_texture_descriptor_set( + dev, &dev->texture_descriptor_sets[i], + (VkImageView)cmd->texture.ptr); + dev->texture_descriptor_sets_len++; + } + vkCmdBindDescriptorSets( + command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, + dev->pipeline_layout, 1, 1, + &dev->texture_descriptor_sets[i].descriptor_set, 0, NULL); + } + + if (!cmd->elem_count) + continue; + + scissor.offset.x = (int32_t)(NK_MAX(cmd->clip_rect.x, 0.f)); + scissor.offset.y = (int32_t)(NK_MAX(cmd->clip_rect.y, 0.f)); + scissor.extent.width = (uint32_t)(cmd->clip_rect.w); + scissor.extent.height = (uint32_t)(cmd->clip_rect.h); + vkCmdSetScissor(command_buffer, 0, 1, &scissor); + vkCmdDrawIndexed(command_buffer, cmd->elem_count, 1, index_offset, + 0, 0); + index_offset += cmd->elem_count; + } + nk_clear(&glfw.ctx); + } + + vkCmdEndRenderPass(command_buffer); + result = vkEndCommandBuffer(command_buffer); + NK_ASSERT(result == VK_SUCCESS); + + if (wait_semaphore) { + wait_semaphore_count = 1; + wait_semaphores = &wait_semaphore; + } else { + wait_semaphore_count = 0; + wait_semaphores = NULL; + } + + memset(&submit_info, 0, sizeof(VkSubmitInfo)); + submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submit_info.commandBufferCount = 1; + submit_info.pCommandBuffers = &command_buffer; + submit_info.pWaitDstStageMask = &wait_stage; + submit_info.waitSemaphoreCount = wait_semaphore_count; + submit_info.pWaitSemaphores = wait_semaphores; + submit_info.signalSemaphoreCount = 1; + submit_info.pSignalSemaphores = &dev->render_completed; + + result = vkQueueSubmit(graphics_queue, 1, &submit_info, NULL); + NK_ASSERT(result == VK_SUCCESS); + + return dev->render_completed; +} + +NK_API void nk_glfw3_char_callback(GLFWwindow *win, unsigned int codepoint) { + (void)win; + if (glfw.text_len < NK_GLFW_TEXT_MAX) + glfw.text[glfw.text_len++] = codepoint; +} + +NK_API void nk_gflw3_scroll_callback(GLFWwindow *win, double xoff, + double yoff) { + (void)win; + (void)xoff; + glfw.scroll.x += (float)xoff; + glfw.scroll.y += (float)yoff; +} + +NK_API void nk_glfw3_mouse_button_callback(GLFWwindow *window, int button, + int action, int mods) { + double x, y; + NK_UNUSED(mods); + if (button != GLFW_MOUSE_BUTTON_LEFT) + return; + glfwGetCursorPos(window, &x, &y); + if (action == GLFW_PRESS) { + double dt = glfwGetTime() - glfw.last_button_click; + if (dt > NK_GLFW_DOUBLE_CLICK_LO && dt < NK_GLFW_DOUBLE_CLICK_HI) { + glfw.is_double_click_down = nk_true; + glfw.double_click_pos = nk_vec2((float)x, (float)y); + } + glfw.last_button_click = glfwGetTime(); + } else + glfw.is_double_click_down = nk_false; +} + +NK_INTERN void nk_glfw3_clipboard_paste(nk_handle usr, + struct nk_text_edit *edit) { + const char *text = glfwGetClipboardString(glfw.win); + if (text) + nk_textedit_paste(edit, text, nk_strlen(text)); + (void)usr; +} + +NK_INTERN void nk_glfw3_clipboard_copy(nk_handle usr, const char *text, + int len) { + char *str = 0; + (void)usr; + if (!len) + return; + str = (char *)malloc((size_t)len + 1); + if (!str) + return; + memcpy(str, text, (size_t)len); + str[len] = '\0'; + glfwSetClipboardString(glfw.win, str); + free(str); +} + +NK_API struct nk_context * +nk_glfw3_init(GLFWwindow *win, VkDevice logical_device, + VkPhysicalDevice physical_device, + uint32_t graphics_queue_family_index, VkImageView *image_views, + uint32_t image_views_len, VkFormat color_format, + enum nk_glfw_init_state init_state, + VkDeviceSize max_vertex_buffer, VkDeviceSize max_element_buffer) { + memset(&glfw, 0, sizeof(struct nk_glfw)); + glfw.win = win; + if (init_state == NK_GLFW3_INSTALL_CALLBACKS) { + glfwSetScrollCallback(win, nk_gflw3_scroll_callback); + glfwSetCharCallback(win, nk_glfw3_char_callback); + glfwSetMouseButtonCallback(win, nk_glfw3_mouse_button_callback); + } + nk_init_default(&glfw.ctx, 0); + glfw.ctx.clip.copy = nk_glfw3_clipboard_copy; + glfw.ctx.clip.paste = nk_glfw3_clipboard_paste; + glfw.ctx.clip.userdata = nk_handle_ptr(0); + glfw.last_button_click = 0; + + glfwGetWindowSize(win, &glfw.width, &glfw.height); + glfwGetFramebufferSize(win, &glfw.display_width, &glfw.display_height); + + nk_glfw3_device_create(logical_device, physical_device, + graphics_queue_family_index, image_views, + image_views_len, color_format, max_vertex_buffer, + max_element_buffer, (uint32_t)glfw.display_width, + (uint32_t)glfw.display_height); + + glfw.is_double_click_down = nk_false; + glfw.double_click_pos = nk_vec2(0, 0); + + return &glfw.ctx; +} + +#endif diff --git a/demo/glfw_vulkan/shaders/demo.frag b/demo/glfw_vulkan/shaders/demo.frag new file mode 100644 index 0000000..2034597 --- /dev/null +++ b/demo/glfw_vulkan/shaders/demo.frag @@ -0,0 +1,12 @@ +#version 450 +#extension GL_ARB_separate_shader_objects : enable + +layout(binding = 0) uniform sampler2D overlay; + +layout(location = 0) in vec2 inUV; + +layout(location = 0) out vec4 outColor; + +void main() { + outColor = texture(overlay, inUV); +} diff --git a/demo/glfw_vulkan/shaders/demo.frag.spv b/demo/glfw_vulkan/shaders/demo.frag.spv new file mode 100644 index 0000000000000000000000000000000000000000..e33fcc08ae25cdadd0b9e5e97e150e7f966965bb GIT binary patch literal 664 zcmY+APfNo<5XHwPX=|(fV?_}`TD_MZR0L5_kz4`=MLjODS#TvLAxR7UdVVS|g72*@ z#)Zk`z5VU%%sRD`hRBArWm|UTclD(PN8r_M_JhY@T$IuH^lU<+BaQ{hbfqCKGUFpO z2{$$oeMAo&eO!P)2USHramWSX2kPeGRuwu6^RU#acnc$)tMv6<&&q;Ki;O>=`oX=L zWtl3`5fkjRJ*s4E0s%V~H^8-xI*+=#j#QyK$zYcGR*hf9S5jA@q;@d># zE7QMRY4$+x0Nu2Z$>TZyt+hS`*~Shz*4tW9^jMFYGjQ?#E;8$}Px3uv)}l|InlsTm u#|x2TuUzcu3yz0;1($bp5Ufwl8aoJ{e*wjr1_(0ruTg=s(fh^?7lfb6qj-@s(1i|gt(N83{s>9D*9@fcm<1$6U7cHJe5Dd zUqV7i{3TwHIG^opBQ~1MoHJ)csbIVj~!8F7eaqZHFo!!n>UL;$0 z?%qZ*XPTuD&Agc^;|cwLid_acE;}K+AZzN^kpC(1gfd|#+J5si%IzQ?#)XaY4{>6L zQUBdX+beQ3(`dq-ov`yF>J0`_UVKSyl)B7Di5p7gK3jBCV>*}h(or%lXh|{N6PUjG zqvGwJd`owu$Mt|voOP*PjyvvGR z_f;LTr^<1E<({Q(@Z9A^ob~Ksj!BXmrRia=rI|51R#^AFR>2a}_l)eO?4@qv`+{S6 zu6jdW_lTnxbe!vT#Bj_jREB!!7WI!`7l(#;Sy5X)kgaHkKAsYj3xxR^(852cF>{Ao z5}uY1Wb}ldbBW>6gSj8vX04z551$m~JkDQ{ryqK!{u%i|#$rGCtc-fA!sq1C!>uXe zuD%92jJ{Uo>6tuzfvfNNs4xE}oa1LA*%Oa12^e$m!{aL@uJ)t9TH=GpoX1;o9=+Vt zn{q$y#Df1LrX~MSEVG)GF{fW*!Sgl8tbW(rLd`R;zV>nEDH*)4v#6Lle$Q#eaN~QH zgyFlY%eyYis005<-SNI~)FgjV2KT+zuh(24?`v!*W nuklear_glfw_vulkan.h + +nuklearshaders/nuklear.vert.spv: nuklearshaders/nuklear.vert + glslc --target-env=vulkan nuklearshaders/nuklear.vert -o nuklearshaders/nuklear.vert.spv + +nuklearshaders/nuklear.frag.spv: nuklearshaders/nuklear.frag + glslc --target-env=vulkan nuklearshaders/nuklear.frag -o nuklearshaders/nuklear.frag.spv + +clean: + rm nuklearshaders/nuklear.vert.spv nuklearshaders/nuklear.frag.spv nuklear_glfw_vulkan.h diff --git a/demo/glfw_vulkan/src/README.md b/demo/glfw_vulkan/src/README.md new file mode 100644 index 0000000..c911fbc --- /dev/null +++ b/demo/glfw_vulkan/src/README.md @@ -0,0 +1,5 @@ +Contrary to OpenGL Vulkan needs precompiled shaders in the SPIR-V format which makes it a bit more difficult to inline the shadercode. + +After executing `make` the result should be a self contained `nuklear_glfw_vulkan.h`. Copy the result file to the parent directory and the "release" should be done. + +You will need to have `xxd`, `glslc` and `awk` installed for this. diff --git a/demo/glfw_vulkan/src/nuklear_glfw_vulkan.in.h b/demo/glfw_vulkan/src/nuklear_glfw_vulkan.in.h new file mode 100644 index 0000000..78a1f6c --- /dev/null +++ b/demo/glfw_vulkan/src/nuklear_glfw_vulkan.in.h @@ -0,0 +1,1424 @@ +/* + * Nuklear - 1.32.0 - public domain + * no warrenty implied; use at your own risk. + * authored from 2015-2016 by Micha Mettke + */ +/* + * ============================================================== + * + * API + * + * =============================================================== + */ +#ifndef NK_GLFW_VULKAN_H_ +#define NK_GLFW_VULKAN_H_ + +// NUKLEAR_SHADERS_START +// will be replaced with the real shader code +// so we can have some ide support while editing the .in file +#include "nuklear.h" + +unsigned char nuklearshaders_nuklear_vert_spv[] = {}; +unsigned int nuklearshaders_nuklear_vert_spv_len = 0; +unsigned char nuklearshaders_nuklear_frag_spv[] = {}; +unsigned int nuklearshaders_nuklear_frag_spv_len = 0; +// NUKLEAR_SHADERS_END + +#include +#include +#define GLFW_INCLUDE_VULKAN +#include + +enum nk_glfw_init_state { NK_GLFW3_DEFAULT = 0, NK_GLFW3_INSTALL_CALLBACKS }; + +NK_API struct nk_context * +nk_glfw3_init(GLFWwindow *win, VkDevice logical_device, + VkPhysicalDevice physical_device, + uint32_t graphics_queue_family_index, VkImageView *image_views, + uint32_t image_views_len, VkFormat color_format, + enum nk_glfw_init_state init_state, + VkDeviceSize max_vertex_buffer, VkDeviceSize max_element_buffer); +NK_API void nk_glfw3_shutdown(void); +NK_API void nk_glfw3_font_stash_begin(struct nk_font_atlas **atlas); +NK_API void nk_glfw3_font_stash_end(VkQueue graphics_queue); +NK_API void nk_glfw3_new_frame(); +NK_API VkSemaphore nk_glfw3_render(VkQueue graphics_queue, + uint32_t buffer_index, + VkSemaphore wait_semaphore, + enum nk_anti_aliasing AA); +NK_API void nk_glfw3_resize(uint32_t framebuffer_width, + uint32_t framebuffer_height); +NK_API void nk_glfw3_device_destroy(void); +NK_API void nk_glfw3_device_create( + VkDevice logical_device, VkPhysicalDevice physical_device, + uint32_t graphics_queue_family_index, VkImageView *image_views, + uint32_t image_views_len, VkFormat color_format, + VkDeviceSize max_vertex_buffer, VkDeviceSize max_element_buffer, + uint32_t framebuffer_width, uint32_t framebuffer_height); + +NK_API void nk_glfw3_char_callback(GLFWwindow *win, unsigned int codepoint); +NK_API void nk_gflw3_scroll_callback(GLFWwindow *win, double xoff, double yoff); +NK_API void nk_glfw3_mouse_button_callback(GLFWwindow *win, int button, + int action, int mods); + +#endif +/* + * ============================================================== + * + * IMPLEMENTATION + * + * =============================================================== + */ +#ifdef NK_GLFW_VULKAN_IMPLEMENTATION +#undef NK_GLFW_VULKAN_IMPLEMENTATION + +#ifndef NK_GLFW_TEXT_MAX +#define NK_GLFW_TEXT_MAX 256 +#endif +#ifndef NK_GLFW_DOUBLE_CLICK_LO +#define NK_GLFW_DOUBLE_CLICK_LO 0.02 +#endif +#ifndef NK_GLFW_DOUBLE_CLICK_HI +#define NK_GLFW_DOUBLE_CLICK_HI 0.2 +#endif +#ifndef NK_GLFW_MAX_TEXTURES +#define NK_GLFW_MAX_TEXTURES 256 +#endif + +#define VK_COLOR_COMPONENT_MASK_RGBA \ + VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | \ + VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT + +struct nk_glfw_vertex { + float position[2]; + float uv[2]; + nk_byte col[4]; +}; + +struct nk_vulkan_texture_descriptor_set { + VkImageView image_view; + VkDescriptorSet descriptor_set; +}; + +struct nk_glfw_device { + struct nk_buffer cmds; + struct nk_draw_null_texture tex_null; + int max_vertex_buffer; + int max_element_buffer; + VkDevice logical_device; + VkPhysicalDevice physical_device; + VkImageView *image_views; + uint32_t image_views_len; + VkFormat color_format; + VkFramebuffer *framebuffers; + uint32_t framebuffers_len; + VkCommandBuffer *command_buffers; + uint32_t command_buffers_len; + VkSampler sampler; + VkCommandPool command_pool; + VkSemaphore render_completed; + VkBuffer vertex_buffer; + VkDeviceMemory vertex_memory; + void *mapped_vertex; + VkBuffer index_buffer; + VkDeviceMemory index_memory; + void *mapped_index; + VkBuffer uniform_buffer; + VkDeviceMemory uniform_memory; + void *mapped_uniform; + VkRenderPass render_pass; + VkDescriptorPool descriptor_pool; + VkDescriptorSetLayout uniform_descriptor_set_layout; + VkDescriptorSet uniform_descriptor_set; + VkDescriptorSetLayout texture_descriptor_set_layout; + struct nk_vulkan_texture_descriptor_set *texture_descriptor_sets; + uint32_t texture_descriptor_sets_len; + VkPipelineLayout pipeline_layout; + VkPipeline pipeline; + VkImage font_image; + VkImageView font_image_view; + VkDeviceMemory font_memory; +}; + +static struct nk_glfw { + GLFWwindow *win; + int width, height; + int display_width, display_height; + struct nk_glfw_device vulkan; + struct nk_context ctx; + struct nk_font_atlas atlas; + struct nk_vec2 fb_scale; + unsigned int text[NK_GLFW_TEXT_MAX]; + int text_len; + struct nk_vec2 scroll; + double last_button_click; + int is_double_click_down; + struct nk_vec2 double_click_pos; +} glfw; + +struct Mat4f { + float m[16]; +}; + +NK_INTERN uint32_t nk_glfw3_find_memory_index( + VkPhysicalDevice physical_device, uint32_t type_filter, + VkMemoryPropertyFlags properties) { + VkPhysicalDeviceMemoryProperties mem_properties; + uint32_t i; + + vkGetPhysicalDeviceMemoryProperties(physical_device, &mem_properties); + for (i = 0; i < mem_properties.memoryTypeCount; i++) { + if ((type_filter & (1 << i)) && + (mem_properties.memoryTypes[i].propertyFlags & properties) == + properties) { + return i; + } + } + + assert(0); + return 0; +} + +NK_INTERN void nk_glfw3_create_sampler(struct nk_glfw_device *dev) { + VkResult result; + VkSamplerCreateInfo sampler_info; + memset(&sampler_info, 0, sizeof(VkSamplerCreateInfo)); + + sampler_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; + sampler_info.pNext = NULL; + sampler_info.maxAnisotropy = 1.0; + sampler_info.magFilter = VK_FILTER_LINEAR; + sampler_info.minFilter = VK_FILTER_LINEAR; + sampler_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; + sampler_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; + sampler_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; + sampler_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; + sampler_info.mipLodBias = 0.0f; + sampler_info.compareEnable = VK_FALSE; + sampler_info.compareOp = VK_COMPARE_OP_ALWAYS; + sampler_info.minLod = 0.0f; + sampler_info.maxLod = 0.0f; + sampler_info.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK; + + result = vkCreateSampler(dev->logical_device, &sampler_info, NULL, + &dev->sampler); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void +nk_glfw3_create_command_pool(struct nk_glfw_device *dev, + uint32_t graphics_queue_family_index) { + VkResult result; + VkCommandPoolCreateInfo pool_info; + memset(&pool_info, 0, sizeof(VkCommandPoolCreateInfo)); + + pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; + pool_info.queueFamilyIndex = graphics_queue_family_index; + pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + result = vkCreateCommandPool(dev->logical_device, &pool_info, NULL, + &dev->command_pool); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void nk_glfw3_create_command_buffers(struct nk_glfw_device *dev) { + VkResult result; + VkCommandBufferAllocateInfo allocate_info; + memset(&allocate_info, 0, sizeof(VkCommandBufferAllocateInfo)); + + dev->command_buffers = (VkCommandBuffer *)malloc(dev->image_views_len * + sizeof(VkCommandBuffer)); + dev->command_buffers_len = dev->image_views_len; + + allocate_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + allocate_info.commandPool = dev->command_pool; + allocate_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + allocate_info.commandBufferCount = dev->command_buffers_len; + + result = vkAllocateCommandBuffers(dev->logical_device, &allocate_info, + dev->command_buffers); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void nk_glfw3_create_semaphore(struct nk_glfw_device *dev) { + VkResult result; + VkSemaphoreCreateInfo semaphore_info; + memset(&semaphore_info, 0, sizeof(VkSemaphoreCreateInfo)); + + semaphore_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; + result = (vkCreateSemaphore(dev->logical_device, &semaphore_info, NULL, + &dev->render_completed)); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void nk_glfw3_create_buffer_and_memory(struct nk_glfw_device *dev, + VkBuffer *buffer, + VkBufferUsageFlags usage, + VkDeviceMemory *memory, + VkDeviceSize size) { + VkMemoryRequirements mem_reqs; + VkResult result; + VkBufferCreateInfo buffer_info; + VkMemoryAllocateInfo alloc_info; + + memset(&buffer_info, 0, sizeof(VkBufferCreateInfo)); + buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + buffer_info.size = size; + buffer_info.usage = usage; + buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + + result = vkCreateBuffer(dev->logical_device, &buffer_info, NULL, buffer); + NK_ASSERT(result == VK_SUCCESS); + + vkGetBufferMemoryRequirements(dev->logical_device, *buffer, &mem_reqs); + + memset(&alloc_info, 0, sizeof(VkMemoryAllocateInfo)); + alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + alloc_info.allocationSize = mem_reqs.size; + alloc_info.memoryTypeIndex = nk_glfw3_find_memory_index( + dev->physical_device, mem_reqs.memoryTypeBits, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + + result = vkAllocateMemory(dev->logical_device, &alloc_info, NULL, memory); + NK_ASSERT(result == VK_SUCCESS); + result = vkBindBufferMemory(dev->logical_device, *buffer, *memory, 0); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void nk_glfw3_create_render_pass(struct nk_glfw_device *dev) { + VkAttachmentDescription attachment; + VkAttachmentReference color_reference; + VkSubpassDependency subpass_dependency; + VkSubpassDescription subpass_description; + VkRenderPassCreateInfo render_pass_info; + VkResult result; + + memset(&attachment, 0, sizeof(VkAttachmentDescription)); + attachment.format = dev->color_format; + attachment.samples = VK_SAMPLE_COUNT_1_BIT; + attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; + attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; + attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + attachment.finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + + memset(&color_reference, 0, sizeof(VkAttachmentReference)); + color_reference.attachment = 0; + color_reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + + memset(&subpass_dependency, 0, sizeof(VkSubpassDependency)); + subpass_dependency.srcSubpass = VK_SUBPASS_EXTERNAL; + subpass_dependency.srcAccessMask = 0; + subpass_dependency.srcStageMask = + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + subpass_dependency.dstSubpass = 0; + subpass_dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | + VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + subpass_dependency.dstStageMask = + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + + memset(&subpass_description, 0, sizeof(VkSubpassDescription)); + subpass_description.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; + subpass_description.colorAttachmentCount = 1; + subpass_description.pColorAttachments = &color_reference; + + memset(&render_pass_info, 0, sizeof(VkRenderPassCreateInfo)); + render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; + render_pass_info.attachmentCount = 1; + render_pass_info.pAttachments = &attachment; + render_pass_info.subpassCount = 1; + render_pass_info.pSubpasses = &subpass_description; + render_pass_info.dependencyCount = 1; + render_pass_info.pDependencies = &subpass_dependency; + + result = vkCreateRenderPass(dev->logical_device, &render_pass_info, NULL, + &dev->render_pass); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void nk_glfw3_create_framebuffers(struct nk_glfw_device *dev, + uint32_t framebuffer_width, + uint32_t framebuffer_height) { + + VkFramebufferCreateInfo framebuffer_create_info; + uint32_t i; + VkResult result; + + dev->framebuffers = + (VkFramebuffer *)malloc(dev->image_views_len * sizeof(VkFramebuffer)); + + memset(&framebuffer_create_info, 0, sizeof(VkFramebufferCreateInfo)); + framebuffer_create_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; + framebuffer_create_info.renderPass = dev->render_pass; + framebuffer_create_info.attachmentCount = 1; + framebuffer_create_info.width = framebuffer_width; + framebuffer_create_info.height = framebuffer_height; + framebuffer_create_info.layers = 1; + for (i = 0; i < dev->image_views_len; i++) { + framebuffer_create_info.pAttachments = &dev->image_views[i]; + result = + vkCreateFramebuffer(dev->logical_device, &framebuffer_create_info, + NULL, &dev->framebuffers[i]); + NK_ASSERT(result == VK_SUCCESS); + } + dev->framebuffers_len = dev->image_views_len; +} + +NK_INTERN void nk_glfw3_create_descriptor_pool(struct nk_glfw_device *dev) { + VkDescriptorPoolSize pool_sizes[2]; + VkDescriptorPoolCreateInfo pool_info; + VkResult result; + + memset(&pool_sizes, 0, sizeof(VkDescriptorPoolSize) * 2); + pool_sizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + pool_sizes[0].descriptorCount = 1; + pool_sizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + pool_sizes[1].descriptorCount = NK_GLFW_MAX_TEXTURES; + + memset(&pool_info, 0, sizeof(VkDescriptorPoolCreateInfo)); + pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; + pool_info.poolSizeCount = 2; + pool_info.pPoolSizes = pool_sizes; + pool_info.maxSets = 1 + NK_GLFW_MAX_TEXTURES; + + result = vkCreateDescriptorPool(dev->logical_device, &pool_info, NULL, + &dev->descriptor_pool); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void +nk_glfw3_create_uniform_descriptor_set_layout(struct nk_glfw_device *dev) { + VkDescriptorSetLayoutBinding binding; + VkDescriptorSetLayoutCreateInfo descriptor_set_info; + VkResult result; + + memset(&binding, 0, sizeof(VkDescriptorSetLayoutBinding)); + binding.binding = 0; + binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + binding.descriptorCount = 1; + binding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; + + memset(&descriptor_set_info, 0, sizeof(VkDescriptorSetLayoutCreateInfo)); + descriptor_set_info.sType = + VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + descriptor_set_info.bindingCount = 1; + descriptor_set_info.pBindings = &binding; + + result = + vkCreateDescriptorSetLayout(dev->logical_device, &descriptor_set_info, + NULL, &dev->uniform_descriptor_set_layout); + + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void +nk_glfw3_create_and_update_uniform_descriptor_set(struct nk_glfw_device *dev) { + VkDescriptorSetAllocateInfo allocate_info; + VkDescriptorBufferInfo buffer_info; + VkWriteDescriptorSet descriptor_write; + VkResult result; + + memset(&allocate_info, 0, sizeof(VkDescriptorSetAllocateInfo)); + allocate_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + allocate_info.descriptorPool = dev->descriptor_pool; + allocate_info.descriptorSetCount = 1; + allocate_info.pSetLayouts = &dev->uniform_descriptor_set_layout; + + result = vkAllocateDescriptorSets(dev->logical_device, &allocate_info, + &dev->uniform_descriptor_set); + NK_ASSERT(result == VK_SUCCESS); + + memset(&buffer_info, 0, sizeof(VkDescriptorBufferInfo)); + buffer_info.buffer = dev->uniform_buffer; + buffer_info.offset = 0; + buffer_info.range = sizeof(struct Mat4f); + + memset(&descriptor_write, 0, sizeof(VkWriteDescriptorSet)); + descriptor_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptor_write.dstSet = dev->uniform_descriptor_set; + descriptor_write.dstBinding = 0; + descriptor_write.dstArrayElement = 0; + descriptor_write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + descriptor_write.descriptorCount = 1; + descriptor_write.pBufferInfo = &buffer_info; + + vkUpdateDescriptorSets(dev->logical_device, 1, &descriptor_write, 0, NULL); +} + +NK_INTERN void +nk_glfw3_create_texture_descriptor_set_layout(struct nk_glfw_device *dev) { + VkDescriptorSetLayoutBinding binding; + VkDescriptorSetLayoutCreateInfo descriptor_set_info; + VkResult result; + + memset(&binding, 0, sizeof(VkDescriptorSetLayoutBinding)); + binding.binding = 0; + binding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + binding.descriptorCount = 1; + binding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; + + memset(&descriptor_set_info, 0, sizeof(VkDescriptorSetLayoutCreateInfo)); + descriptor_set_info.sType = + VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + descriptor_set_info.bindingCount = 1; + descriptor_set_info.pBindings = &binding; + + result = + vkCreateDescriptorSetLayout(dev->logical_device, &descriptor_set_info, + NULL, &dev->texture_descriptor_set_layout); + + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void +nk_glfw3_create_texture_descriptor_sets(struct nk_glfw_device *dev) { + VkDescriptorSetLayout *descriptor_set_layouts; + VkDescriptorSet *descriptor_sets; + VkDescriptorSetAllocateInfo allocate_info; + VkResult result; + int i; + + descriptor_set_layouts = (VkDescriptorSetLayout *)malloc( + NK_GLFW_MAX_TEXTURES * sizeof(VkDescriptorSetLayout)); + descriptor_sets = (VkDescriptorSet *)malloc(NK_GLFW_MAX_TEXTURES * + sizeof(VkDescriptorSet)); + + dev->texture_descriptor_sets = + (struct nk_vulkan_texture_descriptor_set *)malloc( + NK_GLFW_MAX_TEXTURES * + sizeof(struct nk_vulkan_texture_descriptor_set)); + dev->texture_descriptor_sets_len = 0; + + for (i = 0; i < NK_GLFW_MAX_TEXTURES; i++) { + descriptor_set_layouts[i] = dev->texture_descriptor_set_layout; + descriptor_sets[i] = dev->texture_descriptor_sets[i].descriptor_set; + } + + memset(&allocate_info, 0, sizeof(VkDescriptorSetAllocateInfo)); + allocate_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + allocate_info.descriptorPool = dev->descriptor_pool; + allocate_info.descriptorSetCount = NK_GLFW_MAX_TEXTURES; + allocate_info.pSetLayouts = descriptor_set_layouts; + + result = vkAllocateDescriptorSets(dev->logical_device, &allocate_info, + descriptor_sets); + NK_ASSERT(result == VK_SUCCESS); + + for (i = 0; i < NK_GLFW_MAX_TEXTURES; i++) { + dev->texture_descriptor_sets[i].descriptor_set = descriptor_sets[i]; + } + free(descriptor_set_layouts); + free(descriptor_sets); +} + +NK_INTERN void nk_glfw3_create_pipeline_layout(struct nk_glfw_device *dev) { + VkPipelineLayoutCreateInfo pipeline_layout_info; + VkDescriptorSetLayout descriptor_set_layouts[2]; + VkResult result; + + descriptor_set_layouts[0] = dev->uniform_descriptor_set_layout; + descriptor_set_layouts[1] = dev->texture_descriptor_set_layout; + + memset(&pipeline_layout_info, 0, sizeof(VkPipelineLayoutCreateInfo)); + pipeline_layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + pipeline_layout_info.setLayoutCount = 2; + pipeline_layout_info.pSetLayouts = descriptor_set_layouts; + + result = (vkCreatePipelineLayout(dev->logical_device, &pipeline_layout_info, + NULL, &dev->pipeline_layout)); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN VkPipelineShaderStageCreateInfo +nk_glfw3_create_shader(struct nk_glfw_device *dev, unsigned char *spv_shader, + uint32_t size, VkShaderStageFlagBits stage_bit) { + VkShaderModuleCreateInfo create_info; + VkPipelineShaderStageCreateInfo shader_info; + VkShaderModule module = NULL; + VkResult result; + + memset(&create_info, 0, sizeof(VkShaderModuleCreateInfo)); + create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + create_info.codeSize = size; + create_info.pCode = (const uint32_t *)spv_shader; + result = + vkCreateShaderModule(dev->logical_device, &create_info, NULL, &module); + NK_ASSERT(result == VK_SUCCESS); + + memset(&shader_info, 0, sizeof(VkPipelineShaderStageCreateInfo)); + shader_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + shader_info.stage = stage_bit; + shader_info.module = module; + shader_info.pName = "main"; + return shader_info; +} + +NK_INTERN void nk_glfw3_create_pipeline(struct nk_glfw_device *dev) { + VkPipelineInputAssemblyStateCreateInfo input_assembly_state; + VkPipelineRasterizationStateCreateInfo rasterization_state; + VkPipelineColorBlendAttachmentState attachment_state = { + VK_TRUE, + VK_BLEND_FACTOR_SRC_ALPHA, + VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, + VK_BLEND_OP_ADD, + VK_BLEND_FACTOR_SRC_ALPHA, + VK_BLEND_FACTOR_ONE, + VK_BLEND_OP_ADD, + VK_COLOR_COMPONENT_MASK_RGBA, + }; + VkPipelineColorBlendStateCreateInfo color_blend_state; + VkPipelineViewportStateCreateInfo viewport_state; + VkPipelineMultisampleStateCreateInfo multisample_state; + VkDynamicState dynamic_states[2] = {VK_DYNAMIC_STATE_VIEWPORT, + VK_DYNAMIC_STATE_SCISSOR}; + VkPipelineDynamicStateCreateInfo dynamic_state; + VkPipelineShaderStageCreateInfo shader_stages[2]; + VkVertexInputBindingDescription vertex_input_info; + VkVertexInputAttributeDescription vertex_attribute_description[3]; + VkPipelineVertexInputStateCreateInfo vertex_input; + VkGraphicsPipelineCreateInfo pipeline_info; + VkResult result; + + memset(&input_assembly_state, 0, + sizeof(VkPipelineInputAssemblyStateCreateInfo)); + input_assembly_state.sType = + VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; + input_assembly_state.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + input_assembly_state.primitiveRestartEnable = VK_FALSE; + + memset(&rasterization_state, 0, + sizeof(VkPipelineRasterizationStateCreateInfo)); + rasterization_state.sType = + VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + rasterization_state.polygonMode = VK_POLYGON_MODE_FILL; + rasterization_state.cullMode = VK_CULL_MODE_NONE; + rasterization_state.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + rasterization_state.lineWidth = 1.0f; + + memset(&color_blend_state, 0, sizeof(VkPipelineColorBlendStateCreateInfo)); + color_blend_state.sType = + VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; + color_blend_state.attachmentCount = 1; + color_blend_state.pAttachments = &attachment_state; + + memset(&viewport_state, 0, sizeof(VkPipelineViewportStateCreateInfo)); + viewport_state.sType = + VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; + viewport_state.viewportCount = 1; + viewport_state.scissorCount = 1; + + memset(&multisample_state, 0, sizeof(VkPipelineMultisampleStateCreateInfo)); + multisample_state.sType = + VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; + multisample_state.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + + memset(&dynamic_state, 0, sizeof(VkPipelineDynamicStateCreateInfo)); + dynamic_state.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; + dynamic_state.pDynamicStates = dynamic_states; + dynamic_state.dynamicStateCount = 2; + + shader_stages[0] = nk_glfw3_create_shader( + dev, nuklearshaders_nuklear_vert_spv, + nuklearshaders_nuklear_vert_spv_len, VK_SHADER_STAGE_VERTEX_BIT); + shader_stages[1] = nk_glfw3_create_shader( + dev, nuklearshaders_nuklear_frag_spv, + nuklearshaders_nuklear_frag_spv_len, VK_SHADER_STAGE_FRAGMENT_BIT); + + memset(&vertex_input_info, 0, sizeof(VkVertexInputBindingDescription)); + vertex_input_info.binding = 0; + vertex_input_info.stride = sizeof(struct nk_glfw_vertex); + vertex_input_info.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; + + memset(&vertex_attribute_description, 0, + sizeof(VkVertexInputAttributeDescription) * 3); + vertex_attribute_description[0].location = 0; + vertex_attribute_description[0].format = VK_FORMAT_R32G32_SFLOAT; + vertex_attribute_description[0].offset = + NK_OFFSETOF(struct nk_glfw_vertex, position); + vertex_attribute_description[1].location = 1; + vertex_attribute_description[1].format = VK_FORMAT_R32G32_SFLOAT; + vertex_attribute_description[1].offset = + NK_OFFSETOF(struct nk_glfw_vertex, uv); + vertex_attribute_description[2].location = 2; + vertex_attribute_description[2].format = VK_FORMAT_R8G8B8A8_UINT; + vertex_attribute_description[2].offset = + NK_OFFSETOF(struct nk_glfw_vertex, col); + + memset(&vertex_input, 0, sizeof(VkPipelineVertexInputStateCreateInfo)); + vertex_input.sType = + VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; + vertex_input.vertexBindingDescriptionCount = 1; + vertex_input.pVertexBindingDescriptions = &vertex_input_info; + vertex_input.vertexAttributeDescriptionCount = 3; + vertex_input.pVertexAttributeDescriptions = vertex_attribute_description; + + memset(&pipeline_info, 0, sizeof(VkGraphicsPipelineCreateInfo)); + pipeline_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + pipeline_info.flags = 0; + pipeline_info.stageCount = 2; + pipeline_info.pStages = shader_stages; + pipeline_info.pVertexInputState = &vertex_input; + pipeline_info.pInputAssemblyState = &input_assembly_state; + pipeline_info.pViewportState = &viewport_state; + pipeline_info.pRasterizationState = &rasterization_state; + pipeline_info.pMultisampleState = &multisample_state; + pipeline_info.pColorBlendState = &color_blend_state; + pipeline_info.pDynamicState = &dynamic_state; + pipeline_info.layout = dev->pipeline_layout; + pipeline_info.renderPass = dev->render_pass; + pipeline_info.basePipelineIndex = -1; + pipeline_info.basePipelineHandle = NULL; + + result = vkCreateGraphicsPipelines(dev->logical_device, NULL, 1, + &pipeline_info, NULL, &dev->pipeline); + NK_ASSERT(result == VK_SUCCESS); + + vkDestroyShaderModule(dev->logical_device, shader_stages[0].module, NULL); + vkDestroyShaderModule(dev->logical_device, shader_stages[1].module, NULL); +} + +NK_INTERN void nk_glfw3_create_render_resources(struct nk_glfw_device *dev, + uint32_t framebuffer_width, + uint32_t framebuffer_height) { + nk_glfw3_create_render_pass(dev); + nk_glfw3_create_framebuffers(dev, framebuffer_width, framebuffer_height); + nk_glfw3_create_descriptor_pool(dev); + nk_glfw3_create_uniform_descriptor_set_layout(dev); + nk_glfw3_create_and_update_uniform_descriptor_set(dev); + nk_glfw3_create_texture_descriptor_set_layout(dev); + nk_glfw3_create_texture_descriptor_sets(dev); + nk_glfw3_create_pipeline_layout(dev); + nk_glfw3_create_pipeline(dev); +} + +NK_API void nk_glfw3_device_create( + VkDevice logical_device, VkPhysicalDevice physical_device, + uint32_t graphics_queue_family_index, VkImageView *image_views, + uint32_t image_views_len, VkFormat color_format, + VkDeviceSize max_vertex_buffer, VkDeviceSize max_element_buffer, + uint32_t framebuffer_width, uint32_t framebuffer_height) { + struct nk_glfw_device *dev = &glfw.vulkan; + dev->max_vertex_buffer = max_vertex_buffer; + dev->max_element_buffer = max_element_buffer; + nk_buffer_init_default(&dev->cmds); + dev->logical_device = logical_device; + dev->physical_device = physical_device; + dev->image_views = image_views; + dev->image_views_len = image_views_len; + dev->color_format = color_format; + dev->framebuffers = NULL; + dev->framebuffers_len = 0; + + nk_glfw3_create_sampler(dev); + nk_glfw3_create_command_pool(dev, graphics_queue_family_index); + nk_glfw3_create_command_buffers(dev); + nk_glfw3_create_semaphore(dev); + + nk_glfw3_create_buffer_and_memory(dev, &dev->vertex_buffer, + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, + &dev->vertex_memory, max_vertex_buffer); + nk_glfw3_create_buffer_and_memory(dev, &dev->index_buffer, + VK_BUFFER_USAGE_INDEX_BUFFER_BIT, + &dev->index_memory, max_element_buffer); + nk_glfw3_create_buffer_and_memory( + dev, &dev->uniform_buffer, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, + &dev->uniform_memory, sizeof(struct Mat4f)); + + vkMapMemory(dev->logical_device, dev->vertex_memory, 0, max_vertex_buffer, + 0, &dev->mapped_vertex); + vkMapMemory(dev->logical_device, dev->index_memory, 0, max_element_buffer, + 0, &dev->mapped_index); + vkMapMemory(dev->logical_device, dev->uniform_memory, 0, + sizeof(struct Mat4f), 0, &dev->mapped_uniform); + + nk_glfw3_create_render_resources(dev, framebuffer_width, + framebuffer_height); +} + +NK_INTERN void nk_glfw3_device_upload_atlas(VkQueue graphics_queue, + const void *image, int width, + int height) { + struct nk_glfw_device *dev = &glfw.vulkan; + + VkImageCreateInfo image_info; + VkResult result; + VkMemoryRequirements mem_reqs; + VkMemoryAllocateInfo alloc_info; + VkBufferCreateInfo buffer_info; + uint8_t *data = 0; + VkCommandBufferBeginInfo begin_info; + VkCommandBuffer command_buffer; + VkImageMemoryBarrier image_memory_barrier; + VkBufferImageCopy buffer_copy_region; + VkImageMemoryBarrier image_shader_memory_barrier; + VkFence fence; + VkFenceCreateInfo fence_create; + VkSubmitInfo submit_info; + VkImageViewCreateInfo image_view_info; + struct { + VkDeviceMemory memory; + VkBuffer buffer; + } staging_buffer; + + memset(&image_info, 0, sizeof(VkImageCreateInfo)); + image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + image_info.imageType = VK_IMAGE_TYPE_2D; + image_info.format = VK_FORMAT_R8G8B8A8_UNORM; + image_info.extent.width = (uint32_t)width; + image_info.extent.height = (uint32_t)height; + image_info.extent.depth = 1; + image_info.mipLevels = 1; + image_info.arrayLayers = 1; + image_info.samples = VK_SAMPLE_COUNT_1_BIT; + image_info.tiling = VK_IMAGE_TILING_OPTIMAL; + image_info.usage = + VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; + image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + + result = + vkCreateImage(dev->logical_device, &image_info, NULL, &dev->font_image); + NK_ASSERT(result == VK_SUCCESS); + + vkGetImageMemoryRequirements(dev->logical_device, dev->font_image, + &mem_reqs); + + memset(&alloc_info, 0, sizeof(VkMemoryAllocateInfo)); + alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + alloc_info.allocationSize = mem_reqs.size; + alloc_info.memoryTypeIndex = nk_glfw3_find_memory_index( + dev->physical_device, mem_reqs.memoryTypeBits, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + + result = vkAllocateMemory(dev->logical_device, &alloc_info, NULL, + &dev->font_memory); + NK_ASSERT(result == VK_SUCCESS); + result = vkBindImageMemory(dev->logical_device, dev->font_image, + dev->font_memory, 0); + NK_ASSERT(result == VK_SUCCESS); + + memset(&buffer_info, 0, sizeof(VkBufferCreateInfo)); + buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + buffer_info.size = alloc_info.allocationSize; + buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + + result = vkCreateBuffer(dev->logical_device, &buffer_info, NULL, + &staging_buffer.buffer); + NK_ASSERT(result == VK_SUCCESS); + vkGetBufferMemoryRequirements(dev->logical_device, staging_buffer.buffer, + &mem_reqs); + + alloc_info.allocationSize = mem_reqs.size; + alloc_info.memoryTypeIndex = nk_glfw3_find_memory_index( + dev->physical_device, mem_reqs.memoryTypeBits, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + + result = vkAllocateMemory(dev->logical_device, &alloc_info, NULL, + &staging_buffer.memory); + NK_ASSERT(result == VK_SUCCESS); + result = vkBindBufferMemory(dev->logical_device, staging_buffer.buffer, + staging_buffer.memory, 0); + NK_ASSERT(result == VK_SUCCESS); + + result = vkMapMemory(dev->logical_device, staging_buffer.memory, 0, + alloc_info.allocationSize, 0, (void **)&data); + NK_ASSERT(result == VK_SUCCESS); + memcpy(data, image, width * height * 4); + vkUnmapMemory(dev->logical_device, staging_buffer.memory); + + memset(&begin_info, 0, sizeof(VkCommandBufferBeginInfo)); + begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + + NK_ASSERT(dev->command_buffers_len > 0); + /* + use the same command buffer as for render as we are regenerating the + buffer during render anyway + */ + command_buffer = dev->command_buffers[0]; + result = vkBeginCommandBuffer(command_buffer, &begin_info); + NK_ASSERT(result == VK_SUCCESS); + + memset(&image_memory_barrier, 0, sizeof(VkImageMemoryBarrier)); + image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + image_memory_barrier.image = dev->font_image; + image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + image_memory_barrier.subresourceRange.aspectMask = + VK_IMAGE_ASPECT_COLOR_BIT; + image_memory_barrier.subresourceRange.levelCount = 1; + image_memory_barrier.subresourceRange.layerCount = 1; + image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + + vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, + &image_memory_barrier); + + memset(&buffer_copy_region, 0, sizeof(VkBufferImageCopy)); + buffer_copy_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + buffer_copy_region.imageSubresource.layerCount = 1; + buffer_copy_region.imageExtent.width = (uint32_t)width; + buffer_copy_region.imageExtent.height = (uint32_t)height; + buffer_copy_region.imageExtent.depth = 1; + + vkCmdCopyBufferToImage( + command_buffer, staging_buffer.buffer, dev->font_image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &buffer_copy_region); + + memset(&image_shader_memory_barrier, 0, sizeof(VkImageMemoryBarrier)); + image_shader_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + image_shader_memory_barrier.image = dev->font_image; + image_shader_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + image_shader_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + image_shader_memory_barrier.oldLayout = + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + image_shader_memory_barrier.newLayout = + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + image_shader_memory_barrier.subresourceRange.aspectMask = + VK_IMAGE_ASPECT_COLOR_BIT; + image_shader_memory_barrier.subresourceRange.levelCount = 1; + image_shader_memory_barrier.subresourceRange.layerCount = 1; + image_shader_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + image_shader_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT, + + vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, NULL, 0, + NULL, 1, &image_shader_memory_barrier); + + result = vkEndCommandBuffer(command_buffer); + NK_ASSERT(result == VK_SUCCESS); + + memset(&fence_create, 0, sizeof(VkFenceCreateInfo)); + fence_create.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; + + result = vkCreateFence(dev->logical_device, &fence_create, NULL, &fence); + NK_ASSERT(result == VK_SUCCESS); + + memset(&submit_info, 0, sizeof(VkSubmitInfo)); + submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submit_info.commandBufferCount = 1; + submit_info.pCommandBuffers = &command_buffer; + + result = vkQueueSubmit(graphics_queue, 1, &submit_info, fence); + NK_ASSERT(result == VK_SUCCESS); + result = + vkWaitForFences(dev->logical_device, 1, &fence, VK_TRUE, UINT64_MAX); + NK_ASSERT(result == VK_SUCCESS); + + vkDestroyFence(dev->logical_device, fence, NULL); + + vkFreeMemory(dev->logical_device, staging_buffer.memory, NULL); + vkDestroyBuffer(dev->logical_device, staging_buffer.buffer, NULL); + + memset(&image_view_info, 0, sizeof(VkImageViewCreateInfo)); + image_view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + image_view_info.image = dev->font_image; + image_view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + image_view_info.format = image_info.format; + image_view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + image_view_info.subresourceRange.layerCount = 1; + image_view_info.subresourceRange.levelCount = 1; + + result = vkCreateImageView(dev->logical_device, &image_view_info, NULL, + &dev->font_image_view); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void nk_glfw3_destroy_render_resources(struct nk_glfw_device *dev) { + uint32_t i; + + vkDestroyPipeline(dev->logical_device, dev->pipeline, NULL); + vkDestroyPipelineLayout(dev->logical_device, dev->pipeline_layout, NULL); + vkDestroyDescriptorSetLayout(dev->logical_device, + dev->texture_descriptor_set_layout, NULL); + vkDestroyDescriptorSetLayout(dev->logical_device, + dev->uniform_descriptor_set_layout, NULL); + vkDestroyDescriptorPool(dev->logical_device, dev->descriptor_pool, NULL); + for (i = 0; i < dev->framebuffers_len; i++) { + vkDestroyFramebuffer(dev->logical_device, dev->framebuffers[i], NULL); + } + free(dev->framebuffers); + dev->framebuffers_len = 0; + free(dev->texture_descriptor_sets); + dev->texture_descriptor_sets_len = 0; + vkDestroyRenderPass(dev->logical_device, dev->render_pass, NULL); +} + +NK_API void nk_glfw3_resize(uint32_t framebuffer_width, + uint32_t framebuffer_height) { + struct nk_glfw_device *dev = &glfw.vulkan; + glfwGetWindowSize(glfw.win, &glfw.width, &glfw.height); + glfwGetFramebufferSize(glfw.win, &glfw.display_width, &glfw.display_height); + glfw.fb_scale.x = (float)glfw.display_width / (float)glfw.width; + glfw.fb_scale.y = (float)glfw.display_height / (float)glfw.height; + + nk_glfw3_destroy_render_resources(dev); + nk_glfw3_create_render_resources(dev, framebuffer_width, + framebuffer_height); +} + +NK_API void nk_glfw3_device_destroy(void) { + struct nk_glfw_device *dev = &glfw.vulkan; + + vkDeviceWaitIdle(dev->logical_device); + + nk_glfw3_destroy_render_resources(dev); + + vkFreeCommandBuffers(dev->logical_device, dev->command_pool, + dev->command_buffers_len, dev->command_buffers); + vkDestroyCommandPool(dev->logical_device, dev->command_pool, NULL); + vkDestroySemaphore(dev->logical_device, dev->render_completed, NULL); + + vkUnmapMemory(dev->logical_device, dev->vertex_memory); + vkUnmapMemory(dev->logical_device, dev->index_memory); + vkUnmapMemory(dev->logical_device, dev->uniform_memory); + + vkFreeMemory(dev->logical_device, dev->vertex_memory, NULL); + vkFreeMemory(dev->logical_device, dev->index_memory, NULL); + vkFreeMemory(dev->logical_device, dev->uniform_memory, NULL); + + vkDestroyBuffer(dev->logical_device, dev->vertex_buffer, NULL); + vkDestroyBuffer(dev->logical_device, dev->index_buffer, NULL); + vkDestroyBuffer(dev->logical_device, dev->uniform_buffer, NULL); + + vkDestroySampler(dev->logical_device, dev->sampler, NULL); + + vkFreeMemory(dev->logical_device, dev->font_memory, NULL); + vkDestroyImage(dev->logical_device, dev->font_image, NULL); + vkDestroyImageView(dev->logical_device, dev->font_image_view, NULL); + + free(dev->command_buffers); + nk_buffer_free(&dev->cmds); +} + +NK_API +void nk_glfw3_shutdown(void) { + nk_font_atlas_clear(&glfw.atlas); + nk_free(&glfw.ctx); + nk_glfw3_device_destroy(); + memset(&glfw, 0, sizeof(glfw)); +} + +NK_API void nk_glfw3_font_stash_begin(struct nk_font_atlas **atlas) { + nk_font_atlas_init_default(&glfw.atlas); + nk_font_atlas_begin(&glfw.atlas); + *atlas = &glfw.atlas; +} + +NK_API void nk_glfw3_font_stash_end(VkQueue graphics_queue) { + struct nk_glfw_device *dev = &glfw.vulkan; + + const void *image; + int w, h; + image = nk_font_atlas_bake(&glfw.atlas, &w, &h, NK_FONT_ATLAS_RGBA32); + nk_glfw3_device_upload_atlas(graphics_queue, image, w, h); + nk_font_atlas_end(&glfw.atlas, nk_handle_ptr(dev->font_image_view), + &dev->tex_null); + if (glfw.atlas.default_font) { + nk_style_set_font(&glfw.ctx, &glfw.atlas.default_font->handle); + } +} + +NK_API void nk_glfw3_new_frame(void) { + int i; + double x, y; + struct nk_context *ctx = &glfw.ctx; + struct GLFWwindow *win = glfw.win; + + nk_input_begin(ctx); + for (i = 0; i < glfw.text_len; ++i) + nk_input_unicode(ctx, glfw.text[i]); + +#ifdef NK_GLFW_GL4_MOUSE_GRABBING + /* optional grabbing behavior */ + if (ctx->input.mouse.grab) + glfwSetInputMode(glfw.win, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); + else if (ctx->input.mouse.ungrab) + glfwSetInputMode(glfw.win, GLFW_CURSOR, GLFW_CURSOR_NORMAL); +#endif + + nk_input_key(ctx, NK_KEY_DEL, + glfwGetKey(win, GLFW_KEY_DELETE) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_ENTER, + glfwGetKey(win, GLFW_KEY_ENTER) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TAB, glfwGetKey(win, GLFW_KEY_TAB) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_BACKSPACE, + glfwGetKey(win, GLFW_KEY_BACKSPACE) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_UP, glfwGetKey(win, GLFW_KEY_UP) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_DOWN, + glfwGetKey(win, GLFW_KEY_DOWN) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_START, + glfwGetKey(win, GLFW_KEY_HOME) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_END, + glfwGetKey(win, GLFW_KEY_END) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_SCROLL_START, + glfwGetKey(win, GLFW_KEY_HOME) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_SCROLL_END, + glfwGetKey(win, GLFW_KEY_END) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_SCROLL_DOWN, + glfwGetKey(win, GLFW_KEY_PAGE_DOWN) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_SCROLL_UP, + glfwGetKey(win, GLFW_KEY_PAGE_UP) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_SHIFT, + glfwGetKey(win, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || + glfwGetKey(win, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS); + + if (glfwGetKey(win, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS || + glfwGetKey(win, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS) { + nk_input_key(ctx, NK_KEY_COPY, + glfwGetKey(win, GLFW_KEY_C) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_PASTE, + glfwGetKey(win, GLFW_KEY_V) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_CUT, + glfwGetKey(win, GLFW_KEY_X) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_UNDO, + glfwGetKey(win, GLFW_KEY_Z) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_REDO, + glfwGetKey(win, GLFW_KEY_R) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_WORD_LEFT, + glfwGetKey(win, GLFW_KEY_LEFT) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_WORD_RIGHT, + glfwGetKey(win, GLFW_KEY_RIGHT) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_LINE_START, + glfwGetKey(win, GLFW_KEY_B) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_LINE_END, + glfwGetKey(win, GLFW_KEY_E) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_SELECT_ALL, + glfwGetKey(win, GLFW_KEY_A) == GLFW_PRESS); + } else { + nk_input_key(ctx, NK_KEY_LEFT, + glfwGetKey(win, GLFW_KEY_LEFT) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_RIGHT, + glfwGetKey(win, GLFW_KEY_RIGHT) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_COPY, 0); + nk_input_key(ctx, NK_KEY_PASTE, 0); + nk_input_key(ctx, NK_KEY_CUT, 0); + nk_input_key(ctx, NK_KEY_SHIFT, 0); + } + + glfwGetCursorPos(win, &x, &y); + nk_input_motion(ctx, (int)x, (int)y); +#ifdef NK_GLFW_GL4_MOUSE_GRABBING + if (ctx->input.mouse.grabbed) { + glfwSetCursorPos(glfw.win, ctx->input.mouse.prev.x, + ctx->input.mouse.prev.y); + ctx->input.mouse.pos.x = ctx->input.mouse.prev.x; + ctx->input.mouse.pos.y = ctx->input.mouse.prev.y; + } +#endif + nk_input_button(ctx, NK_BUTTON_LEFT, (int)x, (int)y, + glfwGetMouseButton(win, GLFW_MOUSE_BUTTON_LEFT) == + GLFW_PRESS); + nk_input_button(ctx, NK_BUTTON_MIDDLE, (int)x, (int)y, + glfwGetMouseButton(win, GLFW_MOUSE_BUTTON_MIDDLE) == + GLFW_PRESS); + nk_input_button(ctx, NK_BUTTON_RIGHT, (int)x, (int)y, + glfwGetMouseButton(win, GLFW_MOUSE_BUTTON_RIGHT) == + GLFW_PRESS); + nk_input_button(ctx, NK_BUTTON_DOUBLE, (int)glfw.double_click_pos.x, + (int)glfw.double_click_pos.y, glfw.is_double_click_down); + nk_input_scroll(ctx, glfw.scroll); + nk_input_end(&glfw.ctx); + glfw.text_len = 0; + glfw.scroll = nk_vec2(0, 0); +} + +NK_INTERN void update_texture_descriptor_set( + struct nk_glfw_device *dev, + struct nk_vulkan_texture_descriptor_set *texture_descriptor_set, + VkImageView image_view) { + VkDescriptorImageInfo descriptor_image_info; + VkWriteDescriptorSet descriptor_write; + + texture_descriptor_set->image_view = image_view; + + memset(&descriptor_image_info, 0, sizeof(VkDescriptorImageInfo)); + descriptor_image_info.sampler = dev->sampler; + descriptor_image_info.imageView = texture_descriptor_set->image_view; + descriptor_image_info.imageLayout = + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + + memset(&descriptor_write, 0, sizeof(VkWriteDescriptorSet)); + descriptor_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptor_write.dstSet = texture_descriptor_set->descriptor_set; + descriptor_write.dstBinding = 0; + descriptor_write.dstArrayElement = 0; + descriptor_write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + descriptor_write.descriptorCount = 1; + descriptor_write.pImageInfo = &descriptor_image_info; + + vkUpdateDescriptorSets(dev->logical_device, 1, &descriptor_write, 0, NULL); +} + +NK_API +VkSemaphore nk_glfw3_render(VkQueue graphics_queue, uint32_t buffer_index, + VkSemaphore wait_semaphore, + enum nk_anti_aliasing AA) { + struct nk_glfw_device *dev = &glfw.vulkan; + struct nk_buffer vbuf, ebuf; + + struct Mat4f projection = { + {2.0f, 0.0f, 0.0f, 0.0f, 0.0f, -2.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, + 0.0f, -1.0f, 1.0f, 0.0f, 1.0f}, + }; + + VkCommandBufferBeginInfo begin_info; + VkClearValue clear_value = {{{0.0f, 0.0f, 0.0f, 0.0f}}}; + VkRenderPassBeginInfo render_pass_begin_nfo; + VkCommandBuffer command_buffer; + VkResult result; + VkViewport viewport; + + VkDeviceSize doffset = 0; + VkImageView current_texture = NULL; + uint32_t index_offset = 0; + VkRect2D scissor; + uint32_t wait_semaphore_count; + VkSemaphore *wait_semaphores; + VkPipelineStageFlags wait_stage = + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + VkSubmitInfo submit_info; + + projection.m[0] /= glfw.width; + projection.m[5] /= glfw.height; + + memcpy(dev->mapped_uniform, &projection, sizeof(projection)); + + memset(&begin_info, 0, sizeof(VkCommandBufferBeginInfo)); + begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + + memset(&render_pass_begin_nfo, 0, sizeof(VkRenderPassBeginInfo)); + render_pass_begin_nfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + render_pass_begin_nfo.renderPass = dev->render_pass; + render_pass_begin_nfo.renderArea.extent.width = (uint32_t)glfw.width; + render_pass_begin_nfo.renderArea.extent.height = (uint32_t)glfw.height; + render_pass_begin_nfo.clearValueCount = 1; + render_pass_begin_nfo.pClearValues = &clear_value; + render_pass_begin_nfo.framebuffer = dev->framebuffers[buffer_index]; + + command_buffer = dev->command_buffers[buffer_index]; + + result = vkBeginCommandBuffer(command_buffer, &begin_info); + NK_ASSERT(result == VK_SUCCESS); + vkCmdBeginRenderPass(command_buffer, &render_pass_begin_nfo, + VK_SUBPASS_CONTENTS_INLINE); + + memset(&viewport, 0, sizeof(VkViewport)); + viewport.width = (float)glfw.width; + viewport.height = (float)glfw.height; + viewport.maxDepth = 1.0f; + vkCmdSetViewport(command_buffer, 0, 1, &viewport); + + vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, + dev->pipeline); + vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, + dev->pipeline_layout, 0, 1, + &dev->uniform_descriptor_set, 0, NULL); + { + /* convert from command queue into draw list and draw to screen */ + const struct nk_draw_command *cmd; + /* load draw vertices & elements directly into vertex + element buffer + */ + { + /* fill convert configuration */ + struct nk_convert_config config; + static const struct nk_draw_vertex_layout_element vertex_layout[] = + {{NK_VERTEX_POSITION, NK_FORMAT_FLOAT, + NK_OFFSETOF(struct nk_glfw_vertex, position)}, + {NK_VERTEX_TEXCOORD, NK_FORMAT_FLOAT, + NK_OFFSETOF(struct nk_glfw_vertex, uv)}, + {NK_VERTEX_COLOR, NK_FORMAT_R8G8B8A8, + NK_OFFSETOF(struct nk_glfw_vertex, col)}, + {NK_VERTEX_LAYOUT_END}}; + NK_MEMSET(&config, 0, sizeof(config)); + config.vertex_layout = vertex_layout; + config.vertex_size = sizeof(struct nk_glfw_vertex); + config.vertex_alignment = NK_ALIGNOF(struct nk_glfw_vertex); + config.tex_null = dev->tex_null; + config.circle_segment_count = 22; + config.curve_segment_count = 22; + config.arc_segment_count = 22; + config.global_alpha = 1.0f; + config.shape_AA = AA; + config.line_AA = AA; + + /* setup buffers to load vertices and elements */ + nk_buffer_init_fixed(&vbuf, dev->mapped_vertex, + (size_t)dev->max_vertex_buffer); + nk_buffer_init_fixed(&ebuf, dev->mapped_index, + (size_t)dev->max_element_buffer); + nk_convert(&glfw.ctx, &dev->cmds, &vbuf, &ebuf, &config); + } + + /* iterate over and execute each draw command */ + + vkCmdBindVertexBuffers(command_buffer, 0, 1, &dev->vertex_buffer, + &doffset); + vkCmdBindIndexBuffer(command_buffer, dev->index_buffer, 0, + VK_INDEX_TYPE_UINT16); + + nk_draw_foreach(cmd, &glfw.ctx, &dev->cmds) { + if (!cmd->texture.ptr) { + continue; + } + if (cmd->texture.ptr && cmd->texture.ptr != current_texture) { + int found = 0; + uint32_t i; + for (i = 0; i < dev->texture_descriptor_sets_len; i++) { + if (dev->texture_descriptor_sets[i].image_view == + cmd->texture.ptr) { + found = 1; + break; + } + } + + if (!found) { + update_texture_descriptor_set( + dev, &dev->texture_descriptor_sets[i], + (VkImageView)cmd->texture.ptr); + dev->texture_descriptor_sets_len++; + } + vkCmdBindDescriptorSets( + command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, + dev->pipeline_layout, 1, 1, + &dev->texture_descriptor_sets[i].descriptor_set, 0, NULL); + } + + if (!cmd->elem_count) + continue; + + scissor.offset.x = (int32_t)(NK_MAX(cmd->clip_rect.x, 0.f)); + scissor.offset.y = (int32_t)(NK_MAX(cmd->clip_rect.y, 0.f)); + scissor.extent.width = (uint32_t)(cmd->clip_rect.w); + scissor.extent.height = (uint32_t)(cmd->clip_rect.h); + vkCmdSetScissor(command_buffer, 0, 1, &scissor); + vkCmdDrawIndexed(command_buffer, cmd->elem_count, 1, index_offset, + 0, 0); + index_offset += cmd->elem_count; + } + nk_clear(&glfw.ctx); + } + + vkCmdEndRenderPass(command_buffer); + result = vkEndCommandBuffer(command_buffer); + NK_ASSERT(result == VK_SUCCESS); + + if (wait_semaphore) { + wait_semaphore_count = 1; + wait_semaphores = &wait_semaphore; + } else { + wait_semaphore_count = 0; + wait_semaphores = NULL; + } + + memset(&submit_info, 0, sizeof(VkSubmitInfo)); + submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submit_info.commandBufferCount = 1; + submit_info.pCommandBuffers = &command_buffer; + submit_info.pWaitDstStageMask = &wait_stage; + submit_info.waitSemaphoreCount = wait_semaphore_count; + submit_info.pWaitSemaphores = wait_semaphores; + submit_info.signalSemaphoreCount = 1; + submit_info.pSignalSemaphores = &dev->render_completed; + + result = vkQueueSubmit(graphics_queue, 1, &submit_info, NULL); + NK_ASSERT(result == VK_SUCCESS); + + return dev->render_completed; +} + +NK_API void nk_glfw3_char_callback(GLFWwindow *win, unsigned int codepoint) { + (void)win; + if (glfw.text_len < NK_GLFW_TEXT_MAX) + glfw.text[glfw.text_len++] = codepoint; +} + +NK_API void nk_gflw3_scroll_callback(GLFWwindow *win, double xoff, + double yoff) { + (void)win; + (void)xoff; + glfw.scroll.x += (float)xoff; + glfw.scroll.y += (float)yoff; +} + +NK_API void nk_glfw3_mouse_button_callback(GLFWwindow *window, int button, + int action, int mods) { + double x, y; + NK_UNUSED(mods); + if (button != GLFW_MOUSE_BUTTON_LEFT) + return; + glfwGetCursorPos(window, &x, &y); + if (action == GLFW_PRESS) { + double dt = glfwGetTime() - glfw.last_button_click; + if (dt > NK_GLFW_DOUBLE_CLICK_LO && dt < NK_GLFW_DOUBLE_CLICK_HI) { + glfw.is_double_click_down = nk_true; + glfw.double_click_pos = nk_vec2((float)x, (float)y); + } + glfw.last_button_click = glfwGetTime(); + } else + glfw.is_double_click_down = nk_false; +} + +NK_INTERN void nk_glfw3_clipboard_paste(nk_handle usr, + struct nk_text_edit *edit) { + const char *text = glfwGetClipboardString(glfw.win); + if (text) + nk_textedit_paste(edit, text, nk_strlen(text)); + (void)usr; +} + +NK_INTERN void nk_glfw3_clipboard_copy(nk_handle usr, const char *text, + int len) { + char *str = 0; + (void)usr; + if (!len) + return; + str = (char *)malloc((size_t)len + 1); + if (!str) + return; + memcpy(str, text, (size_t)len); + str[len] = '\0'; + glfwSetClipboardString(glfw.win, str); + free(str); +} + +NK_API struct nk_context * +nk_glfw3_init(GLFWwindow *win, VkDevice logical_device, + VkPhysicalDevice physical_device, + uint32_t graphics_queue_family_index, VkImageView *image_views, + uint32_t image_views_len, VkFormat color_format, + enum nk_glfw_init_state init_state, + VkDeviceSize max_vertex_buffer, VkDeviceSize max_element_buffer) { + memset(&glfw, 0, sizeof(struct nk_glfw)); + glfw.win = win; + if (init_state == NK_GLFW3_INSTALL_CALLBACKS) { + glfwSetScrollCallback(win, nk_gflw3_scroll_callback); + glfwSetCharCallback(win, nk_glfw3_char_callback); + glfwSetMouseButtonCallback(win, nk_glfw3_mouse_button_callback); + } + nk_init_default(&glfw.ctx, 0); + glfw.ctx.clip.copy = nk_glfw3_clipboard_copy; + glfw.ctx.clip.paste = nk_glfw3_clipboard_paste; + glfw.ctx.clip.userdata = nk_handle_ptr(0); + glfw.last_button_click = 0; + + glfwGetWindowSize(win, &glfw.width, &glfw.height); + glfwGetFramebufferSize(win, &glfw.display_width, &glfw.display_height); + + nk_glfw3_device_create(logical_device, physical_device, + graphics_queue_family_index, image_views, + image_views_len, color_format, max_vertex_buffer, + max_element_buffer, (uint32_t)glfw.display_width, + (uint32_t)glfw.display_height); + + glfw.is_double_click_down = nk_false; + glfw.double_click_pos = nk_vec2(0, 0); + + return &glfw.ctx; +} + +#endif diff --git a/demo/glfw_vulkan/src/nuklearshaders/nuklear.frag b/demo/glfw_vulkan/src/nuklearshaders/nuklear.frag new file mode 100644 index 0000000..376ad16 --- /dev/null +++ b/demo/glfw_vulkan/src/nuklearshaders/nuklear.frag @@ -0,0 +1,13 @@ +#version 450 +#extension GL_ARB_separate_shader_objects : enable + +layout(binding = 0, set = 1) uniform sampler2D currentTexture; + +layout(location = 0) in vec4 fragColor; +layout(location = 1) in vec2 fragUv; +layout(location = 0) out vec4 outColor; + +void main() { + vec4 texColor = texture(currentTexture, fragUv); + outColor = fragColor * texColor; +} diff --git a/demo/glfw_vulkan/src/nuklearshaders/nuklear.vert b/demo/glfw_vulkan/src/nuklearshaders/nuklear.vert new file mode 100644 index 0000000..3eee82d --- /dev/null +++ b/demo/glfw_vulkan/src/nuklearshaders/nuklear.vert @@ -0,0 +1,23 @@ +#version 450 +#extension GL_ARB_separate_shader_objects : enable + +out gl_PerVertex { + vec4 gl_Position; +}; + +layout(binding = 0) uniform UniformBufferObject { + mat4 projection; +} ubo; + +layout(location = 0) in vec2 position; +layout(location = 1) in vec2 uv; +layout(location = 2) in uvec4 color; +layout(location = 0) out vec4 fragColor; +layout(location = 1) out vec2 fragUv; + +void main() { + gl_Position = ubo.projection * vec4(position, 0.0, 1.0); + gl_Position.y = -gl_Position.y; + fragColor = vec4(color[0]/255.0, color[1]/255.0, color[2]/255.0, color[3]/255.0); + fragUv = uv; +} From e67d078b75f673db311461793c6bd76c4fde28a8 Mon Sep 17 00:00:00 2001 From: Andreas Streichardt Date: Sun, 22 Oct 2023 12:08:57 +0200 Subject: [PATCH 057/106] =?UTF-8?q?=F0=9F=94=A5=20remove=20compiled=20spv?= =?UTF-8?q?=20files?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- demo/glfw_vulkan/.gitignore | 1 + demo/glfw_vulkan/shaders/demo.frag.spv | Bin 664 -> 0 bytes demo/glfw_vulkan/shaders/demo.vert.spv | Bin 1284 -> 0 bytes 3 files changed, 1 insertion(+) delete mode 100644 demo/glfw_vulkan/shaders/demo.frag.spv delete mode 100644 demo/glfw_vulkan/shaders/demo.vert.spv diff --git a/demo/glfw_vulkan/.gitignore b/demo/glfw_vulkan/.gitignore index 76e4086..00569e3 100644 --- a/demo/glfw_vulkan/.gitignore +++ b/demo/glfw_vulkan/.gitignore @@ -1,2 +1,3 @@ src/nuklearshaders/*.spv src/nuklear_glfw_vulkan.h +shaders/*.spv diff --git a/demo/glfw_vulkan/shaders/demo.frag.spv b/demo/glfw_vulkan/shaders/demo.frag.spv deleted file mode 100644 index e33fcc08ae25cdadd0b9e5e97e150e7f966965bb..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 664 zcmY+APfNo<5XHwPX=|(fV?_}`TD_MZR0L5_kz4`=MLjODS#TvLAxR7UdVVS|g72*@ z#)Zk`z5VU%%sRD`hRBArWm|UTclD(PN8r_M_JhY@T$IuH^lU<+BaQ{hbfqCKGUFpO z2{$$oeMAo&eO!P)2USHramWSX2kPeGRuwu6^RU#acnc$)tMv6<&&q;Ki;O>=`oX=L zWtl3`5fkjRJ*s4E0s%V~H^8-xI*+=#j#QyK$zYcGR*hf9S5jA@q;@d># zE7QMRY4$+x0Nu2Z$>TZyt+hS`*~Shz*4tW9^jMFYGjQ?#E;8$}Px3uv)}l|InlsTm u#|x2TuUzcu3yz0;1($bp5Ufwl8aoJ{e*wjr1_(0ruTg=s(fh^?7lfb6qj-@s(1i|gt(N83{s>9D*9@fcm<1$6U7cHJe5Dd zUqV7i{3TwHIG^opBQ~1MoHJ)csbIVj~!8F7eaqZHFo!!n>UL;$0 z?%qZ*XPTuD&Agc^;|cwLid_acE;}K+AZzN^kpC(1gfd|#+J5si%IzQ?#)XaY4{>6L zQUBdX+beQ3(`dq-ov`yF>J0`_UVKSyl)B7Di5p7gK3jBCV>*}h(or%lXh|{N6PUjG zqvGwJd`owu$Mt|voOP*PjyvvGR z_f;LTr^<1E<({Q(@Z9A^ob~Ksj!BXmrRia=rI|51R#^AFR>2a}_l)eO?4@qv`+{S6 zu6jdW_lTnxbe!vT#Bj_jREB!!7WI!`7l(#;Sy5X)kgaHkKAsYj3xxR^(852cF>{Ao z5}uY1Wb}ldbBW>6gSj8vX04z551$m~JkDQ{ryqK!{u%i|#$rGCtc-fA!sq1C!>uXe zuD%92jJ{Uo>6tuzfvfNNs4xE}oa1LA*%Oa12^e$m!{aL@uJ)t9TH=GpoX1;o9=+Vt zn{q$y#Df1LrX~MSEVG)GF{fW*!Sgl8tbW(rLd`R;zV>nEDH*)4v#6Lle$Q#eaN~QH zgyFlY%eyYis005<-SNI~)FgjV2KT+zuh(24?`v!*W Date: Sun, 29 Oct 2023 10:08:29 +0100 Subject: [PATCH 058/106] Separated color_factor for button into text and background Tree node button background looked out of place when disabled, so I made the background not be affected by being disabled. --- demo/common/overview.c | 2 +- nuklear.h | 186 +++++++++++++++++++++++++---------------- src/nuklear.h | 3 +- src/nuklear_button.c | 22 ++--- src/nuklear_style.c | 69 ++++++++------- src/nuklear_widget.c | 92 +++++++++++++------- 6 files changed, 227 insertions(+), 147 deletions(-) diff --git a/demo/common/overview.c b/demo/common/overview.c index c4f15f6..5822144 100644 --- a/demo/common/overview.c +++ b/demo/common/overview.c @@ -180,6 +180,7 @@ overview(struct nk_context *ctx) nk_layout_row_static(ctx, 30, 100, 2); nk_button_symbol_label(ctx, NK_SYMBOL_TRIANGLE_LEFT, "prev", NK_TEXT_RIGHT); nk_button_symbol_label(ctx, NK_SYMBOL_TRIANGLE_RIGHT, "next", NK_TEXT_LEFT); + nk_tree_pop(ctx); } @@ -259,7 +260,6 @@ overview(struct nk_context *ctx) nk_tree_pop(ctx); } - if (nk_tree_push(ctx, NK_TREE_NODE, "Selectable", NK_MINIMIZED)) { if (nk_tree_push(ctx, NK_TREE_NODE, "List", NK_MINIMIZED)) diff --git a/nuklear.h b/nuklear.h index cf70358..ea69b00 100644 --- a/nuklear.h +++ b/nuklear.h @@ -4919,6 +4919,7 @@ struct nk_style_button { struct nk_style_item hover; struct nk_style_item active; struct nk_color border_color; + float color_factor_background; /* text */ struct nk_color text_background; @@ -4926,6 +4927,7 @@ struct nk_style_button { struct nk_color text_hover; struct nk_color text_active; nk_flags text_alignment; + float color_factor_text; /* properties */ float border; @@ -4933,7 +4935,6 @@ struct nk_style_button { struct nk_vec2 padding; struct nk_vec2 image_padding; struct nk_vec2 touch_padding; - float color_factor; float disabled_factor; /* optional user callbacks */ @@ -18288,25 +18289,26 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) /* default button */ button = &style->button; nk_zero_struct(*button); - button->normal = nk_style_item_color(table[NK_COLOR_BUTTON]); - button->hover = nk_style_item_color(table[NK_COLOR_BUTTON_HOVER]); - button->active = nk_style_item_color(table[NK_COLOR_BUTTON_ACTIVE]); - button->border_color = table[NK_COLOR_BORDER]; - button->text_background = table[NK_COLOR_BUTTON]; - button->text_normal = table[NK_COLOR_TEXT]; - button->text_hover = table[NK_COLOR_TEXT]; - button->text_active = table[NK_COLOR_TEXT]; - button->padding = nk_vec2(2.0f,2.0f); - button->image_padding = nk_vec2(0.0f,0.0f); - button->touch_padding = nk_vec2(0.0f, 0.0f); - button->userdata = nk_handle_ptr(0); - button->text_alignment = NK_TEXT_CENTERED; - button->border = 1.0f; - button->rounding = 4.0f; - button->color_factor = 1.0f; - button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; - button->draw_begin = 0; - button->draw_end = 0; + button->normal = nk_style_item_color(table[NK_COLOR_BUTTON]); + button->hover = nk_style_item_color(table[NK_COLOR_BUTTON_HOVER]); + button->active = nk_style_item_color(table[NK_COLOR_BUTTON_ACTIVE]); + button->border_color = table[NK_COLOR_BORDER]; + button->text_background = table[NK_COLOR_BUTTON]; + button->text_normal = table[NK_COLOR_TEXT]; + button->text_hover = table[NK_COLOR_TEXT]; + button->text_active = table[NK_COLOR_TEXT]; + button->padding = nk_vec2(2.0f,2.0f); + button->image_padding = nk_vec2(0.0f,0.0f); + button->touch_padding = nk_vec2(0.0f, 0.0f); + button->userdata = nk_handle_ptr(0); + button->text_alignment = NK_TEXT_CENTERED; + button->border = 1.0f; + button->rounding = 4.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; + button->draw_begin = 0; + button->draw_end = 0; /* contextual button */ button = &style->contextual_button; @@ -18325,7 +18327,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; - button->color_factor = 1.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -18347,7 +18350,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 1.0f; - button->color_factor = 1.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -18462,7 +18466,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 1.0f; button->rounding = 0.0f; - button->color_factor = 1.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -18532,7 +18537,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 1.0f; button->rounding = 0.0f; - button->color_factor = 1.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -18606,7 +18612,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; - button->color_factor = 1.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -18687,7 +18694,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; - button->color_factor = 1.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -18724,7 +18732,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; - button->color_factor = 1.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -18747,7 +18756,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; - button->color_factor = 1.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -18786,7 +18796,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; - button->color_factor = 1.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -18808,7 +18819,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; - button->color_factor = 1.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -23336,36 +23348,50 @@ nk_widget_disable_begin(struct nk_context* ctx) win->widgets_disabled = nk_true; - style->button.color_factor = style->button.disabled_factor; + style->button.color_factor_text = style->button.disabled_factor; + style->button.color_factor_background = style->button.disabled_factor; style->chart.color_factor = style->chart.disabled_factor; style->checkbox.color_factor = style->checkbox.disabled_factor; style->combo.color_factor = style->combo.disabled_factor; - style->combo.button.color_factor = style->combo.button.disabled_factor; - style->contextual_button.color_factor = style->contextual_button.disabled_factor; + style->combo.button.color_factor_text = style->combo.button.disabled_factor; + style->combo.button.color_factor_background = style->combo.button.disabled_factor; + style->contextual_button.color_factor_text = style->contextual_button.disabled_factor; + style->contextual_button.color_factor_background = style->contextual_button.disabled_factor; style->edit.color_factor = style->edit.disabled_factor; style->edit.scrollbar.color_factor = style->edit.scrollbar.disabled_factor; - style->menu_button.color_factor = style->menu_button.disabled_factor; + style->menu_button.color_factor_text = style->menu_button.disabled_factor; + style->menu_button.color_factor_background = style->menu_button.disabled_factor; style->option.color_factor = style->option.disabled_factor; style->progress.color_factor = style->progress.disabled_factor; style->property.color_factor = style->property.disabled_factor; - style->property.inc_button.color_factor = style->property.inc_button.disabled_factor; - style->property.dec_button.color_factor = style->property.dec_button.disabled_factor; + style->property.inc_button.color_factor_text = style->property.inc_button.disabled_factor; + style->property.inc_button.color_factor_background = style->property.inc_button.disabled_factor; + style->property.dec_button.color_factor_text = style->property.dec_button.disabled_factor; + style->property.dec_button.color_factor_background = style->property.dec_button.disabled_factor; style->property.edit.color_factor = style->property.edit.disabled_factor; style->scrollh.color_factor = style->scrollh.disabled_factor; - style->scrollh.inc_button.color_factor = style->scrollh.inc_button.disabled_factor; - style->scrollh.dec_button.color_factor = style->scrollh.dec_button.disabled_factor; + style->scrollh.inc_button.color_factor_text = style->scrollh.inc_button.disabled_factor; + style->scrollh.inc_button.color_factor_background = style->scrollh.inc_button.disabled_factor; + style->scrollh.dec_button.color_factor_text = style->scrollh.dec_button.disabled_factor; + style->scrollh.dec_button.color_factor_background = style->scrollh.dec_button.disabled_factor; style->scrollv.color_factor = style->scrollv.disabled_factor; - style->scrollv.inc_button.color_factor = style->scrollv.inc_button.disabled_factor; - style->scrollv.dec_button.color_factor = style->scrollv.dec_button.disabled_factor; + style->scrollv.inc_button.color_factor_text = style->scrollv.inc_button.disabled_factor; + style->scrollv.inc_button.color_factor_background = style->scrollv.inc_button.disabled_factor; + style->scrollv.dec_button.color_factor_text = style->scrollv.dec_button.disabled_factor; + style->scrollv.dec_button.color_factor_background = style->scrollv.dec_button.disabled_factor; style->selectable.color_factor = style->selectable.disabled_factor; style->slider.color_factor = style->slider.disabled_factor; - style->slider.inc_button.color_factor = style->slider.inc_button.disabled_factor; - style->slider.dec_button.color_factor = style->slider.dec_button.disabled_factor; + style->slider.inc_button.color_factor_text = style->slider.inc_button.disabled_factor; + style->slider.inc_button.color_factor_background = style->slider.inc_button.disabled_factor; + style->slider.dec_button.color_factor_text = style->slider.dec_button.disabled_factor; + style->slider.dec_button.color_factor_background = style->slider.dec_button.disabled_factor; style->tab.color_factor = style->tab.disabled_factor; - style->tab.node_maximize_button.color_factor = style->tab.node_maximize_button.disabled_factor; - style->tab.node_minimize_button.color_factor = style->tab.node_minimize_button.disabled_factor; - style->tab.tab_maximize_button.color_factor = style->tab.tab_maximize_button.disabled_factor; - style->tab.tab_minimize_button.color_factor = style->tab.tab_minimize_button.disabled_factor; + style->tab.node_maximize_button.color_factor_text = style->tab.node_maximize_button.disabled_factor; + style->tab.node_minimize_button.color_factor_text = style->tab.node_minimize_button.disabled_factor; + style->tab.tab_maximize_button.color_factor_text = style->tab.tab_maximize_button.disabled_factor; + style->tab.tab_maximize_button.color_factor_background = style->tab.tab_maximize_button.disabled_factor; + style->tab.tab_minimize_button.color_factor_text = style->tab.tab_minimize_button.disabled_factor; + style->tab.tab_minimize_button.color_factor_background = style->tab.tab_minimize_button.disabled_factor; style->text.color_factor = style->text.disabled_factor; } NK_API void @@ -23385,36 +23411,50 @@ nk_widget_disable_end(struct nk_context* ctx) win->widgets_disabled = nk_false; - style->button.color_factor = 1.0f; + style->button.color_factor_text = 1.0f; + style->button.color_factor_background = 1.0f; style->chart.color_factor = 1.0f; style->checkbox.color_factor = 1.0f; style->combo.color_factor = 1.0f; - style->combo.button.color_factor = 1.0f; - style->contextual_button.color_factor = 1.0f; + style->combo.button.color_factor_text = 1.0f; + style->combo.button.color_factor_background = 1.0f; + style->contextual_button.color_factor_text = 1.0f; + style->contextual_button.color_factor_background = 1.0f; style->edit.color_factor = 1.0f; style->edit.scrollbar.color_factor = 1.0f; - style->menu_button.color_factor = 1.0f; + style->menu_button.color_factor_text = 1.0f; + style->menu_button.color_factor_background = 1.0f; style->option.color_factor = 1.0f; style->progress.color_factor = 1.0f; style->property.color_factor = 1.0f; - style->property.inc_button.color_factor = 1.0f; - style->property.dec_button.color_factor = 1.0f; + style->property.inc_button.color_factor_text = 1.0f; + style->property.inc_button.color_factor_background = 1.0f; + style->property.dec_button.color_factor_text = 1.0f; + style->property.dec_button.color_factor_background = 1.0f; style->property.edit.color_factor = 1.0f; style->scrollh.color_factor = 1.0f; - style->scrollh.inc_button.color_factor = 1.0f; - style->scrollh.dec_button.color_factor = 1.0f; + style->scrollh.inc_button.color_factor_text = 1.0f; + style->scrollh.inc_button.color_factor_background = 1.0f; + style->scrollh.dec_button.color_factor_text = 1.0f; + style->scrollh.dec_button.color_factor_background = 1.0f; style->scrollv.color_factor = 1.0f; - style->scrollv.inc_button.color_factor = 1.0f; - style->scrollv.dec_button.color_factor = 1.0f; + style->scrollv.inc_button.color_factor_text = 1.0f; + style->scrollv.inc_button.color_factor_background = 1.0f; + style->scrollv.dec_button.color_factor_text = 1.0f; + style->scrollv.dec_button.color_factor_background = 1.0f; style->selectable.color_factor = 1.0f; style->slider.color_factor = 1.0f; - style->slider.inc_button.color_factor = 1.0f; - style->slider.dec_button.color_factor = 1.0f; + style->slider.inc_button.color_factor_text = 1.0f; + style->slider.inc_button.color_factor_background = 1.0f; + style->slider.dec_button.color_factor_text = 1.0f; + style->slider.dec_button.color_factor_background = 1.0f; style->tab.color_factor = 1.0f; - style->tab.node_maximize_button.color_factor = 1.0f; - style->tab.node_minimize_button.color_factor = 1.0f; - style->tab.tab_maximize_button.color_factor = 1.0f; - style->tab.tab_minimize_button.color_factor = 1.0f; + style->tab.node_maximize_button.color_factor_text = 1.0f; + style->tab.node_minimize_button.color_factor_text = 1.0f; + style->tab.tab_maximize_button.color_factor_text = 1.0f; + style->tab.tab_maximize_button.color_factor_background = 1.0f; + style->tab.tab_minimize_button.color_factor_text = 1.0f; + style->tab.tab_minimize_button.color_factor_background = 1.0f; style->text.color_factor = 1.0f; } @@ -24060,14 +24100,14 @@ nk_draw_button(struct nk_command_buffer *out, switch (background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); + nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor_background)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); + nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor_background)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); - nk_stroke_rect(out, *bounds, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor)); + nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor_background)); + nk_stroke_rect(out, *bounds, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor_background)); break; } return background; @@ -24117,7 +24157,7 @@ nk_draw_button_text(struct nk_command_buffer *out, text.text = style->text_active; else text.text = style->text_normal; - text.text = nk_rgb_factor(text.text, style->color_factor); + text.text = nk_rgb_factor(text.text, style->color_factor_text); text.padding = nk_vec2(0,0); nk_widget_text(out, *content, txt, len, &text, text_alignment, font); @@ -24167,7 +24207,7 @@ nk_draw_button_symbol(struct nk_command_buffer *out, sym = style->text_active; else sym = style->text_normal; - sym = nk_rgb_factor(sym, style->color_factor); + sym = nk_rgb_factor(sym, style->color_factor_text); nk_draw_symbol(out, type, *content, bg, sym, 1, font); } NK_LIB nk_bool @@ -24199,7 +24239,7 @@ nk_draw_button_image(struct nk_command_buffer *out, nk_flags state, const struct nk_style_button *style, const struct nk_image *img) { nk_draw_button(out, bounds, state, style); - nk_draw_image(out, *content, img, nk_rgb_factor(nk_white, style->color_factor)); + nk_draw_image(out, *content, img, nk_rgb_factor(nk_white, style->color_factor_background)); } NK_LIB nk_bool nk_do_button_image(nk_flags *state, @@ -24256,8 +24296,8 @@ nk_draw_button_text_symbol(struct nk_command_buffer *out, text.text = style->text_normal; } - sym = nk_rgb_factor(sym, style->color_factor); - text.text = nk_rgb_factor(text.text, style->color_factor); + sym = nk_rgb_factor(sym, style->color_factor_text); + text.text = nk_rgb_factor(text.text, style->color_factor_text); text.padding = nk_vec2(0,0); nk_draw_symbol(out, type, *symbol, style->text_background, sym, 0, font); nk_widget_text(out, *label, str, len, &text, NK_TEXT_CENTERED, font); @@ -24315,10 +24355,10 @@ nk_draw_button_text_image(struct nk_command_buffer *out, text.text = style->text_active; else text.text = style->text_normal; - text.text = nk_rgb_factor(text.text, style->color_factor); + text.text = nk_rgb_factor(text.text, style->color_factor_text); text.padding = nk_vec2(0, 0); nk_widget_text(out, *label, str, len, &text, NK_TEXT_CENTERED, font); - nk_draw_image(out, *image, img, nk_rgb_factor(nk_white, style->color_factor)); + nk_draw_image(out, *image, img, nk_rgb_factor(nk_white, style->color_factor_background)); } NK_LIB nk_bool nk_do_button_text_image(nk_flags *state, diff --git a/src/nuklear.h b/src/nuklear.h index a16607b..a7a0243 100644 --- a/src/nuklear.h +++ b/src/nuklear.h @@ -4697,6 +4697,7 @@ struct nk_style_button { struct nk_style_item hover; struct nk_style_item active; struct nk_color border_color; + float color_factor_background; /* text */ struct nk_color text_background; @@ -4704,6 +4705,7 @@ struct nk_style_button { struct nk_color text_hover; struct nk_color text_active; nk_flags text_alignment; + float color_factor_text; /* properties */ float border; @@ -4711,7 +4713,6 @@ struct nk_style_button { struct nk_vec2 padding; struct nk_vec2 image_padding; struct nk_vec2 touch_padding; - float color_factor; float disabled_factor; /* optional user callbacks */ diff --git a/src/nuklear_button.c b/src/nuklear_button.c index 423e0df..fca7f0c 100644 --- a/src/nuklear_button.c +++ b/src/nuklear_button.c @@ -100,14 +100,14 @@ nk_draw_button(struct nk_command_buffer *out, switch (background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); + nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor_background)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); + nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor_background)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); - nk_stroke_rect(out, *bounds, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor)); + nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor_background)); + nk_stroke_rect(out, *bounds, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor_background)); break; } return background; @@ -157,7 +157,7 @@ nk_draw_button_text(struct nk_command_buffer *out, text.text = style->text_active; else text.text = style->text_normal; - text.text = nk_rgb_factor(text.text, style->color_factor); + text.text = nk_rgb_factor(text.text, style->color_factor_text); text.padding = nk_vec2(0,0); nk_widget_text(out, *content, txt, len, &text, text_alignment, font); @@ -207,7 +207,7 @@ nk_draw_button_symbol(struct nk_command_buffer *out, sym = style->text_active; else sym = style->text_normal; - sym = nk_rgb_factor(sym, style->color_factor); + sym = nk_rgb_factor(sym, style->color_factor_text); nk_draw_symbol(out, type, *content, bg, sym, 1, font); } NK_LIB nk_bool @@ -239,7 +239,7 @@ nk_draw_button_image(struct nk_command_buffer *out, nk_flags state, const struct nk_style_button *style, const struct nk_image *img) { nk_draw_button(out, bounds, state, style); - nk_draw_image(out, *content, img, nk_rgb_factor(nk_white, style->color_factor)); + nk_draw_image(out, *content, img, nk_rgb_factor(nk_white, style->color_factor_background)); } NK_LIB nk_bool nk_do_button_image(nk_flags *state, @@ -296,8 +296,8 @@ nk_draw_button_text_symbol(struct nk_command_buffer *out, text.text = style->text_normal; } - sym = nk_rgb_factor(sym, style->color_factor); - text.text = nk_rgb_factor(text.text, style->color_factor); + sym = nk_rgb_factor(sym, style->color_factor_text); + text.text = nk_rgb_factor(text.text, style->color_factor_text); text.padding = nk_vec2(0,0); nk_draw_symbol(out, type, *symbol, style->text_background, sym, 0, font); nk_widget_text(out, *label, str, len, &text, NK_TEXT_CENTERED, font); @@ -355,10 +355,10 @@ nk_draw_button_text_image(struct nk_command_buffer *out, text.text = style->text_active; else text.text = style->text_normal; - text.text = nk_rgb_factor(text.text, style->color_factor); + text.text = nk_rgb_factor(text.text, style->color_factor_text); text.padding = nk_vec2(0, 0); nk_widget_text(out, *label, str, len, &text, NK_TEXT_CENTERED, font); - nk_draw_image(out, *image, img, nk_rgb_factor(nk_white, style->color_factor)); + nk_draw_image(out, *image, img, nk_rgb_factor(nk_white, style->color_factor_background)); } NK_LIB nk_bool nk_do_button_text_image(nk_flags *state, diff --git a/src/nuklear_style.c b/src/nuklear_style.c index b97ad71..6cf4514 100644 --- a/src/nuklear_style.c +++ b/src/nuklear_style.c @@ -119,25 +119,26 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) /* default button */ button = &style->button; nk_zero_struct(*button); - button->normal = nk_style_item_color(table[NK_COLOR_BUTTON]); - button->hover = nk_style_item_color(table[NK_COLOR_BUTTON_HOVER]); - button->active = nk_style_item_color(table[NK_COLOR_BUTTON_ACTIVE]); - button->border_color = table[NK_COLOR_BORDER]; - button->text_background = table[NK_COLOR_BUTTON]; - button->text_normal = table[NK_COLOR_TEXT]; - button->text_hover = table[NK_COLOR_TEXT]; - button->text_active = table[NK_COLOR_TEXT]; - button->padding = nk_vec2(2.0f,2.0f); - button->image_padding = nk_vec2(0.0f,0.0f); - button->touch_padding = nk_vec2(0.0f, 0.0f); - button->userdata = nk_handle_ptr(0); - button->text_alignment = NK_TEXT_CENTERED; - button->border = 1.0f; - button->rounding = 4.0f; - button->color_factor = 1.0f; - button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; - button->draw_begin = 0; - button->draw_end = 0; + button->normal = nk_style_item_color(table[NK_COLOR_BUTTON]); + button->hover = nk_style_item_color(table[NK_COLOR_BUTTON_HOVER]); + button->active = nk_style_item_color(table[NK_COLOR_BUTTON_ACTIVE]); + button->border_color = table[NK_COLOR_BORDER]; + button->text_background = table[NK_COLOR_BUTTON]; + button->text_normal = table[NK_COLOR_TEXT]; + button->text_hover = table[NK_COLOR_TEXT]; + button->text_active = table[NK_COLOR_TEXT]; + button->padding = nk_vec2(2.0f,2.0f); + button->image_padding = nk_vec2(0.0f,0.0f); + button->touch_padding = nk_vec2(0.0f, 0.0f); + button->userdata = nk_handle_ptr(0); + button->text_alignment = NK_TEXT_CENTERED; + button->border = 1.0f; + button->rounding = 4.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; + button->draw_begin = 0; + button->draw_end = 0; /* contextual button */ button = &style->contextual_button; @@ -156,7 +157,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; - button->color_factor = 1.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -178,7 +180,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 1.0f; - button->color_factor = 1.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -293,7 +296,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 1.0f; button->rounding = 0.0f; - button->color_factor = 1.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -363,7 +367,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 1.0f; button->rounding = 0.0f; - button->color_factor = 1.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -437,7 +442,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; - button->color_factor = 1.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -518,7 +524,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; - button->color_factor = 1.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -555,7 +562,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; - button->color_factor = 1.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -578,7 +586,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; - button->color_factor = 1.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -617,7 +626,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; - button->color_factor = 1.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -639,7 +649,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; - button->color_factor = 1.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; diff --git a/src/nuklear_widget.c b/src/nuklear_widget.c index f2a243c..a21f137 100644 --- a/src/nuklear_widget.c +++ b/src/nuklear_widget.c @@ -246,36 +246,50 @@ nk_widget_disable_begin(struct nk_context* ctx) win->widgets_disabled = nk_true; - style->button.color_factor = style->button.disabled_factor; + style->button.color_factor_text = style->button.disabled_factor; + style->button.color_factor_background = style->button.disabled_factor; style->chart.color_factor = style->chart.disabled_factor; style->checkbox.color_factor = style->checkbox.disabled_factor; style->combo.color_factor = style->combo.disabled_factor; - style->combo.button.color_factor = style->combo.button.disabled_factor; - style->contextual_button.color_factor = style->contextual_button.disabled_factor; + style->combo.button.color_factor_text = style->combo.button.disabled_factor; + style->combo.button.color_factor_background = style->combo.button.disabled_factor; + style->contextual_button.color_factor_text = style->contextual_button.disabled_factor; + style->contextual_button.color_factor_background = style->contextual_button.disabled_factor; style->edit.color_factor = style->edit.disabled_factor; style->edit.scrollbar.color_factor = style->edit.scrollbar.disabled_factor; - style->menu_button.color_factor = style->menu_button.disabled_factor; + style->menu_button.color_factor_text = style->menu_button.disabled_factor; + style->menu_button.color_factor_background = style->menu_button.disabled_factor; style->option.color_factor = style->option.disabled_factor; style->progress.color_factor = style->progress.disabled_factor; style->property.color_factor = style->property.disabled_factor; - style->property.inc_button.color_factor = style->property.inc_button.disabled_factor; - style->property.dec_button.color_factor = style->property.dec_button.disabled_factor; + style->property.inc_button.color_factor_text = style->property.inc_button.disabled_factor; + style->property.inc_button.color_factor_background = style->property.inc_button.disabled_factor; + style->property.dec_button.color_factor_text = style->property.dec_button.disabled_factor; + style->property.dec_button.color_factor_background = style->property.dec_button.disabled_factor; style->property.edit.color_factor = style->property.edit.disabled_factor; style->scrollh.color_factor = style->scrollh.disabled_factor; - style->scrollh.inc_button.color_factor = style->scrollh.inc_button.disabled_factor; - style->scrollh.dec_button.color_factor = style->scrollh.dec_button.disabled_factor; + style->scrollh.inc_button.color_factor_text = style->scrollh.inc_button.disabled_factor; + style->scrollh.inc_button.color_factor_background = style->scrollh.inc_button.disabled_factor; + style->scrollh.dec_button.color_factor_text = style->scrollh.dec_button.disabled_factor; + style->scrollh.dec_button.color_factor_background = style->scrollh.dec_button.disabled_factor; style->scrollv.color_factor = style->scrollv.disabled_factor; - style->scrollv.inc_button.color_factor = style->scrollv.inc_button.disabled_factor; - style->scrollv.dec_button.color_factor = style->scrollv.dec_button.disabled_factor; + style->scrollv.inc_button.color_factor_text = style->scrollv.inc_button.disabled_factor; + style->scrollv.inc_button.color_factor_background = style->scrollv.inc_button.disabled_factor; + style->scrollv.dec_button.color_factor_text = style->scrollv.dec_button.disabled_factor; + style->scrollv.dec_button.color_factor_background = style->scrollv.dec_button.disabled_factor; style->selectable.color_factor = style->selectable.disabled_factor; style->slider.color_factor = style->slider.disabled_factor; - style->slider.inc_button.color_factor = style->slider.inc_button.disabled_factor; - style->slider.dec_button.color_factor = style->slider.dec_button.disabled_factor; + style->slider.inc_button.color_factor_text = style->slider.inc_button.disabled_factor; + style->slider.inc_button.color_factor_background = style->slider.inc_button.disabled_factor; + style->slider.dec_button.color_factor_text = style->slider.dec_button.disabled_factor; + style->slider.dec_button.color_factor_background = style->slider.dec_button.disabled_factor; style->tab.color_factor = style->tab.disabled_factor; - style->tab.node_maximize_button.color_factor = style->tab.node_maximize_button.disabled_factor; - style->tab.node_minimize_button.color_factor = style->tab.node_minimize_button.disabled_factor; - style->tab.tab_maximize_button.color_factor = style->tab.tab_maximize_button.disabled_factor; - style->tab.tab_minimize_button.color_factor = style->tab.tab_minimize_button.disabled_factor; + style->tab.node_maximize_button.color_factor_text = style->tab.node_maximize_button.disabled_factor; + style->tab.node_minimize_button.color_factor_text = style->tab.node_minimize_button.disabled_factor; + style->tab.tab_maximize_button.color_factor_text = style->tab.tab_maximize_button.disabled_factor; + style->tab.tab_maximize_button.color_factor_background = style->tab.tab_maximize_button.disabled_factor; + style->tab.tab_minimize_button.color_factor_text = style->tab.tab_minimize_button.disabled_factor; + style->tab.tab_minimize_button.color_factor_background = style->tab.tab_minimize_button.disabled_factor; style->text.color_factor = style->text.disabled_factor; } NK_API void @@ -295,35 +309,49 @@ nk_widget_disable_end(struct nk_context* ctx) win->widgets_disabled = nk_false; - style->button.color_factor = 1.0f; + style->button.color_factor_text = 1.0f; + style->button.color_factor_background = 1.0f; style->chart.color_factor = 1.0f; style->checkbox.color_factor = 1.0f; style->combo.color_factor = 1.0f; - style->combo.button.color_factor = 1.0f; - style->contextual_button.color_factor = 1.0f; + style->combo.button.color_factor_text = 1.0f; + style->combo.button.color_factor_background = 1.0f; + style->contextual_button.color_factor_text = 1.0f; + style->contextual_button.color_factor_background = 1.0f; style->edit.color_factor = 1.0f; style->edit.scrollbar.color_factor = 1.0f; - style->menu_button.color_factor = 1.0f; + style->menu_button.color_factor_text = 1.0f; + style->menu_button.color_factor_background = 1.0f; style->option.color_factor = 1.0f; style->progress.color_factor = 1.0f; style->property.color_factor = 1.0f; - style->property.inc_button.color_factor = 1.0f; - style->property.dec_button.color_factor = 1.0f; + style->property.inc_button.color_factor_text = 1.0f; + style->property.inc_button.color_factor_background = 1.0f; + style->property.dec_button.color_factor_text = 1.0f; + style->property.dec_button.color_factor_background = 1.0f; style->property.edit.color_factor = 1.0f; style->scrollh.color_factor = 1.0f; - style->scrollh.inc_button.color_factor = 1.0f; - style->scrollh.dec_button.color_factor = 1.0f; + style->scrollh.inc_button.color_factor_text = 1.0f; + style->scrollh.inc_button.color_factor_background = 1.0f; + style->scrollh.dec_button.color_factor_text = 1.0f; + style->scrollh.dec_button.color_factor_background = 1.0f; style->scrollv.color_factor = 1.0f; - style->scrollv.inc_button.color_factor = 1.0f; - style->scrollv.dec_button.color_factor = 1.0f; + style->scrollv.inc_button.color_factor_text = 1.0f; + style->scrollv.inc_button.color_factor_background = 1.0f; + style->scrollv.dec_button.color_factor_text = 1.0f; + style->scrollv.dec_button.color_factor_background = 1.0f; style->selectable.color_factor = 1.0f; style->slider.color_factor = 1.0f; - style->slider.inc_button.color_factor = 1.0f; - style->slider.dec_button.color_factor = 1.0f; + style->slider.inc_button.color_factor_text = 1.0f; + style->slider.inc_button.color_factor_background = 1.0f; + style->slider.dec_button.color_factor_text = 1.0f; + style->slider.dec_button.color_factor_background = 1.0f; style->tab.color_factor = 1.0f; - style->tab.node_maximize_button.color_factor = 1.0f; - style->tab.node_minimize_button.color_factor = 1.0f; - style->tab.tab_maximize_button.color_factor = 1.0f; - style->tab.tab_minimize_button.color_factor = 1.0f; + style->tab.node_maximize_button.color_factor_text = 1.0f; + style->tab.node_minimize_button.color_factor_text = 1.0f; + style->tab.tab_maximize_button.color_factor_text = 1.0f; + style->tab.tab_maximize_button.color_factor_background = 1.0f; + style->tab.tab_minimize_button.color_factor_text = 1.0f; + style->tab.tab_minimize_button.color_factor_background = 1.0f; style->text.color_factor = 1.0f; } From f88d7b58bb944b0bbedcc4bd7799ca3ed714c28a Mon Sep 17 00:00:00 2001 From: Yukyduky Date: Sun, 29 Oct 2023 10:18:09 +0100 Subject: [PATCH 059/106] Fixed tabs not being shown as disabled properly --- nuklear.h | 10 +++++----- src/nuklear_tree.c | 10 +++++----- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/nuklear.h b/nuklear.h index ea69b00..580026a 100644 --- a/nuklear.h +++ b/nuklear.h @@ -22483,15 +22483,15 @@ nk_tree_state_base(struct nk_context *ctx, enum nk_tree_type type, switch(background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, header, &background->data.image, nk_white); + nk_draw_image(out, header, &background->data.image, nk_rgb_factor(nk_white, style->tab.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, header, &background->data.slice, nk_white); + nk_draw_nine_slice(out, header, &background->data.slice, nk_rgb_factor(nk_white, style->tab.color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, header, 0, style->tab.border_color); + nk_fill_rect(out, header, 0, nk_rgb_factor(style->tab.border_color, style->tab.color_factor)); nk_fill_rect(out, nk_shrink_rect(header, style->tab.border), - style->tab.rounding, background->data.color); + style->tab.rounding, nk_rgb_factor(background->data.color, style->tab.color_factor)); break; } } else text.background = style->window.background; @@ -22536,7 +22536,7 @@ nk_tree_state_base(struct nk_context *ctx, enum nk_tree_type type, label.y = sym.y; label.w = header.w - (sym.w + item_spacing.y + style->tab.indent); label.h = style->font->height; - text.text = style->tab.text; + text.text = nk_rgb_factor(style->tab.text, style->tab.color_factor); text.padding = nk_vec2(0,0); nk_widget_text(out, label, title, nk_strlen(title), &text, NK_TEXT_LEFT, style->font);} diff --git a/src/nuklear_tree.c b/src/nuklear_tree.c index ef37ff0..8ecc8c3 100644 --- a/src/nuklear_tree.c +++ b/src/nuklear_tree.c @@ -52,15 +52,15 @@ nk_tree_state_base(struct nk_context *ctx, enum nk_tree_type type, switch(background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, header, &background->data.image, nk_white); + nk_draw_image(out, header, &background->data.image, nk_rgb_factor(nk_white, style->tab.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, header, &background->data.slice, nk_white); + nk_draw_nine_slice(out, header, &background->data.slice, nk_rgb_factor(nk_white, style->tab.color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, header, 0, style->tab.border_color); + nk_fill_rect(out, header, 0, nk_rgb_factor(style->tab.border_color, style->tab.color_factor)); nk_fill_rect(out, nk_shrink_rect(header, style->tab.border), - style->tab.rounding, background->data.color); + style->tab.rounding, nk_rgb_factor(background->data.color, style->tab.color_factor)); break; } } else text.background = style->window.background; @@ -105,7 +105,7 @@ nk_tree_state_base(struct nk_context *ctx, enum nk_tree_type type, label.y = sym.y; label.w = header.w - (sym.w + item_spacing.y + style->tab.indent); label.h = style->font->height; - text.text = style->tab.text; + text.text = nk_rgb_factor(style->tab.text, style->tab.color_factor); text.padding = nk_vec2(0,0); nk_widget_text(out, label, title, nk_strlen(title), &text, NK_TEXT_LEFT, style->font);} From a3f0da05ab1212291aabc4319aa4d70e89313e05 Mon Sep 17 00:00:00 2001 From: Andreas Streichardt Date: Mon, 13 Nov 2023 09:17:17 +0100 Subject: [PATCH 060/106] =?UTF-8?q?=E2=9C=A8=20make=20vulkan=20validation?= =?UTF-8?q?=20layers=20optional?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- demo/glfw_vulkan/main.c | 133 ++++++++++++++++++++++------------------ 1 file changed, 74 insertions(+), 59 deletions(-) diff --git a/demo/glfw_vulkan/main.c b/demo/glfw_vulkan/main.c index 8e0b39d..555a5aa 100644 --- a/demo/glfw_vulkan/main.c +++ b/demo/glfw_vulkan/main.c @@ -102,7 +102,7 @@ void swap_chain_support_details_free( struct vulkan_demo { GLFWwindow *win; VkInstance instance; - VkDebugUtilsMessengerEXT debugMessenger; + VkDebugUtilsMessengerEXT debug_messenger; VkSurfaceKHR surface; VkPhysicalDevice physical_device; struct queue_family_indices indices; @@ -193,6 +193,43 @@ cleanup: return ret; } +VkResult create_debug_utils_messenger_ext( + VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT *pCreateInfo, + const VkAllocationCallbacks *pAllocator, + VkDebugUtilsMessengerEXT *pDebugMessenger) { + PFN_vkCreateDebugUtilsMessengerEXT func = + (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr( + instance, "vkCreateDebugUtilsMessengerEXT"); + if (func != NULL) { + return func(instance, pCreateInfo, pAllocator, pDebugMessenger); + } else { + return VK_ERROR_EXTENSION_NOT_PRESENT; + } +} + +bool create_debug_callback(struct vulkan_demo *demo) { + VkResult result; + + VkDebugUtilsMessengerCreateInfoEXT create_info; + memset(&create_info, 0, sizeof(VkDebugUtilsMessengerCreateInfoEXT)); + create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT; + create_info.messageSeverity = + VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | + VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; + create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | + VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | + VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; + create_info.pfnUserCallback = vulkan_debug_callback; + + result = create_debug_utils_messenger_ext(demo->instance, &create_info, + NULL, &demo->debug_messenger); + if (result != VK_SUCCESS) { + fprintf(stderr, "create_debug_utils_messenger_ext failed %d\n", result); + return false; + } + return true; +} + bool create_instance(struct vulkan_demo *demo) { uint32_t i; uint32_t available_instance_extension_count; @@ -205,11 +242,15 @@ bool create_instance(struct vulkan_demo *demo) { const char **glfw_extensions; uint32_t enabled_extension_count; const char **enabled_extensions = NULL; + bool validation_layers_installed; - if (!check_validation_layer_support()) { - fprintf(stderr, "Couldn't find validation layer %s\n", + validation_layers_installed = check_validation_layer_support(); + + if (!validation_layers_installed) { + fprintf(stdout, + "Couldn't find validation layer %s. Continuing without " + "validation layers.\n", validation_layer_name); - return ret; } result = vkEnumerateInstanceExtensionProperties( NULL, &available_instance_extension_count, NULL); @@ -239,12 +280,19 @@ bool create_instance(struct vulkan_demo *demo) { glfw_extensions = glfwGetRequiredInstanceExtensions(&glfw_extension_count); - enabled_extension_count = glfw_extension_count + 1; - enabled_extensions = malloc(enabled_extension_count * sizeof(char *)); - memcpy(enabled_extensions, glfw_extensions, - glfw_extension_count * sizeof(char *)); - enabled_extensions[glfw_extension_count] = - VK_EXT_DEBUG_UTILS_EXTENSION_NAME; + enabled_extension_count = glfw_extension_count; + if (validation_layers_installed) { + enabled_extension_count += 1; + enabled_extensions = malloc(enabled_extension_count * sizeof(char *)); + memcpy(enabled_extensions, glfw_extensions, + glfw_extension_count * sizeof(char *)); + enabled_extensions[glfw_extension_count] = + VK_EXT_DEBUG_UTILS_EXTENSION_NAME; + } else { + enabled_extensions = malloc(enabled_extension_count * sizeof(char *)); + memcpy(enabled_extensions, glfw_extensions, + glfw_extension_count * sizeof(char *)); + } printf("Trying to enable the following instance extensions: "); for (i = 0; i < enabled_extension_count; i++) { @@ -283,15 +331,20 @@ bool create_instance(struct vulkan_demo *demo) { create_info.pApplicationInfo = &app_info; create_info.enabledExtensionCount = enabled_extension_count; create_info.ppEnabledExtensionNames = enabled_extensions; - create_info.enabledLayerCount = 1; - create_info.ppEnabledLayerNames = &validation_layer_name; + if (validation_layers_installed) { + create_info.enabledLayerCount = 1; + create_info.ppEnabledLayerNames = &validation_layer_name; + } result = vkCreateInstance(&create_info, NULL, &demo->instance); if (result != VK_SUCCESS) { fprintf(stderr, "vkCreateInstance result %d\n", result); return ret; } - ret = true; - + if (validation_layers_installed) { + ret = create_debug_callback(demo); + } else { + ret = true; + } cleanup: if (available_instance_extensions) { free(available_instance_extensions); @@ -303,43 +356,6 @@ cleanup: return ret; } -VkResult create_debug_utils_messenger_ext( - VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT *pCreateInfo, - const VkAllocationCallbacks *pAllocator, - VkDebugUtilsMessengerEXT *pDebugMessenger) { - PFN_vkCreateDebugUtilsMessengerEXT func = - (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr( - instance, "vkCreateDebugUtilsMessengerEXT"); - if (func != NULL) { - return func(instance, pCreateInfo, pAllocator, pDebugMessenger); - } else { - return VK_ERROR_EXTENSION_NOT_PRESENT; - } -} - -bool create_debug_callback(struct vulkan_demo *demo) { - VkResult result; - - VkDebugUtilsMessengerCreateInfoEXT create_info; - memset(&create_info, 0, sizeof(VkDebugUtilsMessengerCreateInfoEXT)); - create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT; - create_info.messageSeverity = - VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | - VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; - create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | - VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | - VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; - create_info.pfnUserCallback = vulkan_debug_callback; - - result = create_debug_utils_messenger_ext(demo->instance, &create_info, - NULL, &demo->debugMessenger); - if (result != VK_SUCCESS) { - fprintf(stderr, "create_debug_utils_messenger_ext failed %d\n", result); - return false; - } - return true; -} - bool create_surface(struct vulkan_demo *demo) { VkResult result; result = glfwCreateWindowSurface(demo->instance, demo->win, NULL, @@ -1817,9 +1833,6 @@ bool create_vulkan_demo(struct vulkan_demo *demo) { if (!create_instance(demo)) { return false; } - if (!create_debug_callback(demo)) { - return false; - } if (!create_surface(demo)) { return false; } @@ -2014,11 +2027,13 @@ bool cleanup(struct vulkan_demo *demo) { vkDestroyDevice(demo->device, NULL); vkDestroySurfaceKHR(demo->instance, demo->surface, NULL); - result = destroy_debug_utils_messenger_ext(demo->instance, - demo->debugMessenger, NULL); - if (result != VK_SUCCESS) { - fprintf(stderr, "Couldn't destroy debug messenger: %d\n", result); - return false; + if (demo->debug_messenger) { + result = destroy_debug_utils_messenger_ext(demo->instance, + demo->debug_messenger, NULL); + if (result != VK_SUCCESS) { + fprintf(stderr, "Couldn't destroy debug messenger: %d\n", result); + return false; + } } vkDestroyInstance(demo->instance, NULL); if (demo->swap_chain_images) { From a668105390c10d7d906d4ecb44d1a5523a41450b Mon Sep 17 00:00:00 2001 From: David Reid Date: Tue, 14 Nov 2023 15:39:10 +1000 Subject: [PATCH 061/106] Fix button text alignment error. When calculating the width and height of the content rect of a button, only the border of one side is being taken into account. Instead the border width needs to be multiplied by two before subtracting from the bounds. This is being done for padding and rounding, but not border, which is resulting in text being misaligned, most notably when using buttons with thick borders. --- nuklear.h | 4 ++-- src/nuklear_button.c | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/nuklear.h b/nuklear.h index c2edb75..baac97f 100644 --- a/nuklear.h +++ b/nuklear.h @@ -23892,8 +23892,8 @@ nk_do_button(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, /* calculate button content space */ content->x = r.x + style->padding.x + style->border + style->rounding; content->y = r.y + style->padding.y + style->border + style->rounding; - content->w = r.w - (2 * style->padding.x + style->border + style->rounding*2); - content->h = r.h - (2 * style->padding.y + style->border + style->rounding*2); + content->w = r.w - (2 * (style->padding.x + style->border + style->rounding)); + content->h = r.h - (2 * (style->padding.y + style->border + style->rounding)); /* execute button behavior */ bounds.x = r.x - style->touch_padding.x; diff --git a/src/nuklear_button.c b/src/nuklear_button.c index 2636b60..af80f93 100644 --- a/src/nuklear_button.c +++ b/src/nuklear_button.c @@ -127,8 +127,8 @@ nk_do_button(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, /* calculate button content space */ content->x = r.x + style->padding.x + style->border + style->rounding; content->y = r.y + style->padding.y + style->border + style->rounding; - content->w = r.w - (2 * style->padding.x + style->border + style->rounding*2); - content->h = r.h - (2 * style->padding.y + style->border + style->rounding*2); + content->w = r.w - (2 * (style->padding.x + style->border + style->rounding)); + content->h = r.h - (2 * (style->padding.y + style->border + style->rounding)); /* execute button behavior */ bounds.x = r.x - style->touch_padding.x; From 42e4c54954c150577fc8e70a26195b2509f67017 Mon Sep 17 00:00:00 2001 From: David Reid Date: Tue, 14 Nov 2023 18:02:22 +1000 Subject: [PATCH 062/106] Bump patch version in clib.json. --- clib.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clib.json b/clib.json index cf690c7..e83c57b 100644 --- a/clib.json +++ b/clib.json @@ -1,6 +1,6 @@ { "name": "nuklear", - "version": "4.10.6", + "version": "4.10.7", "repo": "Immediate-Mode-UI/Nuklear", "description": "A small ANSI C gui toolkit", "keywords": ["gl", "ui", "toolkit"], From d09ff8935e787dc6afc91b6c889194bdc65b2b81 Mon Sep 17 00:00:00 2001 From: Cameron Cawley Date: Thu, 16 Nov 2023 17:01:56 +0000 Subject: [PATCH 063/106] Update to a newer version of stb_image --- demo/common/filebrowser/stb_image.h | 3354 +++++++++++++++++++-------- 1 file changed, 2416 insertions(+), 938 deletions(-) diff --git a/demo/common/filebrowser/stb_image.h b/demo/common/filebrowser/stb_image.h index 1f4d468..5e807a0 100644 --- a/demo/common/filebrowser/stb_image.h +++ b/demo/common/filebrowser/stb_image.h @@ -1,5 +1,5 @@ -/* stb_image - v2.08 - public domain image loader - http://nothings.org/stb_image.h - no warranty implied; use at your own risk +/* stb_image - v2.28 - public domain image loader - http://nothings.org/stb + no warranty implied; use at your own risk Do this: #define STB_IMAGE_IMPLEMENTATION @@ -21,7 +21,7 @@ avoid problematic images and only need the trivial interface JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib) - PNG 1/2/4/8-bit-per-channel (16 bpc not supported) + PNG 1/2/4/8/16-bit-per-channel TGA (not sure what subset, if a subset) BMP non-1bpp, non-RLE @@ -42,184 +42,86 @@ Full documentation under "DOCUMENTATION" below. - Revision 2.00 release notes: +LICENSE - - Progressive JPEG is now supported. + See end of file for license information. - - PPM and PGM binary formats are now supported, thanks to Ken Miller. +RECENT REVISION HISTORY: - - x86 platforms now make use of SSE2 SIMD instructions for - JPEG decoding, and ARM platforms can use NEON SIMD if requested. - This work was done by Fabian "ryg" Giesen. SSE2 is used by - default, but NEON must be enabled explicitly; see docs. - - With other JPEG optimizations included in this version, we see - 2x speedup on a JPEG on an x86 machine, and a 1.5x speedup - on a JPEG on an ARM machine, relative to previous versions of this - library. The same results will not obtain for all JPGs and for all - x86/ARM machines. (Note that progressive JPEGs are significantly - slower to decode than regular JPEGs.) This doesn't mean that this - is the fastest JPEG decoder in the land; rather, it brings it - closer to parity with standard libraries. If you want the fastest - decode, look elsewhere. (See "Philosophy" section of docs below.) - - See final bullet items below for more info on SIMD. - - - Added STBI_MALLOC, STBI_REALLOC, and STBI_FREE macros for replacing - the memory allocator. Unlike other STBI libraries, these macros don't - support a context parameter, so if you need to pass a context in to - the allocator, you'll have to store it in a global or a thread-local - variable. - - - Split existing STBI_NO_HDR flag into two flags, STBI_NO_HDR and - STBI_NO_LINEAR. - STBI_NO_HDR: suppress implementation of .hdr reader format - STBI_NO_LINEAR: suppress high-dynamic-range light-linear float API - - - You can suppress implementation of any of the decoders to reduce - your code footprint by #defining one or more of the following - symbols before creating the implementation. - - STBI_NO_JPEG - STBI_NO_PNG - STBI_NO_BMP - STBI_NO_PSD - STBI_NO_TGA - STBI_NO_GIF - STBI_NO_HDR - STBI_NO_PIC - STBI_NO_PNM (.ppm and .pgm) - - - You can request *only* certain decoders and suppress all other ones - (this will be more forward-compatible, as addition of new decoders - doesn't require you to disable them explicitly): - - STBI_ONLY_JPEG - STBI_ONLY_PNG - STBI_ONLY_BMP - STBI_ONLY_PSD - STBI_ONLY_TGA - STBI_ONLY_GIF - STBI_ONLY_HDR - STBI_ONLY_PIC - STBI_ONLY_PNM (.ppm and .pgm) - - Note that you can define multiples of these, and you will get all - of them ("only x" and "only y" is interpreted to mean "only x&y"). - - - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still - want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB - - - Compilation of all SIMD code can be suppressed with - #define STBI_NO_SIMD - It should not be necessary to disable SIMD unless you have issues - compiling (e.g. using an x86 compiler which doesn't support SSE - intrinsics or that doesn't support the method used to detect - SSE2 support at run-time), and even those can be reported as - bugs so I can refine the built-in compile-time checking to be - smarter. - - - The old STBI_SIMD system which allowed installing a user-defined - IDCT etc. has been removed. If you need this, don't upgrade. My - assumption is that almost nobody was doing this, and those who - were will find the built-in SIMD more satisfactory anyway. - - - RGB values computed for JPEG images are slightly different from - previous versions of stb_image. (This is due to using less - integer precision in SIMD.) The C code has been adjusted so - that the same RGB values will be computed regardless of whether - SIMD support is available, so your app should always produce - consistent results. But these results are slightly different from - previous versions. (Specifically, about 3% of available YCbCr values - will compute different RGB results from pre-1.49 versions by +-1; - most of the deviating values are one smaller in the G channel.) - - - If you must produce consistent results with previous versions of - stb_image, #define STBI_JPEG_OLD and you will get the same results - you used to; however, you will not get the SIMD speedups for - the YCbCr-to-RGB conversion step (although you should still see - significant JPEG speedup from the other changes). - - Please note that STBI_JPEG_OLD is a temporary feature; it will be - removed in future versions of the library. It is only intended for - near-term back-compatibility use. - - - Latest revision history: - 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA - 2.07 (2015-09-13) partial animated GIF support - limited 16-bit PSD support - minor bugs, code cleanup, and compiler warnings - 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value - 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning - 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit - 2.03 (2015-04-12) additional corruption checking - stbi_set_flip_vertically_on_load - fix NEON support; fix mingw support - 2.02 (2015-01-19) fix incorrect assert, fix warning - 2.01 (2015-01-17) fix various warnings - 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG - 2.00 (2014-12-25) optimize JPEG, including x86 SSE2 & ARM NEON SIMD - progressive JPEG - PGM/PPM support - STBI_MALLOC,STBI_REALLOC,STBI_FREE - STBI_NO_*, STBI_ONLY_* - GIF bugfix - 1.48 (2014-12-14) fix incorrectly-named assert() - 1.47 (2014-12-14) 1/2/4-bit PNG support (both grayscale and paletted) - optimize PNG - fix bug in interlaced PNG with user-specified channel count + 2.28 (2023-01-29) many error fixes, security errors, just tons of stuff + 2.27 (2021-07-11) document stbi_info better, 16-bit PNM support, bug fixes + 2.26 (2020-07-13) many minor fixes + 2.25 (2020-02-02) fix warnings + 2.24 (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically + 2.23 (2019-08-11) fix clang static analysis warning + 2.22 (2019-03-04) gif fixes, fix warnings + 2.21 (2019-02-25) fix typo in comment + 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs + 2.19 (2018-02-11) fix warning + 2.18 (2018-01-30) fix warnings + 2.17 (2018-01-29) bugfix, 1-bit BMP, 16-bitness query, fix warnings + 2.16 (2017-07-23) all functions have 16-bit variants; optimizations; bugfixes + 2.15 (2017-03-18) fix png-1,2,4; all Imagenet JPGs; no runtime SSE detection on GCC + 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs + 2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes + 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes + 2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64 + RGB-format JPEG; remove white matting in PSD; + allocate large structures on the stack; + correct channel count for PNG & BMP + 2.10 (2016-01-22) avoid warning introduced in 2.09 + 2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED See end of file for full revision history. ============================ Contributors ========================= - Image formats Bug fixes & warning fixes - Sean Barrett (jpeg, png, bmp) Marc LeBlanc - Nicolas Schulz (hdr, psd) Christpher Lloyd - Jonathan Dummer (tga) Dave Moore - Jean-Marc Lienher (gif) Won Chun - Tom Seddon (pic) the Horde3D community - Thatcher Ulrich (psd) Janez Zemva - Ken Miller (pgm, ppm) Jonathan Blow - urraka@github (animated gif) Laurent Gomila - Aruelien Pocheville - Ryamond Barbiero - David Woo - Extensions, features Martin Golini - Jetro Lauha (stbi_info) Roy Eltham - Martin "SpartanJ" Golini (stbi_info) Luke Graham - James "moose2000" Brown (iPhone PNG) Thomas Ruf - Ben "Disch" Wenger (io callbacks) John Bartholomew - Omar Cornut (1/2/4-bit PNG) Ken Hamada - Nicolas Guillemot (vertical flip) Cort Stratton - Richard Mitton (16-bit PSD) Blazej Dariusz Roszkowski - Thibault Reuille - Paul Du Bois - Guillaume George - Jerry Jansson - Hayaki Saito - Johan Duparc - Ronny Chevalier - Optimizations & bugfixes Michal Cichon - Fabian "ryg" Giesen Tero Hanninen - Arseny Kapoulkine Sergio Gonzalez - Cass Everitt - Engin Manap - If your name should be here but Martins Mozeiko - isn't, let Sean know. Joseph Thomson - Phil Jordan - Nathan Reed - Michaelangel007@github - Nick Verigakis + Image formats Extensions, features + Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info) + Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info) + Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG) + Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks) + Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG) + Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip) + Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD) + github:urraka (animated gif) Junggon Kim (PNM comments) + Christopher Forseth (animated gif) Daniel Gibson (16-bit TGA) + socks-the-fox (16-bit PNG) + Jeremy Sawicki (handle all ImageNet JPGs) + Optimizations & bugfixes Mikhail Morozov (1-bit BMP) + Fabian "ryg" Giesen Anael Seghezzi (is-16-bit query) + Arseny Kapoulkine Simon Breuss (16-bit PNM) + John-Mark Allen + Carmelo J Fdez-Aguera -LICENSE + Bug & warning fixes + Marc LeBlanc David Woo Guillaume George Martins Mozeiko + Christpher Lloyd Jerry Jansson Joseph Thomson Blazej Dariusz Roszkowski + Phil Jordan Dave Moore Roy Eltham + Hayaki Saito Nathan Reed Won Chun + Luke Graham Johan Duparc Nick Verigakis the Horde3D community + Thomas Ruf Ronny Chevalier github:rlyeh + Janez Zemva John Bartholomew Michal Cichon github:romigrou + Jonathan Blow Ken Hamada Tero Hanninen github:svdijk + Eugene Golushkov Laurent Gomila Cort Stratton github:snagar + Aruelien Pocheville Sergio Gonzalez Thibault Reuille github:Zelex + Cass Everitt Ryamond Barbiero github:grim210 + Paul Du Bois Engin Manap Aldo Culquicondor github:sammyhw + Philipp Wiesemann Dale Weiler Oriol Ferrer Mesia github:phprus + Josh Tobin Neil Bickford Matthew Gregan github:poppolopoppo + Julian Raschke Gregory Mullen Christian Floisand github:darealshinji + Baldur Karlsson Kevin Schmidt JR Smith github:Michaelangel007 + Brad Weinberger Matvey Cherevko github:mosra + Luca Sas Alexander Veselov Zack Middleton [reserved] + Ryan C. Gordon [reserved] [reserved] + DO NOT ADD YOUR NAME HERE -This software is in the public domain. Where that dedication is not -recognized, you are granted a perpetual, irrevocable license to copy, -distribute, and modify this file as you see fit. + Jacko Dirks + To add your name to the credits, pick a random blank space in the middle and fill it. + 80% of merge conflicts on stb PRs are due to people adding their name at the end + of the credits. */ #ifndef STBI_INCLUDE_STB_IMAGE_H @@ -228,10 +130,8 @@ distribute, and modify this file as you see fit. // DOCUMENTATION // // Limitations: -// - no 16-bit-per-channel PNG // - no 12-bit-per-channel JPEG // - no JPEGs with arithmetic coding -// - no 1-bit BMP // - GIF always returns *comp=4 // // Basic usage (see HDR discussion below for HDR usage): @@ -241,13 +141,13 @@ distribute, and modify this file as you see fit. // // ... x = width, y = height, n = # 8-bit components per pixel ... // // ... replace '0' with '1'..'4' to force that many components per pixel // // ... but 'n' will always be the number that it would have been if you said 0 -// stbi_image_free(data) +// stbi_image_free(data); // // Standard parameters: -// int *x -- outputs image width in pixels -// int *y -- outputs image height in pixels -// int *comp -- outputs # of image components in image file -// int req_comp -- if non-zero, # of image components requested in result +// int *x -- outputs image width in pixels +// int *y -- outputs image height in pixels +// int *channels_in_file -- outputs # of image components in image file +// int desired_channels -- if non-zero, # of image components requested in result // // The return value from an image loader is an 'unsigned char *' which points // to the pixel data, or NULL on an allocation failure or if the image is @@ -255,11 +155,12 @@ distribute, and modify this file as you see fit. // with each pixel consisting of N interleaved 8-bit components; the first // pixel pointed to is top-left-most in the image. There is no padding between // image scanlines or between pixels, regardless of format. The number of -// components N is 'req_comp' if req_comp is non-zero, or *comp otherwise. -// If req_comp is non-zero, *comp has the number of components that _would_ -// have been output otherwise. E.g. if you set req_comp to 4, you will always -// get RGBA output, but you can check *comp to see if it's trivially opaque -// because e.g. there were only 3 channels in the source image. +// components N is 'desired_channels' if desired_channels is non-zero, or +// *channels_in_file otherwise. If desired_channels is non-zero, +// *channels_in_file has the number of components that _would_ have been +// output otherwise. E.g. if you set desired_channels to 4, you will always +// get RGBA output, but you can check *channels_in_file to see if it's trivially +// opaque because e.g. there were only 3 channels in the source image. // // An output image with N components has the following components interleaved // in this order in each pixel: @@ -271,14 +172,50 @@ distribute, and modify this file as you see fit. // 4 red, green, blue, alpha // // If image loading fails for any reason, the return value will be NULL, -// and *x, *y, *comp will be unchanged. The function stbi_failure_reason() -// can be queried for an extremely brief, end-user unfriendly explanation -// of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid -// compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly +// and *x, *y, *channels_in_file will be unchanged. The function +// stbi_failure_reason() can be queried for an extremely brief, end-user +// unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS +// to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly // more user-friendly ones. // // Paletted PNG, BMP, GIF, and PIC images are automatically depalettized. // +// To query the width, height and component count of an image without having to +// decode the full file, you can use the stbi_info family of functions: +// +// int x,y,n,ok; +// ok = stbi_info(filename, &x, &y, &n); +// // returns ok=1 and sets x, y, n if image is a supported format, +// // 0 otherwise. +// +// Note that stb_image pervasively uses ints in its public API for sizes, +// including sizes of memory buffers. This is now part of the API and thus +// hard to change without causing breakage. As a result, the various image +// loaders all have certain limits on image size; these differ somewhat +// by format but generally boil down to either just under 2GB or just under +// 1GB. When the decoded image would be larger than this, stb_image decoding +// will fail. +// +// Additionally, stb_image will reject image files that have any of their +// dimensions set to a larger value than the configurable STBI_MAX_DIMENSIONS, +// which defaults to 2**24 = 16777216 pixels. Due to the above memory limit, +// the only way to have an image with such dimensions load correctly +// is for it to have a rather extreme aspect ratio. Either way, the +// assumption here is that such larger images are likely to be malformed +// or malicious. If you do need to load an image with individual dimensions +// larger than that, and it still fits in the overall size limit, you can +// #define STBI_MAX_DIMENSIONS on your own to be something larger. +// +// =========================================================================== +// +// UNICODE: +// +// If compiling for Windows and you wish to use Unicode filenames, compile +// with +// #define STBI_WINDOWS_UTF8 +// and pass utf8-encoded filenames. Call stbi_convert_wchar_to_utf8 to convert +// Windows wchar_t filenames to utf8. +// // =========================================================================== // // Philosophy @@ -291,15 +228,15 @@ distribute, and modify this file as you see fit. // // Sometimes I let "good performance" creep up in priority over "easy to maintain", // and for best performance I may provide less-easy-to-use APIs that give higher -// performance, in addition to the easy to use ones. Nevertheless, it's important +// performance, in addition to the easy-to-use ones. Nevertheless, it's important // to keep in mind that from the standpoint of you, a client of this library, -// all you care about is #1 and #3, and stb libraries do not emphasize #3 above all. +// all you care about is #1 and #3, and stb libraries DO NOT emphasize #3 above all. // // Some secondary priorities arise directly from the first two, some of which -// make more explicit reasons why performance can't be emphasized. +// provide more explicit reasons why performance can't be emphasized. // // - Portable ("ease of use") -// - Small footprint ("easy to maintain") +// - Small source code footprint ("easy to maintain") // - No dependencies ("ease of use") // // =========================================================================== @@ -331,13 +268,6 @@ distribute, and modify this file as you see fit. // (at least this is true for iOS and Android). Therefore, the NEON support is // toggled by a build flag: define STBI_NEON to get NEON loops. // -// The output of the JPEG decoder is slightly different from versions where -// SIMD support was introduced (that is, for versions before 1.49). The -// difference is only +-1 in the 8-bit RGB channels, and only on a small -// fraction of pixels. You can force the pre-1.49 behavior by defining -// STBI_JPEG_OLD, but this will disable some of the SIMD decoding path -// and hence cost some performance. -// // If for some reason you do not want to use any of SIMD code, or if // you have issues compiling it, you can disable it entirely by // defining STBI_NO_SIMD. @@ -346,11 +276,10 @@ distribute, and modify this file as you see fit. // // HDR image support (disable by defining STBI_NO_HDR) // -// stb_image now supports loading HDR images in general, and currently -// the Radiance .HDR file format, although the support is provided -// generically. You can still load any file through the existing interface; -// if you attempt to load an HDR file, it will be automatically remapped to -// LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; +// stb_image supports loading HDR images in general, and currently the Radiance +// .HDR file format specifically. You can still load any file through the existing +// interface; if you attempt to load an HDR file, it will be automatically remapped +// to LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; // both of these constants can be reconfigured through this interface: // // stbi_hdr_to_ldr_gamma(2.2f); @@ -382,18 +311,59 @@ distribute, and modify this file as you see fit. // // iPhone PNG support: // -// By default we convert iphone-formatted PNGs back to RGB, even though -// they are internally encoded differently. You can disable this conversion -// by by calling stbi_convert_iphone_png_to_rgb(0), in which case -// you will always just get the native iphone "format" through (which -// is BGR stored in RGB). +// We optionally support converting iPhone-formatted PNGs (which store +// premultiplied BGRA) back to RGB, even though they're internally encoded +// differently. To enable this conversion, call +// stbi_convert_iphone_png_to_rgb(1). // // Call stbi_set_unpremultiply_on_load(1) as well to force a divide per // pixel to remove any premultiplied alpha *only* if the image file explicitly // says there's premultiplied data (currently only happens in iPhone images, // and only if iPhone convert-to-rgb processing is on). // - +// =========================================================================== +// +// ADDITIONAL CONFIGURATION +// +// - You can suppress implementation of any of the decoders to reduce +// your code footprint by #defining one or more of the following +// symbols before creating the implementation. +// +// STBI_NO_JPEG +// STBI_NO_PNG +// STBI_NO_BMP +// STBI_NO_PSD +// STBI_NO_TGA +// STBI_NO_GIF +// STBI_NO_HDR +// STBI_NO_PIC +// STBI_NO_PNM (.ppm and .pgm) +// +// - You can request *only* certain decoders and suppress all other ones +// (this will be more forward-compatible, as addition of new decoders +// doesn't require you to disable them explicitly): +// +// STBI_ONLY_JPEG +// STBI_ONLY_PNG +// STBI_ONLY_BMP +// STBI_ONLY_PSD +// STBI_ONLY_TGA +// STBI_ONLY_GIF +// STBI_ONLY_HDR +// STBI_ONLY_PIC +// STBI_ONLY_PNM (.ppm and .pgm) +// +// - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still +// want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB +// +// - If you define STBI_MAX_DIMENSIONS, stb_image will reject images greater +// than that size (in either width or height) without further processing. +// This is to let programs in the wild set an upper bound to prevent +// denial-of-service attacks on untrusted data, as one could generate a +// valid image of gigantic dimensions and force stb_image to allocate a +// huge block of memory and spend disproportionate time decoding it. By +// default this is set to (1 << 24), which is 16777216, but that's still +// very big. #ifndef STBI_NO_STDIO #include @@ -403,7 +373,7 @@ distribute, and modify this file as you see fit. enum { - STBI_default = 0, // only used for req_comp + STBI_default = 0, // only used for desired_channels STBI_grey = 1, STBI_grey_alpha = 2, @@ -411,17 +381,21 @@ enum STBI_rgb_alpha = 4 }; +#include typedef unsigned char stbi_uc; +typedef unsigned short stbi_us; #ifdef __cplusplus extern "C" { #endif +#ifndef STBIDEF #ifdef STB_IMAGE_STATIC #define STBIDEF static #else #define STBIDEF extern #endif +#endif ////////////////////////////////////////////////////////////////////////////// // @@ -439,34 +413,64 @@ typedef struct int (*eof) (void *user); // returns nonzero if we are at end of file/data } stbi_io_callbacks; -STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *comp, int req_comp); -STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *comp, int req_comp); -STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *comp, int req_comp); +//////////////////////////////////// +// +// 8-bits-per-channel interface +// + +STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *channels_in_file, int desired_channels); #ifndef STBI_NO_STDIO -STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp); +STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); // for stbi_load_from_file, file pointer is left pointing immediately after image #endif +#ifndef STBI_NO_GIF +STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp); +#endif + +#ifdef STBI_WINDOWS_UTF8 +STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input); +#endif + +//////////////////////////////////// +// +// 16-bits-per-channel interface +// + +STBIDEF stbi_us *stbi_load_16_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); + +#ifndef STBI_NO_STDIO +STBIDEF stbi_us *stbi_load_16 (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); +#endif + +//////////////////////////////////// +// +// float-per-channel interface +// #ifndef STBI_NO_LINEAR - STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *comp, int req_comp); - STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp); - STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp); + STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); #ifndef STBI_NO_STDIO - STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *comp, int req_comp); + STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); #endif #endif #ifndef STBI_NO_HDR STBIDEF void stbi_hdr_to_ldr_gamma(float gamma); STBIDEF void stbi_hdr_to_ldr_scale(float scale); -#endif +#endif // STBI_NO_HDR #ifndef STBI_NO_LINEAR STBIDEF void stbi_ldr_to_hdr_gamma(float gamma); STBIDEF void stbi_ldr_to_hdr_scale(float scale); -#endif // STBI_NO_HDR +#endif // STBI_NO_LINEAR // stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user); @@ -478,7 +482,7 @@ STBIDEF int stbi_is_hdr_from_file(FILE *f); // get a VERY brief reason for failure -// NOT THREADSAFE +// on most compilers (and ALL modern mainstream compilers) this is threadsafe STBIDEF const char *stbi_failure_reason (void); // free the loaded image -- this is just free() @@ -487,11 +491,14 @@ STBIDEF void stbi_image_free (void *retval_from_stbi_load); // get image dimensions & components without fully decoding STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp); +STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len); +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *clbk, void *user); #ifndef STBI_NO_STDIO -STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp); -STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp); - +STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp); +STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp); +STBIDEF int stbi_is_16_bit (char const *filename); +STBIDEF int stbi_is_16_bit_from_file(FILE *f); #endif @@ -508,6 +515,13 @@ STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert); // flip the image vertically, so the first pixel in the output array is the bottom left STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip); +// as above, but only applies to images loaded on the thread that calls the function +// this function is only available if your compiler supports thread-local variables; +// calling it will fail to link if your compiler doesn't +STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply); +STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert); +STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip); + // ZLIB client - used by PNG, available for other purposes STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen); @@ -572,9 +586,10 @@ STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const ch #include // ptrdiff_t on osx #include #include +#include #if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) -#include // ldexp +#include // ldexp, pow #endif #ifndef STBI_NO_STDIO @@ -586,6 +601,12 @@ STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const ch #define STBI_ASSERT(x) assert(x) #endif +#ifdef __cplusplus +#define STBI_EXTERN extern "C" +#else +#define STBI_EXTERN extern +#endif + #ifndef _MSC_VER #ifdef __cplusplus @@ -597,8 +618,25 @@ STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const ch #define stbi_inline __forceinline #endif +#ifndef STBI_NO_THREAD_LOCALS + #if defined(__cplusplus) && __cplusplus >= 201103L + #define STBI_THREAD_LOCAL thread_local + #elif defined(__GNUC__) && __GNUC__ < 5 + #define STBI_THREAD_LOCAL __thread + #elif defined(_MSC_VER) + #define STBI_THREAD_LOCAL __declspec(thread) + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) + #define STBI_THREAD_LOCAL _Thread_local + #endif -#ifdef _MSC_VER + #ifndef STBI_THREAD_LOCAL + #if defined(__GNUC__) + #define STBI_THREAD_LOCAL __thread + #endif + #endif +#endif + +#if defined(_MSC_VER) || defined(__SYMBIAN32__) typedef unsigned short stbi__uint16; typedef signed short stbi__int16; typedef unsigned int stbi__uint32; @@ -627,21 +665,25 @@ typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; #ifdef STBI_HAS_LROTL #define stbi_lrot(x,y) _lrotl(x,y) #else - #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (32 - (y)))) + #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (-(y) & 31))) #endif -#if defined(STBI_MALLOC) && defined(STBI_FREE) && defined(STBI_REALLOC) +#if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED)) // ok -#elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) +#elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED) // ok #else -#error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC." +#error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)." #endif #ifndef STBI_MALLOC -#define STBI_MALLOC(sz) malloc(sz) -#define STBI_REALLOC(p,sz) realloc(p,sz) -#define STBI_FREE(p) free(p) +#define STBI_MALLOC(sz) malloc(sz) +#define STBI_REALLOC(p,newsz) realloc(p,newsz) +#define STBI_FREE(p) free(p) +#endif + +#ifndef STBI_REALLOC_SIZED +#define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz) #endif // x86/x64 detection @@ -651,12 +693,14 @@ typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; #define STBI__X86_TARGET #endif -#if defined(__GNUC__) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) && !defined(__SSE2__) && !defined(STBI_NO_SIMD) -// NOTE: not clear do we actually need this for the 64-bit path? +#if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && !defined(STBI_NO_SIMD) // gcc doesn't support sse2 intrinsics unless you compile with -msse2, -// (but compiling with -msse2 allows the compiler to use SSE2 everywhere; -// this is just broken and gcc are jerks for not fixing it properly -// http://www.virtualdub.org/blog/pivot/entry.php?id=363 ) +// which in turn means it gets to use SSE2 everywhere. This is unfortunate, +// but previous attempts to provide the SSE2 functions with runtime +// detection caused numerous issues. The way architecture extensions are +// exposed in GCC/Clang is, sadly, not really suited for one-file libs. +// New behavior: if compiled with -msse2, we use SSE2 without any +// detection; if not, we don't use it at all. #define STBI_NO_SIMD #endif @@ -675,7 +719,7 @@ typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; #define STBI_NO_SIMD #endif -#if !defined(STBI_NO_SIMD) && defined(STBI__X86_TARGET) +#if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) #define STBI_SSE2 #include @@ -704,25 +748,27 @@ static int stbi__cpuid3(void) #define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name -static int stbi__sse2_available() +#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) +static int stbi__sse2_available(void) { int info3 = stbi__cpuid3(); return ((info3 >> 26) & 1) != 0; } +#endif + #else // assume GCC-style if not VC++ #define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) -static int stbi__sse2_available() +#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) +static int stbi__sse2_available(void) { -#if defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__) >= 408 // GCC 4.8 or later - // GCC 4.8+ has a nice way to do this - return __builtin_cpu_supports("sse2"); -#else - // portable way to do this, preferably without using GCC inline ASM? - // just bail for now. - return 0; -#endif + // If we're even attempting to compile this on GCC/Clang, that means + // -msse2 is on, which means the compiler is allowed to use SSE2 + // instructions at will, and so are we. + return 1; } +#endif + #endif #endif @@ -733,14 +779,21 @@ static int stbi__sse2_available() #ifdef STBI_NEON #include -// assume GCC or Clang on ARM targets +#ifdef _MSC_VER +#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name +#else #define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) #endif +#endif #ifndef STBI_SIMD_ALIGN #define STBI_SIMD_ALIGN(type, name) type name #endif +#ifndef STBI_MAX_DIMENSIONS +#define STBI_MAX_DIMENSIONS (1 << 24) +#endif + /////////////////////////////////////////////// // // stbi__context struct and start_xxx functions @@ -758,6 +811,7 @@ typedef struct int read_from_callbacks; int buflen; stbi_uc buffer_start[128]; + int callback_already_read; stbi_uc *img_buffer, *img_buffer_end; stbi_uc *img_buffer_original, *img_buffer_original_end; @@ -771,6 +825,7 @@ static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len) { s->io.read = NULL; s->read_from_callbacks = 0; + s->callback_already_read = 0; s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer; s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len; } @@ -782,7 +837,8 @@ static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void * s->io_user_data = user; s->buflen = sizeof(s->buffer_start); s->read_from_callbacks = 1; - s->img_buffer_original = s->buffer_start; + s->callback_already_read = 0; + s->img_buffer = s->img_buffer_original = s->buffer_start; stbi__refill_buffer(s); s->img_buffer_original_end = s->img_buffer_end; } @@ -796,12 +852,17 @@ static int stbi__stdio_read(void *user, char *data, int size) static void stbi__stdio_skip(void *user, int n) { + int ch; fseek((FILE*) user, n, SEEK_CUR); + ch = fgetc((FILE*) user); /* have to read a byte to reset feof()'s flag */ + if (ch != EOF) { + ungetc(ch, (FILE *) user); /* push byte back onto stream if valid. */ + } } static int stbi__stdio_eof(void *user) { - return feof((FILE*) user); + return feof((FILE*) user) || ferror((FILE *) user); } static stbi_io_callbacks stbi__stdio_callbacks = @@ -829,79 +890,197 @@ static void stbi__rewind(stbi__context *s) s->img_buffer_end = s->img_buffer_original_end; } +enum +{ + STBI_ORDER_RGB, + STBI_ORDER_BGR +}; + +typedef struct +{ + int bits_per_channel; + int num_channels; + int channel_order; +} stbi__result_info; + #ifndef STBI_NO_JPEG static int stbi__jpeg_test(stbi__context *s); -static stbi_uc *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PNG static int stbi__png_test(stbi__context *s); -static stbi_uc *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__png_is16(stbi__context *s); #endif #ifndef STBI_NO_BMP static int stbi__bmp_test(stbi__context *s); -static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_TGA static int stbi__tga_test(stbi__context *s); -static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PSD static int stbi__psd_test(stbi__context *s); -static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc); static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__psd_is16(stbi__context *s); #endif #ifndef STBI_NO_HDR static int stbi__hdr_test(stbi__context *s); -static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PIC static int stbi__pic_test(stbi__context *s); -static stbi_uc *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static void *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_GIF static int stbi__gif_test(stbi__context *s); -static stbi_uc *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp); static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PNM static int stbi__pnm_test(stbi__context *s); -static stbi_uc *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__pnm_is16(stbi__context *s); #endif -// this is not threadsafe -static const char *stbi__g_failure_reason; +static +#ifdef STBI_THREAD_LOCAL +STBI_THREAD_LOCAL +#endif +const char *stbi__g_failure_reason; STBIDEF const char *stbi_failure_reason(void) { return stbi__g_failure_reason; } +#ifndef STBI_NO_FAILURE_STRINGS static int stbi__err(const char *str) { stbi__g_failure_reason = str; return 0; } +#endif static void *stbi__malloc(size_t size) { return STBI_MALLOC(size); } +// stb_image uses ints pervasively, including for offset calculations. +// therefore the largest decoded image size we can support with the +// current code, even on 64-bit targets, is INT_MAX. this is not a +// significant limitation for the intended use case. +// +// we do, however, need to make sure our size calculations don't +// overflow. hence a few helper functions for size calculations that +// multiply integers together, making sure that they're non-negative +// and no overflow occurs. + +// return 1 if the sum is valid, 0 on overflow. +// negative terms are considered invalid. +static int stbi__addsizes_valid(int a, int b) +{ + if (b < 0) return 0; + // now 0 <= b <= INT_MAX, hence also + // 0 <= INT_MAX - b <= INTMAX. + // And "a + b <= INT_MAX" (which might overflow) is the + // same as a <= INT_MAX - b (no overflow) + return a <= INT_MAX - b; +} + +// returns 1 if the product is valid, 0 on overflow. +// negative factors are considered invalid. +static int stbi__mul2sizes_valid(int a, int b) +{ + if (a < 0 || b < 0) return 0; + if (b == 0) return 1; // mul-by-0 is always safe + // portable way to check for no overflows in a*b + return a <= INT_MAX/b; +} + +#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) +// returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow +static int stbi__mad2sizes_valid(int a, int b, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a*b, add); +} +#endif + +// returns 1 if "a*b*c + add" has no negative terms/factors and doesn't overflow +static int stbi__mad3sizes_valid(int a, int b, int c, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && + stbi__addsizes_valid(a*b*c, add); +} + +// returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) +static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && + stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add); +} +#endif + +#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) +// mallocs with size overflow checking +static void *stbi__malloc_mad2(int a, int b, int add) +{ + if (!stbi__mad2sizes_valid(a, b, add)) return NULL; + return stbi__malloc(a*b + add); +} +#endif + +static void *stbi__malloc_mad3(int a, int b, int c, int add) +{ + if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL; + return stbi__malloc(a*b*c + add); +} + +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) +static void *stbi__malloc_mad4(int a, int b, int c, int d, int add) +{ + if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL; + return stbi__malloc(a*b*c*d + add); +} +#endif + +// returns 1 if the sum of two signed ints is valid (between -2^31 and 2^31-1 inclusive), 0 on overflow. +static int stbi__addints_valid(int a, int b) +{ + if ((a >= 0) != (b >= 0)) return 1; // a and b have different signs, so no overflow + if (a < 0 && b < 0) return a >= INT_MIN - b; // same as a + b >= INT_MIN; INT_MIN - b cannot overflow since b < 0. + return a <= INT_MAX - b; +} + +// returns 1 if the product of two signed shorts is valid, 0 on overflow. +static int stbi__mul2shorts_valid(short a, short b) +{ + if (b == 0 || b == -1) return 1; // multiplication by 0 is always 0; check for -1 so SHRT_MIN/b doesn't overflow + if ((a >= 0) == (b >= 0)) return a <= SHRT_MAX/b; // product is positive, so similar to mul2sizes_valid + if (b < 0) return a <= SHRT_MIN / b; // same as a * b >= SHRT_MIN + return a >= SHRT_MIN / b; +} + // stbi__err - error // stbi__errpf - error returning pointer to float // stbi__errpuc - error returning pointer to unsigned char @@ -930,40 +1109,69 @@ static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp); static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp); #endif -static int stbi__vertically_flip_on_load = 0; +static int stbi__vertically_flip_on_load_global = 0; STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) { - stbi__vertically_flip_on_load = flag_true_if_should_flip; + stbi__vertically_flip_on_load_global = flag_true_if_should_flip; } -static unsigned char *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) +#ifndef STBI_THREAD_LOCAL +#define stbi__vertically_flip_on_load stbi__vertically_flip_on_load_global +#else +static STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local, stbi__vertically_flip_on_load_set; + +STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip) { - #ifndef STBI_NO_JPEG - if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp); - #endif + stbi__vertically_flip_on_load_local = flag_true_if_should_flip; + stbi__vertically_flip_on_load_set = 1; +} + +#define stbi__vertically_flip_on_load (stbi__vertically_flip_on_load_set \ + ? stbi__vertically_flip_on_load_local \ + : stbi__vertically_flip_on_load_global) +#endif // STBI_THREAD_LOCAL + +static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) +{ + memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields + ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed + ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order + ri->num_channels = 0; + + // test the formats with a very explicit header first (at least a FOURCC + // or distinctive magic number first) #ifndef STBI_NO_PNG - if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp); + if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_BMP - if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp); + if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_GIF - if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp); + if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_PSD - if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp); + if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp, ri, bpc); + #else + STBI_NOTUSED(bpc); #endif #ifndef STBI_NO_PIC - if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp); + if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp, ri); + #endif + + // then the formats that can end up attempting to load with just 1 or 2 + // bytes matching expectations; these are prone to false positives, so + // try them later + #ifndef STBI_NO_JPEG + if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_PNM - if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp); + if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_HDR if (stbi__hdr_test(s)) { - float *hdr = stbi__hdr_load(s, x,y,comp,req_comp); + float *hdr = stbi__hdr_load(s, x,y,comp,req_comp, ri); return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); } #endif @@ -971,66 +1179,179 @@ static unsigned char *stbi__load_main(stbi__context *s, int *x, int *y, int *com #ifndef STBI_NO_TGA // test tga last because it's a crappy test! if (stbi__tga_test(s)) - return stbi__tga_load(s,x,y,comp,req_comp); + return stbi__tga_load(s,x,y,comp,req_comp, ri); #endif return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt"); } -static unsigned char *stbi__load_flip(stbi__context *s, int *x, int *y, int *comp, int req_comp) +static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels) { - unsigned char *result = stbi__load_main(s, x, y, comp, req_comp); + int i; + int img_len = w * h * channels; + stbi_uc *reduced; - if (stbi__vertically_flip_on_load && result != NULL) { - int w = *x, h = *y; - int depth = req_comp ? req_comp : *comp; - int row,col,z; - stbi_uc temp; + reduced = (stbi_uc *) stbi__malloc(img_len); + if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory"); - // @OPTIMIZE: use a bigger temp buffer and memcpy multiple pixels at once - for (row = 0; row < (h>>1); row++) { - for (col = 0; col < w; col++) { - for (z = 0; z < depth; z++) { - temp = result[(row * w + col) * depth + z]; - result[(row * w + col) * depth + z] = result[((h - row - 1) * w + col) * depth + z]; - result[((h - row - 1) * w + col) * depth + z] = temp; - } - } - } - } + for (i = 0; i < img_len; ++i) + reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling - return result; + STBI_FREE(orig); + return reduced; } -#ifndef STBI_NO_HDR +static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels) +{ + int i; + int img_len = w * h * channels; + stbi__uint16 *enlarged; + + enlarged = (stbi__uint16 *) stbi__malloc(img_len*2); + if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); + + for (i = 0; i < img_len; ++i) + enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff + + STBI_FREE(orig); + return enlarged; +} + +static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel) +{ + int row; + size_t bytes_per_row = (size_t)w * bytes_per_pixel; + stbi_uc temp[2048]; + stbi_uc *bytes = (stbi_uc *)image; + + for (row = 0; row < (h>>1); row++) { + stbi_uc *row0 = bytes + row*bytes_per_row; + stbi_uc *row1 = bytes + (h - row - 1)*bytes_per_row; + // swap row0 with row1 + size_t bytes_left = bytes_per_row; + while (bytes_left) { + size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp); + memcpy(temp, row0, bytes_copy); + memcpy(row0, row1, bytes_copy); + memcpy(row1, temp, bytes_copy); + row0 += bytes_copy; + row1 += bytes_copy; + bytes_left -= bytes_copy; + } + } +} + +#ifndef STBI_NO_GIF +static void stbi__vertical_flip_slices(void *image, int w, int h, int z, int bytes_per_pixel) +{ + int slice; + int slice_size = w * h * bytes_per_pixel; + + stbi_uc *bytes = (stbi_uc *)image; + for (slice = 0; slice < z; ++slice) { + stbi__vertical_flip(bytes, w, h, bytes_per_pixel); + bytes += slice_size; + } +} +#endif + +static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__result_info ri; + void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8); + + if (result == NULL) + return NULL; + + // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. + STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); + + if (ri.bits_per_channel != 8) { + result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 8; + } + + // @TODO: move stbi__convert_format to here + + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc)); + } + + return (unsigned char *) result; +} + +static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__result_info ri; + void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16); + + if (result == NULL) + return NULL; + + // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. + STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); + + if (ri.bits_per_channel != 16) { + result = stbi__convert_8_to_16((stbi_uc *) result, *x, *y, req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 16; + } + + // @TODO: move stbi__convert_format16 to here + // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision + + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16)); + } + + return (stbi__uint16 *) result; +} + +#if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR) static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp) { if (stbi__vertically_flip_on_load && result != NULL) { - int w = *x, h = *y; - int depth = req_comp ? req_comp : *comp; - int row,col,z; - float temp; - - // @OPTIMIZE: use a bigger temp buffer and memcpy multiple pixels at once - for (row = 0; row < (h>>1); row++) { - for (col = 0; col < w; col++) { - for (z = 0; z < depth; z++) { - temp = result[(row * w + col) * depth + z]; - result[(row * w + col) * depth + z] = result[((h - row - 1) * w + col) * depth + z]; - result[((h - row - 1) * w + col) * depth + z] = temp; - } - } - } + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(float)); } } #endif #ifndef STBI_NO_STDIO +#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) +STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide); +STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default); +#endif + +#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) +STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input) +{ + return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL); +} +#endif + static FILE *stbi__fopen(char const *filename, char const *mode) { FILE *f; +#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) + wchar_t wMode[64]; + wchar_t wFilename[1024]; + if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename))) + return 0; + + if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode))) + return 0; + #if defined(_MSC_VER) && _MSC_VER >= 1400 + if (0 != _wfopen_s(&f, wFilename, wMode)) + f = 0; +#else + f = _wfopen(wFilename, wMode); +#endif + +#elif defined(_MSC_VER) && _MSC_VER >= 1400 if (0 != fopen_s(&f, filename, mode)) f=0; #else @@ -1055,42 +1376,98 @@ STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req unsigned char *result; stbi__context s; stbi__start_file(&s,f); - result = stbi__load_flip(&s,x,y,comp,req_comp); + result = stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); if (result) { // need to 'unget' all the characters in the IO buffer fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); } return result; } + +STBIDEF stbi__uint16 *stbi_load_from_file_16(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + stbi__uint16 *result; + stbi__context s; + stbi__start_file(&s,f); + result = stbi__load_and_postprocess_16bit(&s,x,y,comp,req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; +} + +STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + stbi__uint16 *result; + if (!f) return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file_16(f,x,y,comp,req_comp); + fclose(f); + return result; +} + + #endif //!STBI_NO_STDIO +STBIDEF stbi_us *stbi_load_16_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); +} + +STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user); + return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); +} + STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_mem(&s,buffer,len); - return stbi__load_flip(&s,x,y,comp,req_comp); + return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); } STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); - return stbi__load_flip(&s,x,y,comp,req_comp); + return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); } +#ifndef STBI_NO_GIF +STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp) +{ + unsigned char *result; + stbi__context s; + stbi__start_mem(&s,buffer,len); + + result = (unsigned char*) stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp); + if (stbi__vertically_flip_on_load) { + stbi__vertical_flip_slices( result, *x, *y, *z, *comp ); + } + + return result; +} +#endif + #ifndef STBI_NO_LINEAR static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) { unsigned char *data; #ifndef STBI_NO_HDR if (stbi__hdr_test(s)) { - float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp); + stbi__result_info ri; + float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp, &ri); if (hdr_data) stbi__float_postprocess(hdr_data,x,y,comp,req_comp); return hdr_data; } #endif - data = stbi__load_flip(s, x, y, comp, req_comp); + data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp); if (data) return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); return stbi__errpf("unknown image type", "Image not of any known type, or corrupt"); @@ -1160,12 +1537,16 @@ STBIDEF int stbi_is_hdr (char const *filename) return result; } -STBIDEF int stbi_is_hdr_from_file(FILE *f) +STBIDEF int stbi_is_hdr_from_file(FILE *f) { #ifndef STBI_NO_HDR + long pos = ftell(f); + int res; stbi__context s; stbi__start_file(&s,f); - return stbi__hdr_test(&s); + res = stbi__hdr_test(&s); + fseek(f, pos, SEEK_SET); + return res; #else STBI_NOTUSED(f); return 0; @@ -1186,14 +1567,15 @@ STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void #endif } -static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f; +#ifndef STBI_NO_LINEAR static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f; -#ifndef STBI_NO_LINEAR STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; } STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; } #endif +static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f; + STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; } STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; } @@ -1213,6 +1595,7 @@ enum static void stbi__refill_buffer(stbi__context *s) { int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen); + s->callback_already_read += (int) (s->img_buffer - s->img_buffer_original); if (n == 0) { // at end of file, treat same as if from memory, but need to handle case // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file @@ -1237,6 +1620,9 @@ stbi_inline static stbi_uc stbi__get8(stbi__context *s) return 0; } +#if defined(STBI_NO_JPEG) && defined(STBI_NO_HDR) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else stbi_inline static int stbi__at_eof(stbi__context *s) { if (s->io.read) { @@ -1248,9 +1634,14 @@ stbi_inline static int stbi__at_eof(stbi__context *s) return s->img_buffer >= s->img_buffer_end; } +#endif +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) +// nothing +#else static void stbi__skip(stbi__context *s, int n) { + if (n == 0) return; // already there! if (n < 0) { s->img_buffer = s->img_buffer_end; return; @@ -1265,7 +1656,11 @@ static void stbi__skip(stbi__context *s, int n) } s->img_buffer += n; } +#endif +#if defined(STBI_NO_PNG) && defined(STBI_NO_TGA) && defined(STBI_NO_HDR) && defined(STBI_NO_PNM) +// nothing +#else static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) { if (s->io.read) { @@ -1289,18 +1684,27 @@ static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) } else return 0; } +#endif +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) +// nothing +#else static int stbi__get16be(stbi__context *s) { int z = stbi__get8(s); return (z << 8) + stbi__get8(s); } +#endif +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) +// nothing +#else static stbi__uint32 stbi__get32be(stbi__context *s) { stbi__uint32 z = stbi__get16be(s); return (z << 16) + stbi__get16be(s); } +#endif #if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) // nothing @@ -1316,13 +1720,16 @@ static int stbi__get16le(stbi__context *s) static stbi__uint32 stbi__get32le(stbi__context *s) { stbi__uint32 z = stbi__get16le(s); - return z + (stbi__get16le(s) << 16); + z += (stbi__uint32)stbi__get16le(s) << 16; + return z; } #endif #define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings - +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else ////////////////////////////////////////////////////////////////////////////// // // generic converter from built-in img_n to req_comp @@ -1338,7 +1745,11 @@ static stbi_uc stbi__compute_y(int r, int g, int b) { return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8); } +#endif +#if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y) { int i,j; @@ -1347,7 +1758,7 @@ static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int r if (req_comp == img_n) return data; STBI_ASSERT(req_comp >= 1 && req_comp <= 4); - good = (unsigned char *) stbi__malloc(req_comp * x * y); + good = (unsigned char *) stbi__malloc_mad3(req_comp, x, y, 0); if (good == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); @@ -1357,37 +1768,97 @@ static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int r unsigned char *src = data + j * x * img_n ; unsigned char *dest = good + j * x * req_comp; - #define COMBO(a,b) ((a)*8+(b)) - #define CASE(a,b) case COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + #define STBI__COMBO(a,b) ((a)*8+(b)) + #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) // convert source image with img_n components to one with req_comp components; // avoid switch per pixel, so use switch per scanline and massive macros - switch (COMBO(img_n, req_comp)) { - CASE(1,2) dest[0]=src[0], dest[1]=255; break; - CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break; - CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break; - CASE(2,1) dest[0]=src[0]; break; - CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break; - CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break; - CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break; - CASE(3,1) dest[0]=stbi__compute_y(src[0],src[1],src[2]); break; - CASE(3,2) dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = 255; break; - CASE(4,1) dest[0]=stbi__compute_y(src[0],src[1],src[2]); break; - CASE(4,2) dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break; - CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break; - default: STBI_ASSERT(0); + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=255; } break; + STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=255; } break; + STBI__CASE(2,1) { dest[0]=src[0]; } break; + STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; + STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=255; } break; + STBI__CASE(3,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; + STBI__CASE(3,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = 255; } break; + STBI__CASE(4,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; + STBI__CASE(4,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = src[3]; } break; + STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; + default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return stbi__errpuc("unsupported", "Unsupported format conversion"); } - #undef CASE + #undef STBI__CASE } STBI_FREE(data); return good; } +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) +// nothing +#else +static stbi__uint16 stbi__compute_y_16(int r, int g, int b) +{ + return (stbi__uint16) (((r*77) + (g*150) + (29*b)) >> 8); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) +// nothing +#else +static stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int req_comp, unsigned int x, unsigned int y) +{ + int i,j; + stbi__uint16 *good; + + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + + good = (stbi__uint16 *) stbi__malloc(req_comp * x * y * 2); + if (good == NULL) { + STBI_FREE(data); + return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); + } + + for (j=0; j < (int) y; ++j) { + stbi__uint16 *src = data + j * x * img_n ; + stbi__uint16 *dest = good + j * x * req_comp; + + #define STBI__COMBO(a,b) ((a)*8+(b)) + #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp components; + // avoid switch per pixel, so use switch per scanline and massive macros + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=0xffff; } break; + STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=0xffff; } break; + STBI__CASE(2,1) { dest[0]=src[0]; } break; + STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; + STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=0xffff; } break; + STBI__CASE(3,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; + STBI__CASE(3,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = 0xffff; } break; + STBI__CASE(4,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; + STBI__CASE(4,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = src[3]; } break; + STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; + default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return (stbi__uint16*) stbi__errpuc("unsupported", "Unsupported format conversion"); + } + #undef STBI__CASE + } + + STBI_FREE(data); + return good; +} +#endif #ifndef STBI_NO_LINEAR static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) { int i,k,n; - float *output = (float *) stbi__malloc(x * y * comp * sizeof(float)); + float *output; + if (!data) return NULL; + output = (float *) stbi__malloc_mad4(x, y, comp, sizeof(float), 0); if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); } // compute number of non-alpha components if (comp & 1) n = comp; else n = comp-1; @@ -1395,7 +1866,11 @@ static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) for (k=0; k < n; ++k) { output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale); } - if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f; + } + if (n < comp) { + for (i=0; i < x*y; ++i) { + output[i*comp + n] = data[i*comp + n]/255.0f; + } } STBI_FREE(data); return output; @@ -1407,7 +1882,9 @@ static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp) { int i,k,n; - stbi_uc *output = (stbi_uc *) stbi__malloc(x * y * comp); + stbi_uc *output; + if (!data) return NULL; + output = (stbi_uc *) stbi__malloc_mad3(x, y, comp, 0); if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } // compute number of non-alpha components if (comp & 1) n = comp; else n = comp-1; @@ -1472,7 +1949,7 @@ typedef struct stbi__context *s; stbi__huffman huff_dc[4]; stbi__huffman huff_ac[4]; - stbi_uc dequant[4][64]; + stbi__uint16 dequant[4][64]; stbi__int16 fast_ac[4][1 << FAST_BITS]; // sizes for components, interleaved MCUs @@ -1508,6 +1985,9 @@ typedef struct int succ_high; int succ_low; int eob_run; + int jfif; + int app14_color_transform; // Adobe APP14 tag + int rgb; int scan_n, order[4]; int restart_interval, todo; @@ -1520,11 +2000,15 @@ typedef struct static int stbi__build_huffman(stbi__huffman *h, int *count) { - int i,j,k=0,code; + int i,j,k=0; + unsigned int code; // build size list for each symbol (from JPEG spec) - for (i=0; i < 16; ++i) - for (j=0; j < count[i]; ++j) + for (i=0; i < 16; ++i) { + for (j=0; j < count[i]; ++j) { h->size[k++] = (stbi_uc) (i+1); + if(k >= 257) return stbi__err("bad size list","Corrupt JPEG"); + } + } h->size[k] = 0; // compute actual symbols (from jpeg spec) @@ -1536,7 +2020,7 @@ static int stbi__build_huffman(stbi__huffman *h, int *count) if (h->size[k] == j) { while (h->size[k] == j) h->code[k++] = (stbi__uint16) (code++); - if (code-1 >= (1 << j)) return stbi__err("bad code lengths","Corrupt JPEG"); + if (code-1 >= (1u << j)) return stbi__err("bad code lengths","Corrupt JPEG"); } // compute largest code + 1 for this size, preshifted as needed later h->maxcode[j] = code << (16-j); @@ -1577,10 +2061,10 @@ static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h) // magnitude code followed by receive_extend code int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits); int m = 1 << (magbits - 1); - if (k < m) k += (-1 << magbits) + 1; + if (k < m) k += (~0U << magbits) + 1; // if the result is small enough, we can fit it in fast_ac table if (k >= -128 && k <= 127) - fast_ac[i] = (stbi__int16) ((k << 8) + (run << 4) + (len + magbits)); + fast_ac[i] = (stbi__int16) ((k * 256) + (run * 16) + (len + magbits)); } } } @@ -1589,9 +2073,10 @@ static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h) static void stbi__grow_buffer_unsafe(stbi__jpeg *j) { do { - int b = j->nomore ? 0 : stbi__get8(j->s); + unsigned int b = j->nomore ? 0 : stbi__get8(j->s); if (b == 0xff) { int c = stbi__get8(j->s); + while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes if (c != 0) { j->marker = (unsigned char) c; j->nomore = 1; @@ -1604,7 +2089,7 @@ static void stbi__grow_buffer_unsafe(stbi__jpeg *j) } // (1 << n) - 1 -static stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535}; +static const stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535}; // decode a jpeg huffman value from the bitstream stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) @@ -1648,6 +2133,8 @@ stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) // convert the huffman code to the symbol id c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; + if(c < 0 || c >= 256) // symbol id out of bounds! + return -1; STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]); // convert the id to a symbol @@ -1657,7 +2144,7 @@ stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) } // bias[n] = (-1<code_bits < n) stbi__grow_buffer_unsafe(j); + if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing - sgn = (stbi__int32)j->code_buffer >> 31; // sign bit is always in MSB + sgn = j->code_buffer >> 31; // sign bit always in MSB; 0 if MSB clear (positive), 1 if MSB set (negative) k = stbi_lrot(j->code_buffer, n); - STBI_ASSERT(n >= 0 && n < (int) (sizeof(stbi__bmask)/sizeof(*stbi__bmask))); j->code_buffer = k & ~stbi__bmask[n]; k &= stbi__bmask[n]; j->code_bits -= n; - return k + (stbi__jbias[n] & ~sgn); + return k + (stbi__jbias[n] & (sgn - 1)); } // get some unsigned bits @@ -1681,6 +2168,7 @@ stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n) { unsigned int k; if (j->code_bits < n) stbi__grow_buffer_unsafe(j); + if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing k = stbi_lrot(j->code_buffer, n); j->code_buffer = k & ~stbi__bmask[n]; k &= stbi__bmask[n]; @@ -1692,6 +2180,7 @@ stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j) { unsigned int k; if (j->code_bits < 1) stbi__grow_buffer_unsafe(j); + if (j->code_bits < 1) return 0; // ran out of bits from stream, return 0s intead of continuing k = j->code_buffer; j->code_buffer <<= 1; --j->code_bits; @@ -1700,7 +2189,7 @@ stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j) // given a value that's at position X in the zigzag stream, // where does it appear in the 8x8 matrix coded as row-major? -static stbi_uc stbi__jpeg_dezigzag[64+15] = +static const stbi_uc stbi__jpeg_dezigzag[64+15] = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, @@ -1716,21 +2205,23 @@ static stbi_uc stbi__jpeg_dezigzag[64+15] = }; // decode one 64-entry block-- -static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi_uc *dequant) +static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi__uint16 *dequant) { int diff,dc,k; int t; if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); t = stbi__jpeg_huff_decode(j, hdc); - if (t < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + if (t < 0 || t > 15) return stbi__err("bad huffman code","Corrupt JPEG"); // 0 all the ac values now so we can do it 32-bits at a time memset(data,0,64*sizeof(data[0])); diff = t ? stbi__extend_receive(j, t) : 0; + if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta","Corrupt JPEG"); dc = j->img_comp[b].dc_pred + diff; j->img_comp[b].dc_pred = dc; + if (!stbi__mul2shorts_valid(dc, dequant[0])) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); data[0] = (short) (dc * dequant[0]); // decode AC components, see JPEG spec @@ -1744,6 +2235,7 @@ static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman if (r) { // fast-AC path k += (r >> 4) & 15; // run s = r & 15; // combined length + if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available"); j->code_buffer <<= s; j->code_bits -= s; // decode into unzigzag'd location @@ -1780,11 +2272,14 @@ static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__ // first scan for DC coefficient, must be first memset(data,0,64*sizeof(data[0])); // 0 all the ac values now t = stbi__jpeg_huff_decode(j, hdc); + if (t < 0 || t > 15) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); diff = t ? stbi__extend_receive(j, t) : 0; + if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta", "Corrupt JPEG"); dc = j->img_comp[b].dc_pred + diff; j->img_comp[b].dc_pred = dc; - data[0] = (short) (dc << j->succ_low); + if (!stbi__mul2shorts_valid(dc, 1 << j->succ_low)) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + data[0] = (short) (dc * (1 << j->succ_low)); } else { // refinement scan for DC coefficient if (stbi__jpeg_get_bit(j)) @@ -1818,10 +2313,11 @@ static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__ if (r) { // fast-AC path k += (r >> 4) & 15; // run s = r & 15; // combined length + if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available"); j->code_buffer <<= s; j->code_bits -= s; zig = stbi__jpeg_dezigzag[k++]; - data[zig] = (short) ((r >> 8) << shift); + data[zig] = (short) ((r >> 8) * (1 << shift)); } else { int rs = stbi__jpeg_huff_decode(j, hac); if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); @@ -1839,7 +2335,7 @@ static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__ } else { k += r; zig = stbi__jpeg_dezigzag[k++]; - data[zig] = (short) (stbi__extend_receive(j,s) << shift); + data[zig] = (short) (stbi__extend_receive(j,s) * (1 << shift)); } } } while (k <= j->spec_end); @@ -1926,7 +2422,7 @@ stbi_inline static stbi_uc stbi__clamp(int x) } #define stbi__f2f(x) ((int) (((x) * 4096 + 0.5))) -#define stbi__fsh(x) ((x) << 12) +#define stbi__fsh(x) ((x) * 4096) // derived from jidctint -- DCT_ISLOW #define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \ @@ -1981,7 +2477,7 @@ static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64]) // (1|2|3|4|5|6|7)==0 0 seconds // all separate -0.047 seconds // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds - int dcterm = d[0] << 2; + int dcterm = d[0]*4; v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; } else { STBI__IDCT_1D(d[ 0],d[ 8],d[16],d[24],d[32],d[40],d[48],d[56]) @@ -2425,7 +2921,7 @@ static stbi_uc stbi__get_marker(stbi__jpeg *j) x = stbi__get8(j->s); if (x != 0xff) return STBI__MARKER_none; while (x == 0xff) - x = stbi__get8(j->s); + x = stbi__get8(j->s); // consume repeated 0xff fill bytes return x; } @@ -2440,7 +2936,7 @@ static void stbi__jpeg_reset(stbi__jpeg *j) j->code_bits = 0; j->code_buffer = 0; j->nomore = 0; - j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0; + j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = j->img_comp[3].dc_pred = 0; j->marker = STBI__MARKER_none; j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; j->eob_run = 0; @@ -2572,7 +3068,7 @@ static int stbi__parse_entropy_coded_data(stbi__jpeg *z) } } -static void stbi__jpeg_dequantize(short *data, stbi_uc *dequant) +static void stbi__jpeg_dequantize(short *data, stbi__uint16 *dequant) { int i; for (i=0; i < 64; ++i) @@ -2614,13 +3110,14 @@ static int stbi__process_marker(stbi__jpeg *z, int m) L = stbi__get16be(z->s)-2; while (L > 0) { int q = stbi__get8(z->s); - int p = q >> 4; + int p = q >> 4, sixteen = (p != 0); int t = q & 15,i; - if (p != 0) return stbi__err("bad DQT type","Corrupt JPEG"); + if (p != 0 && p != 1) return stbi__err("bad DQT type","Corrupt JPEG"); if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG"); + for (i=0; i < 64; ++i) - z->dequant[t][stbi__jpeg_dezigzag[i]] = stbi__get8(z->s); - L -= 65; + z->dequant[t][stbi__jpeg_dezigzag[i]] = (stbi__uint16)(sixteen ? stbi__get16be(z->s) : stbi__get8(z->s)); + L -= (sixteen ? 129 : 65); } return L==0; @@ -2637,6 +3134,7 @@ static int stbi__process_marker(stbi__jpeg *z, int m) sizes[i] = stbi__get8(z->s); n += sizes[i]; } + if(n > 256) return stbi__err("bad DHT header","Corrupt JPEG"); // Loop over i < n would write past end of values! L -= 17; if (tc == 0) { if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0; @@ -2653,12 +3151,50 @@ static int stbi__process_marker(stbi__jpeg *z, int m) } return L==0; } + // check for comment block or APP blocks if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { - stbi__skip(z->s, stbi__get16be(z->s)-2); + L = stbi__get16be(z->s); + if (L < 2) { + if (m == 0xFE) + return stbi__err("bad COM len","Corrupt JPEG"); + else + return stbi__err("bad APP len","Corrupt JPEG"); + } + L -= 2; + + if (m == 0xE0 && L >= 5) { // JFIF APP0 segment + static const unsigned char tag[5] = {'J','F','I','F','\0'}; + int ok = 1; + int i; + for (i=0; i < 5; ++i) + if (stbi__get8(z->s) != tag[i]) + ok = 0; + L -= 5; + if (ok) + z->jfif = 1; + } else if (m == 0xEE && L >= 12) { // Adobe APP14 segment + static const unsigned char tag[6] = {'A','d','o','b','e','\0'}; + int ok = 1; + int i; + for (i=0; i < 6; ++i) + if (stbi__get8(z->s) != tag[i]) + ok = 0; + L -= 6; + if (ok) { + stbi__get8(z->s); // version + stbi__get16be(z->s); // flags0 + stbi__get16be(z->s); // flags1 + z->app14_color_transform = stbi__get8(z->s); // color transform + L -= 6; + } + } + + stbi__skip(z->s, L); return 1; } - return 0; + + return stbi__err("unknown marker","Corrupt JPEG"); } // after we see SOS @@ -2701,6 +3237,28 @@ static int stbi__process_scan_header(stbi__jpeg *z) return 1; } +static int stbi__free_jpeg_components(stbi__jpeg *z, int ncomp, int why) +{ + int i; + for (i=0; i < ncomp; ++i) { + if (z->img_comp[i].raw_data) { + STBI_FREE(z->img_comp[i].raw_data); + z->img_comp[i].raw_data = NULL; + z->img_comp[i].data = NULL; + } + if (z->img_comp[i].raw_coeff) { + STBI_FREE(z->img_comp[i].raw_coeff); + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].coeff = 0; + } + if (z->img_comp[i].linebuf) { + STBI_FREE(z->img_comp[i].linebuf); + z->img_comp[i].linebuf = NULL; + } + } + return why; +} + static int stbi__process_frame_header(stbi__jpeg *z, int scan) { stbi__context *s = z->s; @@ -2709,8 +3267,10 @@ static int stbi__process_frame_header(stbi__jpeg *z, int scan) p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); c = stbi__get8(s); - if (c != 3 && c != 1) return stbi__err("bad component count","Corrupt JPEG"); // JFIF requires + if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count","Corrupt JPEG"); s->img_n = c; for (i=0; i < c; ++i) { z->img_comp[i].data = NULL; @@ -2719,11 +3279,12 @@ static int stbi__process_frame_header(stbi__jpeg *z, int scan) if (Lf != 8+3*s->img_n) return stbi__err("bad SOF len","Corrupt JPEG"); + z->rgb = 0; for (i=0; i < s->img_n; ++i) { + static const unsigned char rgb[3] = { 'R', 'G', 'B' }; z->img_comp[i].id = stbi__get8(s); - if (z->img_comp[i].id != i+1) // JFIF requires - if (z->img_comp[i].id != i) // some version of jpegtran outputs non-JFIF-compliant files! - return stbi__err("bad component ID","Corrupt JPEG"); + if (s->img_n == 3 && z->img_comp[i].id == rgb[i]) + ++z->rgb; q = stbi__get8(s); z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG"); z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG"); @@ -2732,18 +3293,26 @@ static int stbi__process_frame_header(stbi__jpeg *z, int scan) if (scan != STBI__SCAN_load) return 1; - if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); + if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err("too large", "Image too large to decode"); for (i=0; i < s->img_n; ++i) { if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; } + // check that plane subsampling factors are integer ratios; our resamplers can't deal with fractional ratios + // and I've never seen a non-corrupted JPEG file actually use them + for (i=0; i < s->img_n; ++i) { + if (h_max % z->img_comp[i].h != 0) return stbi__err("bad H","Corrupt JPEG"); + if (v_max % z->img_comp[i].v != 0) return stbi__err("bad V","Corrupt JPEG"); + } + // compute interleaved mcu info z->img_h_max = h_max; z->img_v_max = v_max; z->img_mcu_w = h_max * 8; z->img_mcu_h = v_max * 8; + // these sizes can't be more than 17 bits z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w; z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h; @@ -2755,28 +3324,27 @@ static int stbi__process_frame_header(stbi__jpeg *z, int scan) // the bogus oversized data from using interleaved MCUs and their // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't // discard the extra data until colorspace conversion + // + // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier) + // so these muls can't overflow with 32-bit ints (which we require) z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; - z->img_comp[i].raw_data = stbi__malloc(z->img_comp[i].w2 * z->img_comp[i].h2+15); - - if (z->img_comp[i].raw_data == NULL) { - for(--i; i >= 0; --i) { - STBI_FREE(z->img_comp[i].raw_data); - z->img_comp[i].raw_data = NULL; - } - return stbi__err("outofmem", "Out of memory"); - } + z->img_comp[i].coeff = 0; + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].linebuf = NULL; + z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15); + if (z->img_comp[i].raw_data == NULL) + return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); // align blocks for idct using mmx/sse z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15); - z->img_comp[i].linebuf = NULL; if (z->progressive) { - z->img_comp[i].coeff_w = (z->img_comp[i].w2 + 7) >> 3; - z->img_comp[i].coeff_h = (z->img_comp[i].h2 + 7) >> 3; - z->img_comp[i].raw_coeff = STBI_MALLOC(z->img_comp[i].coeff_w * z->img_comp[i].coeff_h * 64 * sizeof(short) + 15); + // w2, h2 are multiples of 8 (see above) + z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8; + z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8; + z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15); + if (z->img_comp[i].raw_coeff == NULL) + return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15); - } else { - z->img_comp[i].coeff = 0; - z->img_comp[i].raw_coeff = 0; } } @@ -2795,6 +3363,8 @@ static int stbi__process_frame_header(stbi__jpeg *z, int scan) static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan) { int m; + z->jfif = 0; + z->app14_color_transform = -1; // valid values are 0,1,2 z->marker = STBI__MARKER_none; // initialize cached marker to empty m = stbi__get_marker(z); if (!stbi__SOI(m)) return stbi__err("no SOI","Corrupt JPEG"); @@ -2814,6 +3384,28 @@ static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan) return 1; } +static int stbi__skip_jpeg_junk_at_end(stbi__jpeg *j) +{ + // some JPEGs have junk at end, skip over it but if we find what looks + // like a valid marker, resume there + while (!stbi__at_eof(j->s)) { + int x = stbi__get8(j->s); + while (x == 255) { // might be a marker + if (stbi__at_eof(j->s)) return STBI__MARKER_none; + x = stbi__get8(j->s); + if (x != 0x00 && x != 0xff) { + // not a stuffed zero or lead-in to another marker, looks + // like an actual marker, return it + return x; + } + // stuffed zero has x=0 now which ends the loop, meaning we go + // back to regular scan loop. + // repeated 0xff keeps trying to read the next byte of the marker. + } + } + return STBI__MARKER_none; +} + // decode image to YCbCr format static int stbi__decode_jpeg_image(stbi__jpeg *j) { @@ -2830,22 +3422,22 @@ static int stbi__decode_jpeg_image(stbi__jpeg *j) if (!stbi__process_scan_header(j)) return 0; if (!stbi__parse_entropy_coded_data(j)) return 0; if (j->marker == STBI__MARKER_none ) { - // handle 0s at the end of image data from IP Kamera 9060 - while (!stbi__at_eof(j->s)) { - int x = stbi__get8(j->s); - if (x == 255) { - j->marker = stbi__get8(j->s); - break; - } else if (x != 0) { - return stbi__err("junk before marker", "Corrupt JPEG"); - } - } + j->marker = stbi__skip_jpeg_junk_at_end(j); // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0 } + m = stbi__get_marker(j); + if (STBI__RESTART(m)) + m = stbi__get_marker(j); + } else if (stbi__DNL(m)) { + int Ld = stbi__get16be(j->s); + stbi__uint32 NL = stbi__get16be(j->s); + if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG"); + if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG"); + m = stbi__get_marker(j); } else { - if (!stbi__process_marker(j, m)) return 0; + if (!stbi__process_marker(j, m)) return 1; + m = stbi__get_marker(j); } - m = stbi__get_marker(j); } if (j->progressive) stbi__jpeg_finish(j); @@ -3060,38 +3652,9 @@ static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_ return out; } -#ifdef STBI_JPEG_OLD -// this is the same YCbCr-to-RGB calculation that stb_image has used -// historically before the algorithm changes in 1.49 -#define float2fixed(x) ((int) ((x) * 65536 + 0.5)) -static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) -{ - int i; - for (i=0; i < count; ++i) { - int y_fixed = (y[i] << 16) + 32768; // rounding - int r,g,b; - int cr = pcr[i] - 128; - int cb = pcb[i] - 128; - r = y_fixed + cr*float2fixed(1.40200f); - g = y_fixed - cr*float2fixed(0.71414f) - cb*float2fixed(0.34414f); - b = y_fixed + cb*float2fixed(1.77200f); - r >>= 16; - g >>= 16; - b >>= 16; - if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } - if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } - if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } - out[0] = (stbi_uc)r; - out[1] = (stbi_uc)g; - out[2] = (stbi_uc)b; - out[3] = 255; - out += step; - } -} -#else // this is a reduced-precision calculation of YCbCr-to-RGB introduced // to make sure the code produces the same results in both SIMD and scalar -#define float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) +#define stbi__float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) { int i; @@ -3100,9 +3663,9 @@ static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc int r,g,b; int cr = pcr[i] - 128; int cb = pcb[i] - 128; - r = y_fixed + cr* float2fixed(1.40200f); - g = y_fixed + (cr*-float2fixed(0.71414f)) + ((cb*-float2fixed(0.34414f)) & 0xffff0000); - b = y_fixed + cb* float2fixed(1.77200f); + r = y_fixed + cr* stbi__float2fixed(1.40200f); + g = y_fixed + (cr*-stbi__float2fixed(0.71414f)) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb* stbi__float2fixed(1.77200f); r >>= 20; g >>= 20; b >>= 20; @@ -3116,7 +3679,6 @@ static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc out += step; } } -#endif #if defined(STBI_SSE2) || defined(STBI_NEON) static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step) @@ -3235,9 +3797,9 @@ static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc cons int r,g,b; int cr = pcr[i] - 128; int cb = pcb[i] - 128; - r = y_fixed + cr* float2fixed(1.40200f); - g = y_fixed + cr*-float2fixed(0.71414f) + ((cb*-float2fixed(0.34414f)) & 0xffff0000); - b = y_fixed + cb* float2fixed(1.77200f); + r = y_fixed + cr* stbi__float2fixed(1.40200f); + g = y_fixed + cr*-stbi__float2fixed(0.71414f) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb* stbi__float2fixed(1.77200f); r >>= 20; g >>= 20; b >>= 20; @@ -3263,18 +3825,14 @@ static void stbi__setup_jpeg(stbi__jpeg *j) #ifdef STBI_SSE2 if (stbi__sse2_available()) { j->idct_block_kernel = stbi__idct_simd; - #ifndef STBI_JPEG_OLD j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; - #endif j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; } #endif #ifdef STBI_NEON j->idct_block_kernel = stbi__idct_simd; - #ifndef STBI_JPEG_OLD j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; - #endif j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; #endif } @@ -3282,23 +3840,7 @@ static void stbi__setup_jpeg(stbi__jpeg *j) // clean up the temporary component buffers static void stbi__cleanup_jpeg(stbi__jpeg *j) { - int i; - for (i=0; i < j->s->img_n; ++i) { - if (j->img_comp[i].raw_data) { - STBI_FREE(j->img_comp[i].raw_data); - j->img_comp[i].raw_data = NULL; - j->img_comp[i].data = NULL; - } - if (j->img_comp[i].raw_coeff) { - STBI_FREE(j->img_comp[i].raw_coeff); - j->img_comp[i].raw_coeff = 0; - j->img_comp[i].coeff = 0; - } - if (j->img_comp[i].linebuf) { - STBI_FREE(j->img_comp[i].linebuf); - j->img_comp[i].linebuf = NULL; - } - } + stbi__free_jpeg_components(j, j->s->img_n, 0); } typedef struct @@ -3311,9 +3853,16 @@ typedef struct int ypos; // which pre-expansion row we're on } stbi__resample; +// fast 0..255 * 0..255 => 0..255 rounded multiplication +static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y) +{ + unsigned int t = x*y + 128; + return (stbi_uc) ((t + (t >>8)) >> 8); +} + static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp) { - int n, decode_n; + int n, decode_n, is_rgb; z->s->img_n = 0; // make stbi__cleanup_jpeg safe // validate req_comp @@ -3323,19 +3872,25 @@ static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; } // determine actual number of components to generate - n = req_comp ? req_comp : z->s->img_n; + n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1; - if (z->s->img_n == 3 && n < 3) + is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif)); + + if (z->s->img_n == 3 && n < 3 && !is_rgb) decode_n = 1; else decode_n = z->s->img_n; + // nothing to do if no components requested; check this now to avoid + // accessing uninitialized coutput[0] later + if (decode_n <= 0) { stbi__cleanup_jpeg(z); return NULL; } + // resample and color-convert { int k; unsigned int i,j; stbi_uc *output; - stbi_uc *coutput[4]; + stbi_uc *coutput[4] = { NULL, NULL, NULL, NULL }; stbi__resample res_comp[4]; @@ -3362,7 +3917,7 @@ static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp } // can't error after this so, this is safe - output = (stbi_uc *) stbi__malloc(n * z->s->img_x * z->s->img_y + 1); + output = (stbi_uc *) stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1); if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } // now go ahead and resample @@ -3385,7 +3940,39 @@ static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp if (n >= 3) { stbi_uc *y = coutput[0]; if (z->s->img_n == 3) { - z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + if (is_rgb) { + for (i=0; i < z->s->img_x; ++i) { + out[0] = y[i]; + out[1] = coutput[1][i]; + out[2] = coutput[2][i]; + out[3] = 255; + out += n; + } + } else { + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } + } else if (z->s->img_n == 4) { + if (z->app14_color_transform == 0) { // CMYK + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(coutput[0][i], m); + out[1] = stbi__blinn_8x8(coutput[1][i], m); + out[2] = stbi__blinn_8x8(coutput[2][i], m); + out[3] = 255; + out += n; + } + } else if (z->app14_color_transform == 2) { // YCCK + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(255 - out[0], m); + out[1] = stbi__blinn_8x8(255 - out[1], m); + out[2] = stbi__blinn_8x8(255 - out[2], m); + out += n; + } + } else { // YCbCr + alpha? Ignore the fourth channel for now + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } } else for (i=0; i < z->s->img_x; ++i) { out[0] = out[1] = out[2] = y[i]; @@ -3393,37 +3980,74 @@ static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp out += n; } } else { - stbi_uc *y = coutput[0]; - if (n == 1) - for (i=0; i < z->s->img_x; ++i) out[i] = y[i]; - else - for (i=0; i < z->s->img_x; ++i) *out++ = y[i], *out++ = 255; + if (is_rgb) { + if (n == 1) + for (i=0; i < z->s->img_x; ++i) + *out++ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); + else { + for (i=0; i < z->s->img_x; ++i, out += 2) { + out[0] = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); + out[1] = 255; + } + } + } else if (z->s->img_n == 4 && z->app14_color_transform == 0) { + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + stbi_uc r = stbi__blinn_8x8(coutput[0][i], m); + stbi_uc g = stbi__blinn_8x8(coutput[1][i], m); + stbi_uc b = stbi__blinn_8x8(coutput[2][i], m); + out[0] = stbi__compute_y(r, g, b); + out[1] = 255; + out += n; + } + } else if (z->s->img_n == 4 && z->app14_color_transform == 2) { + for (i=0; i < z->s->img_x; ++i) { + out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]); + out[1] = 255; + out += n; + } + } else { + stbi_uc *y = coutput[0]; + if (n == 1) + for (i=0; i < z->s->img_x; ++i) out[i] = y[i]; + else + for (i=0; i < z->s->img_x; ++i) { *out++ = y[i]; *out++ = 255; } + } } } stbi__cleanup_jpeg(z); *out_x = z->s->img_x; *out_y = z->s->img_y; - if (comp) *comp = z->s->img_n; // report original components, not output + if (comp) *comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output return output; } } -static unsigned char *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { - stbi__jpeg j; - j.s = s; - stbi__setup_jpeg(&j); - return load_jpeg_image(&j, x,y,comp,req_comp); + unsigned char* result; + stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg)); + if (!j) return stbi__errpuc("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + STBI_NOTUSED(ri); + j->s = s; + stbi__setup_jpeg(j); + result = load_jpeg_image(j, x,y,comp,req_comp); + STBI_FREE(j); + return result; } static int stbi__jpeg_test(stbi__context *s) { int r; - stbi__jpeg j; - j.s = s; - stbi__setup_jpeg(&j); - r = stbi__decode_jpeg_header(&j, STBI__SCAN_type); + stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg)); + if (!j) return stbi__err("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + j->s = s; + stbi__setup_jpeg(j); + r = stbi__decode_jpeg_header(j, STBI__SCAN_type); stbi__rewind(s); + STBI_FREE(j); return r; } @@ -3435,15 +4059,20 @@ static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp) } if (x) *x = j->s->img_x; if (y) *y = j->s->img_y; - if (comp) *comp = j->s->img_n; + if (comp) *comp = j->s->img_n >= 3 ? 3 : 1; return 1; } static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) { - stbi__jpeg j; - j.s = s; - return stbi__jpeg_info_raw(&j, x, y, comp); + int result; + stbi__jpeg* j = (stbi__jpeg*) (stbi__malloc(sizeof(stbi__jpeg))); + if (!j) return stbi__err("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + j->s = s; + result = stbi__jpeg_info_raw(j, x, y, comp); + STBI_FREE(j); + return result; } #endif @@ -3459,6 +4088,7 @@ static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) // fast-way is faster to check than jpeg huffman, but slow way is slower #define STBI__ZFAST_BITS 9 // accelerate all cases in default tables #define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1) +#define STBI__ZNSYMS 288 // number of symbols in literal/length alphabet // zlib-style huffman encoding // (jpegs packs from left, zlib from right, so can't share code) @@ -3468,8 +4098,8 @@ typedef struct stbi__uint16 firstcode[16]; int maxcode[17]; stbi__uint16 firstsymbol[16]; - stbi_uc size[288]; - stbi__uint16 value[288]; + stbi_uc size[STBI__ZNSYMS]; + stbi__uint16 value[STBI__ZNSYMS]; } stbi__zhuffman; stbi_inline static int stbi__bitreverse16(int n) @@ -3489,7 +4119,7 @@ stbi_inline static int stbi__bit_reverse(int v, int bits) return stbi__bitreverse16(v) >> (16-bits); } -static int stbi__zbuild_huffman(stbi__zhuffman *z, stbi_uc *sizelist, int num) +static int stbi__zbuild_huffman(stbi__zhuffman *z, const stbi_uc *sizelist, int num) { int i,k=0; int code, next_code[16], sizes[17]; @@ -3556,16 +4186,23 @@ typedef struct stbi__zhuffman z_length, z_distance; } stbi__zbuf; +stbi_inline static int stbi__zeof(stbi__zbuf *z) +{ + return (z->zbuffer >= z->zbuffer_end); +} + stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z) { - if (z->zbuffer >= z->zbuffer_end) return 0; - return *z->zbuffer++; + return stbi__zeof(z) ? 0 : *z->zbuffer++; } static void stbi__fill_bits(stbi__zbuf *z) { do { - STBI_ASSERT(z->code_buffer < (1U << z->num_bits)); + if (z->code_buffer >= (1U << z->num_bits)) { + z->zbuffer = z->zbuffer_end; /* treat this as EOF so we fail. */ + return; + } z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits; z->num_bits += 8; } while (z->num_bits <= 24); @@ -3590,10 +4227,11 @@ static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z) for (s=STBI__ZFAST_BITS+1; ; ++s) if (k < z->maxcode[s]) break; - if (s == 16) return -1; // invalid code! + if (s >= 16) return -1; // invalid code! // code size is s, so: b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s]; - STBI_ASSERT(z->size[b] == s); + if (b >= STBI__ZNSYMS) return -1; // some data was corrupt somewhere! + if (z->size[b] != s) return -1; // was originally an assert, but report failure instead. a->code_buffer >>= s; a->num_bits -= s; return z->value[b]; @@ -3602,7 +4240,12 @@ static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z) stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z) { int b,s; - if (a->num_bits < 16) stbi__fill_bits(a); + if (a->num_bits < 16) { + if (stbi__zeof(a)) { + return -1; /* report error for unexpected end of data. */ + } + stbi__fill_bits(a); + } b = z->fast[a->code_buffer & STBI__ZFAST_MASK]; if (b) { s = b >> 9; @@ -3616,14 +4259,18 @@ stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z) static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes { char *q; - int cur, limit; + unsigned int cur, limit, old_limit; z->zout = zout; if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG"); - cur = (int) (z->zout - z->zout_start); - limit = (int) (z->zout_end - z->zout_start); - while (cur + n > limit) + cur = (unsigned int) (z->zout - z->zout_start); + limit = old_limit = (unsigned) (z->zout_end - z->zout_start); + if (UINT_MAX - cur < (unsigned) n) return stbi__err("outofmem", "Out of memory"); + while (cur + n > limit) { + if(limit > UINT_MAX / 2) return stbi__err("outofmem", "Out of memory"); limit *= 2; - q = (char *) STBI_REALLOC(z->zout_start, limit); + } + q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit); + STBI_NOTUSED(old_limit); if (q == NULL) return stbi__err("outofmem", "Out of memory"); z->zout_start = q; z->zout = q + cur; @@ -3631,18 +4278,18 @@ static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room return 1; } -static int stbi__zlength_base[31] = { +static const int stbi__zlength_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 }; -static int stbi__zlength_extra[31]= +static const int stbi__zlength_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; -static int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, +static const int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; -static int stbi__zdist_extra[32] = +static const int stbi__zdist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; static int stbi__parse_huffman_block(stbi__zbuf *a) @@ -3664,11 +4311,12 @@ static int stbi__parse_huffman_block(stbi__zbuf *a) a->zout = zout; return 1; } + if (z >= 286) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, length codes 286 and 287 must not appear in compressed data z -= 257; len = stbi__zlength_base[z]; if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]); z = stbi__zhuffman_decode(a, &a->z_distance); - if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); + if (z < 0 || z >= 30) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, distance codes 30 and 31 must not appear in compressed data dist = stbi__zdist_base[z]; if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]); if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG"); @@ -3689,7 +4337,7 @@ static int stbi__parse_huffman_block(stbi__zbuf *a) static int stbi__compute_huffman_codes(stbi__zbuf *a) { - static stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; + static const stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; stbi__zhuffman z_codelength; stbi_uc lencodes[286+32+137];//padding for maximum single op stbi_uc codelength_sizes[19]; @@ -3698,6 +4346,7 @@ static int stbi__compute_huffman_codes(stbi__zbuf *a) int hlit = stbi__zreceive(a,5) + 257; int hdist = stbi__zreceive(a,5) + 1; int hclen = stbi__zreceive(a,4) + 4; + int ntot = hlit + hdist; memset(codelength_sizes, 0, sizeof(codelength_sizes)); for (i=0; i < hclen; ++i) { @@ -3707,33 +4356,36 @@ static int stbi__compute_huffman_codes(stbi__zbuf *a) if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; n = 0; - while (n < hlit + hdist) { + while (n < ntot) { int c = stbi__zhuffman_decode(a, &z_codelength); if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG"); if (c < 16) lencodes[n++] = (stbi_uc) c; - else if (c == 16) { - c = stbi__zreceive(a,2)+3; - memset(lencodes+n, lencodes[n-1], c); - n += c; - } else if (c == 17) { - c = stbi__zreceive(a,3)+3; - memset(lencodes+n, 0, c); - n += c; - } else { - STBI_ASSERT(c == 18); - c = stbi__zreceive(a,7)+11; - memset(lencodes+n, 0, c); + else { + stbi_uc fill = 0; + if (c == 16) { + c = stbi__zreceive(a,2)+3; + if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG"); + fill = lencodes[n-1]; + } else if (c == 17) { + c = stbi__zreceive(a,3)+3; + } else if (c == 18) { + c = stbi__zreceive(a,7)+11; + } else { + return stbi__err("bad codelengths", "Corrupt PNG"); + } + if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG"); + memset(lencodes+n, fill, c); n += c; } } - if (n != hlit+hdist) return stbi__err("bad codelengths","Corrupt PNG"); + if (n != ntot) return stbi__err("bad codelengths","Corrupt PNG"); if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0; return 1; } -static int stbi__parse_uncomperssed_block(stbi__zbuf *a) +static int stbi__parse_uncompressed_block(stbi__zbuf *a) { stbi_uc header[4]; int len,nlen,k; @@ -3746,7 +4398,7 @@ static int stbi__parse_uncomperssed_block(stbi__zbuf *a) a->code_buffer >>= 8; a->num_bits -= 8; } - STBI_ASSERT(a->num_bits == 0); + if (a->num_bits < 0) return stbi__err("zlib corrupt","Corrupt PNG"); // now fill header the normal way while (k < 4) header[k++] = stbi__zget8(a); @@ -3768,6 +4420,7 @@ static int stbi__parse_zlib_header(stbi__zbuf *a) int cm = cmf & 15; /* int cinfo = cmf >> 4; */ int flg = stbi__zget8(a); + if (stbi__zeof(a)) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png @@ -3775,9 +4428,24 @@ static int stbi__parse_zlib_header(stbi__zbuf *a) return 1; } -// @TODO: should statically initialize these for optimal thread safety -static stbi_uc stbi__zdefault_length[288], stbi__zdefault_distance[32]; -static void stbi__init_zdefaults(void) +static const stbi_uc stbi__zdefault_length[STBI__ZNSYMS] = +{ + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8 +}; +static const stbi_uc stbi__zdefault_distance[32] = +{ + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5 +}; +/* +Init algorithm: { int i; // use <= to match clearly with spec for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8; @@ -3787,6 +4455,7 @@ static void stbi__init_zdefaults(void) for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5; } +*/ static int stbi__parse_zlib(stbi__zbuf *a, int parse_header) { @@ -3799,14 +4468,13 @@ static int stbi__parse_zlib(stbi__zbuf *a, int parse_header) final = stbi__zreceive(a,1); type = stbi__zreceive(a,2); if (type == 0) { - if (!stbi__parse_uncomperssed_block(a)) return 0; + if (!stbi__parse_uncompressed_block(a)) return 0; } else if (type == 3) { return 0; } else { if (type == 1) { // use fixed code lengths - if (!stbi__zdefault_distance[31]) stbi__init_zdefaults(); - if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , 288)) return 0; + if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , STBI__ZNSYMS)) return 0; if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0; } else { if (!stbi__compute_huffman_codes(a)) return 0; @@ -3930,7 +4598,7 @@ static stbi__pngchunk stbi__get_chunk_header(stbi__context *s) static int stbi__check_png_header(stbi__context *s) { - static stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 }; + static const stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 }; int i; for (i=0; i < 8; ++i) if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG"); @@ -3941,6 +4609,7 @@ typedef struct { stbi__context *s; stbi_uc *idata, *expanded, *out; + int depth; } stbi__png; @@ -3975,44 +4644,50 @@ static int stbi__paeth(int a, int b, int c) return c; } -static stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 }; +static const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 }; // create the png data from post-deflated data static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color) { + int bytes = (depth == 16? 2 : 1); stbi__context *s = a->s; - stbi__uint32 i,j,stride = x*out_n; + stbi__uint32 i,j,stride = x*out_n*bytes; stbi__uint32 img_len, img_width_bytes; int k; int img_n = s->img_n; // copy it into a local for later + int output_bytes = out_n*bytes; + int filter_bytes = img_n*bytes; + int width = x; + STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1); - a->out = (stbi_uc *) stbi__malloc(x * y * out_n); // extra bytes to write off the end into + a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into if (!a->out) return stbi__err("outofmem", "Out of memory"); + if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) return stbi__err("too large", "Corrupt PNG"); img_width_bytes = (((img_n * x * depth) + 7) >> 3); img_len = (img_width_bytes + 1) * y; - if (s->img_x == x && s->img_y == y) { - if (raw_len != img_len) return stbi__err("not enough pixels","Corrupt PNG"); - } else { // interlaced: - if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG"); - } + + // we used to check for exact match between raw_len and img_len on non-interlaced PNGs, + // but issue #276 reported a PNG in the wild that had extra data at the end (all zeros), + // so just check for raw_len < img_len always. + if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG"); for (j=0; j < y; ++j) { stbi_uc *cur = a->out + stride*j; - stbi_uc *prior = cur - stride; + stbi_uc *prior; int filter = *raw++; - int filter_bytes = img_n; - int width = x; + if (filter > 4) return stbi__err("invalid filter","Corrupt PNG"); if (depth < 8) { - STBI_ASSERT(img_width_bytes <= x); + if (img_width_bytes > x) return stbi__err("invalid width","Corrupt PNG"); cur += x*out_n - img_width_bytes; // store output to the rightmost img_len bytes, so we can decode in place filter_bytes = 1; width = img_width_bytes; } + prior = cur - stride; // bugfix: need to compute this after 'cur +=' computation above // if first row, use special filter that doesn't sample previous row if (j == 0) filter = first_row_filter[filter]; @@ -4036,6 +4711,14 @@ static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 r raw += img_n; cur += out_n; prior += out_n; + } else if (depth == 16) { + if (img_n != out_n) { + cur[filter_bytes] = 255; // first pixel top byte + cur[filter_bytes+1] = 255; // first pixel bottom byte + } + raw += filter_bytes; + cur += output_bytes; + prior += output_bytes; } else { raw += 1; cur += 1; @@ -4044,50 +4727,59 @@ static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 r // this is a little gross, so that we don't switch per-pixel or per-component if (depth < 8 || img_n == out_n) { - int nk = (width - 1)*img_n; - #define CASE(f) \ + int nk = (width - 1)*filter_bytes; + #define STBI__CASE(f) \ case f: \ for (k=0; k < nk; ++k) switch (filter) { // "none" filter turns into a memcpy here; make that explicit. case STBI__F_none: memcpy(cur, raw, nk); break; - CASE(STBI__F_sub) cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); break; - CASE(STBI__F_up) cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break; - CASE(STBI__F_avg) cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); break; - CASE(STBI__F_paeth) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],prior[k],prior[k-filter_bytes])); break; - CASE(STBI__F_avg_first) cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); break; - CASE(STBI__F_paeth_first) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],0,0)); break; + STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); } break; + STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; + STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); } break; + STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],prior[k],prior[k-filter_bytes])); } break; + STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); } break; + STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],0,0)); } break; } - #undef CASE + #undef STBI__CASE raw += nk; } else { STBI_ASSERT(img_n+1 == out_n); - #define CASE(f) \ + #define STBI__CASE(f) \ case f: \ - for (i=x-1; i >= 1; --i, cur[img_n]=255,raw+=img_n,cur+=out_n,prior+=out_n) \ - for (k=0; k < img_n; ++k) + for (i=x-1; i >= 1; --i, cur[filter_bytes]=255,raw+=filter_bytes,cur+=output_bytes,prior+=output_bytes) \ + for (k=0; k < filter_bytes; ++k) switch (filter) { - CASE(STBI__F_none) cur[k] = raw[k]; break; - CASE(STBI__F_sub) cur[k] = STBI__BYTECAST(raw[k] + cur[k-out_n]); break; - CASE(STBI__F_up) cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break; - CASE(STBI__F_avg) cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-out_n])>>1)); break; - CASE(STBI__F_paeth) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-out_n],prior[k],prior[k-out_n])); break; - CASE(STBI__F_avg_first) cur[k] = STBI__BYTECAST(raw[k] + (cur[k-out_n] >> 1)); break; - CASE(STBI__F_paeth_first) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-out_n],0,0)); break; + STBI__CASE(STBI__F_none) { cur[k] = raw[k]; } break; + STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k- output_bytes]); } break; + STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; + STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k- output_bytes])>>1)); } break; + STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],prior[k],prior[k- output_bytes])); } break; + STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k- output_bytes] >> 1)); } break; + STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],0,0)); } break; + } + #undef STBI__CASE + + // the loop above sets the high byte of the pixels' alpha, but for + // 16 bit png files we also need the low byte set. we'll do that here. + if (depth == 16) { + cur = a->out + stride*j; // start at the beginning of the row again + for (i=0; i < x; ++i,cur+=output_bytes) { + cur[filter_bytes+1] = 255; + } } - #undef CASE } } // we make a separate pass to expand bits to pixels; for performance, // this could run two scanlines behind the above code, so it won't - // interfere with filtering but will still be in the cache. + // intefere with filtering but will still be in the cache. if (depth < 8) { for (j=0; j < y; ++j) { stbi_uc *cur = a->out + stride*j; stbi_uc *in = a->out + stride*j + x*out_n - img_width_bytes; // unpack 1/2/4-bit into a 8-bit buffer. allows us to keep the common 8-bit path optimal at minimal cost for 1/2/4-bit - // png guarantee byte alignment, if width is not multiple of 8/4/2 we'll decode dummy trailing data that will be skipped in the later loop + // png guarante byte alignment, if width is not multiple of 8/4/2 we'll decode dummy trailing data that will be skipped in the later loop stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range // note that the final byte might overshoot and write more data than desired. @@ -4151,6 +4843,17 @@ static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 r } } } + } else if (depth == 16) { + // force the image data from big-endian to platform-native. + // this is done in a separate pass due to the decoding relying + // on the data being untouched, but could probably be done + // per-line during decode if care is taken. + stbi_uc *cur = a->out; + stbi__uint16 *cur16 = (stbi__uint16*)cur; + + for(i=0; i < x*y*out_n; ++i,cur16++,cur+=2) { + *cur16 = (cur[0] << 8) | cur[1]; + } } return 1; @@ -4158,13 +4861,16 @@ static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 r static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced) { + int bytes = (depth == 16 ? 2 : 1); + int out_bytes = out_n * bytes; stbi_uc *final; int p; if (!interlaced) return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color); // de-interlacing - final = (stbi_uc *) stbi__malloc(a->s->img_x * a->s->img_y * out_n); + final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0); + if (!final) return stbi__err("outofmem", "Out of memory"); for (p=0; p < 7; ++p) { int xorig[] = { 0,4,0,2,0,1,0 }; int yorig[] = { 0,0,4,0,2,0,1 }; @@ -4184,8 +4890,8 @@ static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint3 for (i=0; i < x; ++i) { int out_y = j*yspc[p]+yorig[p]; int out_x = i*xspc[p]+xorig[p]; - memcpy(final + out_y*a->s->img_x*out_n + out_x*out_n, - a->out + (j*x+i)*out_n, out_n); + memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes, + a->out + (j*x+i)*out_bytes, out_bytes); } } STBI_FREE(a->out); @@ -4223,15 +4929,40 @@ static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n) return 1; } +static int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi__uint16 *p = (stbi__uint16*) z->out; + + // compute color-based transparency, assuming we've + // already got 65535 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); + + if (out_n == 2) { + for (i = 0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 65535); + p += 2; + } + } else { + for (i = 0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) + p[3] = 0; + p += 4; + } + } + return 1; +} + static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n) { stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y; stbi_uc *p, *temp_out, *orig = a->out; - p = (stbi_uc *) stbi__malloc(pixel_count * pal_img_n); + p = (stbi_uc *) stbi__malloc_mad2(pixel_count, pal_img_n, 0); if (p == NULL) return stbi__err("outofmem", "Out of memory"); - // between here and free(out) below, exiting would leak + // between here and free(out) below, exitting would leak temp_out = p; if (pal_img_n == 3) { @@ -4260,19 +4991,46 @@ static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int return 1; } -static int stbi__unpremultiply_on_load = 0; -static int stbi__de_iphone_flag = 0; +static int stbi__unpremultiply_on_load_global = 0; +static int stbi__de_iphone_flag_global = 0; STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) { - stbi__unpremultiply_on_load = flag_true_if_should_unpremultiply; + stbi__unpremultiply_on_load_global = flag_true_if_should_unpremultiply; } STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) { - stbi__de_iphone_flag = flag_true_if_should_convert; + stbi__de_iphone_flag_global = flag_true_if_should_convert; } +#ifndef STBI_THREAD_LOCAL +#define stbi__unpremultiply_on_load stbi__unpremultiply_on_load_global +#define stbi__de_iphone_flag stbi__de_iphone_flag_global +#else +static STBI_THREAD_LOCAL int stbi__unpremultiply_on_load_local, stbi__unpremultiply_on_load_set; +static STBI_THREAD_LOCAL int stbi__de_iphone_flag_local, stbi__de_iphone_flag_set; + +STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply) +{ + stbi__unpremultiply_on_load_local = flag_true_if_should_unpremultiply; + stbi__unpremultiply_on_load_set = 1; +} + +STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert) +{ + stbi__de_iphone_flag_local = flag_true_if_should_convert; + stbi__de_iphone_flag_set = 1; +} + +#define stbi__unpremultiply_on_load (stbi__unpremultiply_on_load_set \ + ? stbi__unpremultiply_on_load_local \ + : stbi__unpremultiply_on_load_global) +#define stbi__de_iphone_flag (stbi__de_iphone_flag_set \ + ? stbi__de_iphone_flag_local \ + : stbi__de_iphone_flag_global) +#endif // STBI_THREAD_LOCAL + static void stbi__de_iphone(stbi__png *z) { stbi__context *s = z->s; @@ -4294,9 +5052,10 @@ static void stbi__de_iphone(stbi__png *z) stbi_uc a = p[3]; stbi_uc t = p[0]; if (a) { - p[0] = p[2] * 255 / a; - p[1] = p[1] * 255 / a; - p[2] = t * 255 / a; + stbi_uc half = a / 2; + p[0] = (p[2] * 255 + half) / a; + p[1] = (p[1] * 255 + half) / a; + p[2] = ( t * 255 + half) / a; } else { p[0] = p[2]; p[2] = t; @@ -4315,14 +5074,15 @@ static void stbi__de_iphone(stbi__png *z) } } -#define STBI__PNG_TYPE(a,b,c,d) (((a) << 24) + ((b) << 16) + ((c) << 8) + (d)) +#define STBI__PNG_TYPE(a,b,c,d) (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d)) static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) { stbi_uc palette[1024], pal_img_n=0; - stbi_uc has_trans=0, tc[3]; + stbi_uc has_trans=0, tc[3]={0}; + stbi__uint16 tc16[3]; stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0; - int first=1,k,interlace=0, color=0, depth=0, is_iphone=0; + int first=1,k,interlace=0, color=0, is_iphone=0; stbi__context *s = z->s; z->expanded = NULL; @@ -4345,10 +5105,13 @@ static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) if (!first) return stbi__err("multiple IHDR","Corrupt PNG"); first = 0; if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG"); - s->img_x = stbi__get32be(s); if (s->img_x > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)"); - s->img_y = stbi__get32be(s); if (s->img_y > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)"); - depth = stbi__get8(s); if (depth != 1 && depth != 2 && depth != 4 && depth != 8) return stbi__err("1/2/4/8-bit only","PNG not supported: 1/2/4/8-bit only"); + s->img_x = stbi__get32be(s); + s->img_y = stbi__get32be(s); + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) return stbi__err("1/2/4/8/16-bit only","PNG not supported: 1/2/4/8/16-bit only"); color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG"); + if (color == 3 && z->depth == 16) return stbi__err("bad ctype","Corrupt PNG"); if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG"); comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG"); filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG"); @@ -4357,14 +5120,13 @@ static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) if (!pal_img_n) { s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); - if (scan == STBI__SCAN_header) return 1; } else { // if paletted, then pal_n is our final components, and // img_n is # components to decompress/filter. s->img_n = 1; if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG"); - // if SCAN_header, have to scan to see if we have a tRNS } + // even with SCAN_header, have to scan to see if we have a tRNS break; } @@ -4396,8 +5158,13 @@ static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG"); if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG"); has_trans = 1; - for (k=0; k < s->img_n; ++k) - tc[k] = (stbi_uc) (stbi__get16be(s) & 255) * stbi__depth_scale_table[depth]; // non 8-bit images will be larger + // non-paletted with tRNS = constant alpha. if header-scanning, we can stop now. + if (scan == STBI__SCAN_header) { ++s->img_n; return 1; } + if (z->depth == 16) { + for (k = 0; k < s->img_n; ++k) tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is + } else { + for (k = 0; k < s->img_n; ++k) tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger + } } break; } @@ -4405,14 +5172,22 @@ static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) case STBI__PNG_TYPE('I','D','A','T'): { if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG"); - if (scan == STBI__SCAN_header) { s->img_n = pal_img_n; return 1; } + if (scan == STBI__SCAN_header) { + // header scan definitely stops at first IDAT + if (pal_img_n) + s->img_n = pal_img_n; + return 1; + } + if (c.length > (1u << 30)) return stbi__err("IDAT size limit", "IDAT section larger than 2^30 bytes"); if ((int)(ioff + c.length) < (int)ioff) return 0; if (ioff + c.length > idata_limit) { + stbi__uint32 idata_limit_old = idata_limit; stbi_uc *p; if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; while (ioff + c.length > idata_limit) idata_limit *= 2; - p = (stbi_uc *) STBI_REALLOC(z->idata, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory"); + STBI_NOTUSED(idata_limit_old); + p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory"); z->idata = p; } if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG"); @@ -4426,7 +5201,7 @@ static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) if (scan != STBI__SCAN_load) return 1; if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG"); // initial guess for decoded data size to avoid unnecessary reallocs - bpl = (s->img_x * depth + 7) / 8; // bytes per line, per component + bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */; z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone); if (z->expanded == NULL) return 0; // zlib should set error @@ -4435,9 +5210,14 @@ static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) s->img_out_n = s->img_n+1; else s->img_out_n = s->img_n; - if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, depth, color, interlace)) return 0; - if (has_trans) - if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; + if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0; + if (has_trans) { + if (z->depth == 16) { + if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0; + } else { + if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; + } + } if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) stbi__de_iphone(z); if (pal_img_n) { @@ -4447,8 +5227,13 @@ static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) if (req_comp >= 3) s->img_out_n = req_comp; if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n)) return 0; + } else if (has_trans) { + // non-paletted image with tRNS -> source image has (constant) alpha + ++s->img_n; } STBI_FREE(z->expanded); z->expanded = NULL; + // end of PNG chunk, read and skip CRC + stbi__get32be(s); return 1; } @@ -4474,21 +5259,30 @@ static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) } } -static unsigned char *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp) +static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, stbi__result_info *ri) { - unsigned char *result=NULL; + void *result=NULL; if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) { + if (p->depth <= 8) + ri->bits_per_channel = 8; + else if (p->depth == 16) + ri->bits_per_channel = 16; + else + return stbi__errpuc("bad bits_per_channel", "PNG not supported: unsupported color depth"); result = p->out; p->out = NULL; if (req_comp && req_comp != p->s->img_out_n) { - result = stbi__convert_format(result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + if (ri->bits_per_channel == 8) + result = stbi__convert_format((unsigned char *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + else + result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); p->s->img_out_n = req_comp; if (result == NULL) return result; } *x = p->s->img_x; *y = p->s->img_y; - if (n) *n = p->s->img_out_n; + if (n) *n = p->s->img_n; } STBI_FREE(p->out); p->out = NULL; STBI_FREE(p->expanded); p->expanded = NULL; @@ -4497,11 +5291,11 @@ static unsigned char *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req return result; } -static unsigned char *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { stbi__png p; p.s = s; - return stbi__do_png(&p, x,y,comp,req_comp); + return stbi__do_png(&p, x,y,comp,req_comp, ri); } static int stbi__png_test(stbi__context *s) @@ -4530,6 +5324,19 @@ static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp) p.s = s; return stbi__png_info_raw(&p, x, y, comp); } + +static int stbi__png_is16(stbi__context *s) +{ + stbi__png p; + p.s = s; + if (!stbi__png_info_raw(&p, NULL, NULL, NULL)) + return 0; + if (p.depth != 16) { + stbi__rewind(p.s); + return 0; + } + return 1; +} #endif // Microsoft/Windows BMP image @@ -4563,11 +5370,11 @@ static int stbi__high_bit(unsigned int z) { int n=0; if (z == 0) return -1; - if (z >= 0x10000) n += 16, z >>= 16; - if (z >= 0x00100) n += 8, z >>= 8; - if (z >= 0x00010) n += 4, z >>= 4; - if (z >= 0x00004) n += 2, z >>= 2; - if (z >= 0x00002) n += 1, z >>= 1; + if (z >= 0x10000) { n += 16; z >>= 16; } + if (z >= 0x00100) { n += 8; z >>= 8; } + if (z >= 0x00010) { n += 4; z >>= 4; } + if (z >= 0x00004) { n += 2; z >>= 2; } + if (z >= 0x00002) { n += 1;/* >>= 1;*/ } return n; } @@ -4581,36 +5388,76 @@ static int stbi__bitcount(unsigned int a) return a & 0xff; } -static int stbi__shiftsigned(int v, int shift, int bits) +// extract an arbitrarily-aligned N-bit value (N=bits) +// from v, and then make it 8-bits long and fractionally +// extend it to full full range. +static int stbi__shiftsigned(unsigned int v, int shift, int bits) { - int result; - int z=0; - - if (shift < 0) v <<= -shift; - else v >>= shift; - result = v; - - z = bits; - while (z < 8) { - result += v >> z; - z += bits; - } - return result; + static unsigned int mul_table[9] = { + 0, + 0xff/*0b11111111*/, 0x55/*0b01010101*/, 0x49/*0b01001001*/, 0x11/*0b00010001*/, + 0x21/*0b00100001*/, 0x41/*0b01000001*/, 0x81/*0b10000001*/, 0x01/*0b00000001*/, + }; + static unsigned int shift_table[9] = { + 0, 0,0,1,0,2,4,6,0, + }; + if (shift < 0) + v <<= -shift; + else + v >>= shift; + STBI_ASSERT(v < 256); + v >>= (8-bits); + STBI_ASSERT(bits >= 0 && bits <= 8); + return (int) ((unsigned) v * mul_table[bits]) >> shift_table[bits]; } -static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +typedef struct { - stbi_uc *out; - unsigned int mr=0,mg=0,mb=0,ma=0, all_a=255; - stbi_uc pal[256][4]; - int psize=0,i,j,compress=0,width; - int bpp, flip_vertically, pad, target, offset, hsz; + int bpp, offset, hsz; + unsigned int mr,mg,mb,ma, all_a; + int extra_read; +} stbi__bmp_data; + +static int stbi__bmp_set_mask_defaults(stbi__bmp_data *info, int compress) +{ + // BI_BITFIELDS specifies masks explicitly, don't override + if (compress == 3) + return 1; + + if (compress == 0) { + if (info->bpp == 16) { + info->mr = 31u << 10; + info->mg = 31u << 5; + info->mb = 31u << 0; + } else if (info->bpp == 32) { + info->mr = 0xffu << 16; + info->mg = 0xffu << 8; + info->mb = 0xffu << 0; + info->ma = 0xffu << 24; + info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0 + } else { + // otherwise, use defaults, which is all-0 + info->mr = info->mg = info->mb = info->ma = 0; + } + return 1; + } + return 0; // error +} + +static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info) +{ + int hsz; if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP"); stbi__get32le(s); // discard filesize stbi__get16le(s); // discard reserved stbi__get16le(s); // discard reserved - offset = stbi__get32le(s); - hsz = stbi__get32le(s); + info->offset = stbi__get32le(s); + info->hsz = hsz = stbi__get32le(s); + info->mr = info->mg = info->mb = info->ma = 0; + info->extra_read = 14; + + if (info->offset < 0) return stbi__errpuc("bad BMP", "bad BMP"); + if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown"); if (hsz == 12) { s->img_x = stbi__get16le(s); @@ -4620,16 +5467,12 @@ static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int s->img_y = stbi__get32le(s); } if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP"); - bpp = stbi__get16le(s); - if (bpp == 1) return stbi__errpuc("monochrome", "BMP type not supported: 1-bit"); - flip_vertically = ((int) s->img_y) > 0; - s->img_y = abs((int) s->img_y); - if (hsz == 12) { - if (bpp < 24) - psize = (offset - 14 - 24) / 3; - } else { - compress = stbi__get32le(s); + info->bpp = stbi__get16le(s); + if (hsz != 12) { + int compress = stbi__get32le(s); if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); + if (compress >= 4) return stbi__errpuc("BMP JPEG/PNG", "BMP type not supported: unsupported compression"); // this includes PNG/JPEG modes + if (compress == 3 && info->bpp != 16 && info->bpp != 32) return stbi__errpuc("bad BMP", "bad BMP"); // bitfields requires 16 or 32 bits/pixel stbi__get32le(s); // discard sizeof stbi__get32le(s); // discard hres stbi__get32le(s); // discard vres @@ -4642,26 +5485,16 @@ static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int stbi__get32le(s); stbi__get32le(s); } - if (bpp == 16 || bpp == 32) { - mr = mg = mb = 0; + if (info->bpp == 16 || info->bpp == 32) { if (compress == 0) { - if (bpp == 32) { - mr = 0xffu << 16; - mg = 0xffu << 8; - mb = 0xffu << 0; - ma = 0xffu << 24; - all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0 - } else { - mr = 31u << 10; - mg = 31u << 5; - mb = 31u << 0; - } + stbi__bmp_set_mask_defaults(info, compress); } else if (compress == 3) { - mr = stbi__get32le(s); - mg = stbi__get32le(s); - mb = stbi__get32le(s); + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->extra_read += 12; // not documented, but generated by photoshop and handled by mspaint - if (mr == mg && mg == mb) { + if (info->mr == info->mg && info->mg == info->mb) { // ?!?!? return stbi__errpuc("bad BMP", "bad BMP"); } @@ -4669,11 +5502,16 @@ static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int return stbi__errpuc("bad BMP", "bad BMP"); } } else { - STBI_ASSERT(hsz == 108 || hsz == 124); - mr = stbi__get32le(s); - mg = stbi__get32le(s); - mb = stbi__get32le(s); - ma = stbi__get32le(s); + // V4/V5 header + int i; + if (hsz != 108 && hsz != 124) + return stbi__errpuc("bad BMP", "bad BMP"); + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->ma = stbi__get32le(s); + if (compress != 3) // override mr/mg/mb unless in BI_BITFIELDS mode, as per docs + stbi__bmp_set_mask_defaults(info, compress); stbi__get32le(s); // discard color space for (i=0; i < 12; ++i) stbi__get32le(s); // discard color space parameters @@ -4684,63 +5522,146 @@ static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int stbi__get32le(s); // discard reserved } } - if (bpp < 16) - psize = (offset - 14 - hsz) >> 2; } - s->img_n = ma ? 4 : 3; + return (void *) 1; +} + + +static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *out; + unsigned int mr=0,mg=0,mb=0,ma=0, all_a; + stbi_uc pal[256][4]; + int psize=0,i,j,width; + int flip_vertically, pad, target; + stbi__bmp_data info; + STBI_NOTUSED(ri); + + info.all_a = 255; + if (stbi__bmp_parse_header(s, &info) == NULL) + return NULL; // error code already set + + flip_vertically = ((int) s->img_y) > 0; + s->img_y = abs((int) s->img_y); + + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + mr = info.mr; + mg = info.mg; + mb = info.mb; + ma = info.ma; + all_a = info.all_a; + + if (info.hsz == 12) { + if (info.bpp < 24) + psize = (info.offset - info.extra_read - 24) / 3; + } else { + if (info.bpp < 16) + psize = (info.offset - info.extra_read - info.hsz) >> 2; + } + if (psize == 0) { + // accept some number of extra bytes after the header, but if the offset points either to before + // the header ends or implies a large amount of extra data, reject the file as malformed + int bytes_read_so_far = s->callback_already_read + (int)(s->img_buffer - s->img_buffer_original); + int header_limit = 1024; // max we actually read is below 256 bytes currently. + int extra_data_limit = 256*4; // what ordinarily goes here is a palette; 256 entries*4 bytes is its max size. + if (bytes_read_so_far <= 0 || bytes_read_so_far > header_limit) { + return stbi__errpuc("bad header", "Corrupt BMP"); + } + // we established that bytes_read_so_far is positive and sensible. + // the first half of this test rejects offsets that are either too small positives, or + // negative, and guarantees that info.offset >= bytes_read_so_far > 0. this in turn + // ensures the number computed in the second half of the test can't overflow. + if (info.offset < bytes_read_so_far || info.offset - bytes_read_so_far > extra_data_limit) { + return stbi__errpuc("bad offset", "Corrupt BMP"); + } else { + stbi__skip(s, info.offset - bytes_read_so_far); + } + } + + if (info.bpp == 24 && ma == 0xff000000) + s->img_n = 3; + else + s->img_n = ma ? 4 : 3; if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 target = req_comp; else target = s->img_n; // if they want monochrome, we'll post-convert - out = (stbi_uc *) stbi__malloc(target * s->img_x * s->img_y); + + // sanity-check size + if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0)) + return stbi__errpuc("too large", "Corrupt BMP"); + + out = (stbi_uc *) stbi__malloc_mad3(target, s->img_x, s->img_y, 0); if (!out) return stbi__errpuc("outofmem", "Out of memory"); - if (bpp < 16) { + if (info.bpp < 16) { int z=0; if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); } for (i=0; i < psize; ++i) { pal[i][2] = stbi__get8(s); pal[i][1] = stbi__get8(s); pal[i][0] = stbi__get8(s); - if (hsz != 12) stbi__get8(s); + if (info.hsz != 12) stbi__get8(s); pal[i][3] = 255; } - stbi__skip(s, offset - 14 - hsz - psize * (hsz == 12 ? 3 : 4)); - if (bpp == 4) width = (s->img_x + 1) >> 1; - else if (bpp == 8) width = s->img_x; + stbi__skip(s, info.offset - info.extra_read - info.hsz - psize * (info.hsz == 12 ? 3 : 4)); + if (info.bpp == 1) width = (s->img_x + 7) >> 3; + else if (info.bpp == 4) width = (s->img_x + 1) >> 1; + else if (info.bpp == 8) width = s->img_x; else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); } pad = (-width)&3; - for (j=0; j < (int) s->img_y; ++j) { - for (i=0; i < (int) s->img_x; i += 2) { - int v=stbi__get8(s),v2=0; - if (bpp == 4) { - v2 = v & 15; - v >>= 4; + if (info.bpp == 1) { + for (j=0; j < (int) s->img_y; ++j) { + int bit_offset = 7, v = stbi__get8(s); + for (i=0; i < (int) s->img_x; ++i) { + int color = (v>>bit_offset)&0x1; + out[z++] = pal[color][0]; + out[z++] = pal[color][1]; + out[z++] = pal[color][2]; + if (target == 4) out[z++] = 255; + if (i+1 == (int) s->img_x) break; + if((--bit_offset) < 0) { + bit_offset = 7; + v = stbi__get8(s); + } } - out[z++] = pal[v][0]; - out[z++] = pal[v][1]; - out[z++] = pal[v][2]; - if (target == 4) out[z++] = 255; - if (i+1 == (int) s->img_x) break; - v = (bpp == 8) ? stbi__get8(s) : v2; - out[z++] = pal[v][0]; - out[z++] = pal[v][1]; - out[z++] = pal[v][2]; - if (target == 4) out[z++] = 255; + stbi__skip(s, pad); + } + } else { + for (j=0; j < (int) s->img_y; ++j) { + for (i=0; i < (int) s->img_x; i += 2) { + int v=stbi__get8(s),v2=0; + if (info.bpp == 4) { + v2 = v & 15; + v >>= 4; + } + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + if (i+1 == (int) s->img_x) break; + v = (info.bpp == 8) ? stbi__get8(s) : v2; + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + } + stbi__skip(s, pad); } - stbi__skip(s, pad); } } else { int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0; int z = 0; int easy=0; - stbi__skip(s, offset - 14 - hsz); - if (bpp == 24) width = 3 * s->img_x; - else if (bpp == 16) width = 2*s->img_x; + stbi__skip(s, info.offset - info.extra_read - info.hsz); + if (info.bpp == 24) width = 3 * s->img_x; + else if (info.bpp == 16) width = 2*s->img_x; else /* bpp = 32 and pad = 0 */ width=0; pad = (-width) & 3; - if (bpp == 24) { + if (info.bpp == 24) { easy = 1; - } else if (bpp == 32) { + } else if (info.bpp == 32) { if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) easy = 2; } @@ -4751,6 +5672,7 @@ static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg); bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb); ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma); + if (rcount > 8 || gcount > 8 || bcount > 8 || acount > 8) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } } for (j=0; j < (int) s->img_y; ++j) { if (easy) { @@ -4765,9 +5687,10 @@ static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int if (target == 4) out[z++] = a; } } else { + int bpp = info.bpp; for (i=0; i < (int) s->img_x; ++i) { stbi__uint32 v = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s)); - int a; + unsigned int a; out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount)); out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount)); out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount)); @@ -4779,7 +5702,7 @@ static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int stbi__skip(s, pad); } } - + // if alpha channel is all 0s, replace with all 255s if (target == 4 && all_a == 0) for (i=4*s->img_x*s->img_y-1; i >= 0; i -= 4) @@ -4791,7 +5714,7 @@ static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int stbi_uc *p1 = out + j *s->img_x*target; stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target; for (i=0; i < (int) s->img_x*target; ++i) { - t = p1[i], p1[i] = p2[i], p2[i] = t; + t = p1[i]; p1[i] = p2[i]; p2[i] = t; } } } @@ -4811,20 +5734,55 @@ static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int // Targa Truevision - TGA // by Jonathan Dummer #ifndef STBI_NO_TGA +// returns STBI_rgb or whatever, 0 on error +static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16) +{ + // only RGB or RGBA (incl. 16bit) or grey allowed + if (is_rgb16) *is_rgb16 = 0; + switch(bits_per_pixel) { + case 8: return STBI_grey; + case 16: if(is_grey) return STBI_grey_alpha; + // fallthrough + case 15: if(is_rgb16) *is_rgb16 = 1; + return STBI_rgb; + case 24: // fallthrough + case 32: return bits_per_pixel/8; + default: return 0; + } +} + static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp) { - int tga_w, tga_h, tga_comp; - int sz; + int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp; + int sz, tga_colormap_type; stbi__get8(s); // discard Offset - sz = stbi__get8(s); // color type - if( sz > 1 ) { + tga_colormap_type = stbi__get8(s); // colormap type + if( tga_colormap_type > 1 ) { stbi__rewind(s); return 0; // only RGB or indexed allowed } - sz = stbi__get8(s); // image type - // only RGB or grey allowed, +/- RLE - if ((sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11)) return 0; - stbi__skip(s,9); + tga_image_type = stbi__get8(s); // image type + if ( tga_colormap_type == 1 ) { // colormapped (paletted) image + if (tga_image_type != 1 && tga_image_type != 9) { + stbi__rewind(s); + return 0; + } + stbi__skip(s,4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) { + stbi__rewind(s); + return 0; + } + stbi__skip(s,4); // skip image x and y origin + tga_colormap_bpp = sz; + } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE + if ( (tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11) ) { + stbi__rewind(s); + return 0; // only RGB or grey allowed, +/- RLE + } + stbi__skip(s,9); // skip colormap specification and image x/y origin + tga_colormap_bpp = 0; + } tga_w = stbi__get16le(s); if( tga_w < 1 ) { stbi__rewind(s); @@ -4835,45 +5793,81 @@ static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp) stbi__rewind(s); return 0; // test height } - sz = stbi__get8(s); // bits per pixel - // only RGB or RGBA or grey allowed - if ((sz != 8) && (sz != 16) && (sz != 24) && (sz != 32)) { - stbi__rewind(s); - return 0; + tga_bits_per_pixel = stbi__get8(s); // bits per pixel + stbi__get8(s); // ignore alpha bits + if (tga_colormap_bpp != 0) { + if((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) { + // when using a colormap, tga_bits_per_pixel is the size of the indexes + // I don't think anything but 8 or 16bit indexes makes sense + stbi__rewind(s); + return 0; + } + tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL); + } else { + tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL); + } + if(!tga_comp) { + stbi__rewind(s); + return 0; } - tga_comp = sz; if (x) *x = tga_w; if (y) *y = tga_h; - if (comp) *comp = tga_comp / 8; + if (comp) *comp = tga_comp; return 1; // seems to have passed everything } static int stbi__tga_test(stbi__context *s) { - int res; - int sz; + int res = 0; + int sz, tga_color_type; stbi__get8(s); // discard Offset - sz = stbi__get8(s); // color type - if ( sz > 1 ) return 0; // only RGB or indexed allowed + tga_color_type = stbi__get8(s); // color type + if ( tga_color_type > 1 ) goto errorEnd; // only RGB or indexed allowed sz = stbi__get8(s); // image type - if ( (sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11) ) return 0; // only RGB or grey allowed, +/- RLE - stbi__get16be(s); // discard palette start - stbi__get16be(s); // discard palette length - stbi__get8(s); // discard bits per palette color entry - stbi__get16be(s); // discard x origin - stbi__get16be(s); // discard y origin - if ( stbi__get16be(s) < 1 ) return 0; // test width - if ( stbi__get16be(s) < 1 ) return 0; // test height + if ( tga_color_type == 1 ) { // colormapped (paletted) image + if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9 + stbi__skip(s,4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; + stbi__skip(s,4); // skip image x and y origin + } else { // "normal" image w/o colormap + if ( (sz != 2) && (sz != 3) && (sz != 10) && (sz != 11) ) goto errorEnd; // only RGB or grey allowed, +/- RLE + stbi__skip(s,9); // skip colormap specification and image x/y origin + } + if ( stbi__get16le(s) < 1 ) goto errorEnd; // test width + if ( stbi__get16le(s) < 1 ) goto errorEnd; // test height sz = stbi__get8(s); // bits per pixel - if ( (sz != 8) && (sz != 16) && (sz != 24) && (sz != 32) ) - res = 0; - else - res = 1; + if ( (tga_color_type == 1) && (sz != 8) && (sz != 16) ) goto errorEnd; // for colormapped images, bpp is size of an index + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; + + res = 1; // if we got this far, everything's good and we can return 1 instead of 0 + +errorEnd: stbi__rewind(s); return res; } -static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +// read 16bit value and convert to 24bit RGB +static void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out) +{ + stbi__uint16 px = (stbi__uint16)stbi__get16le(s); + stbi__uint16 fiveBitMask = 31; + // we have 3 channels with 5bits each + int r = (px >> 10) & fiveBitMask; + int g = (px >> 5) & fiveBitMask; + int b = px & fiveBitMask; + // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later + out[0] = (stbi_uc)((r * 255)/31); + out[1] = (stbi_uc)((g * 255)/31); + out[2] = (stbi_uc)((b * 255)/31); + + // some people claim that the most significant bit might be used for alpha + // (possibly if an alpha-bit is set in the "image descriptor byte") + // but that only made 16bit test images completely translucent.. + // so let's treat all 15 and 16bit TGAs as RGB with no alpha. +} + +static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { // read in the TGA header stuff int tga_offset = stbi__get8(s); @@ -4888,55 +5882,54 @@ static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int int tga_width = stbi__get16le(s); int tga_height = stbi__get16le(s); int tga_bits_per_pixel = stbi__get8(s); - int tga_comp = tga_bits_per_pixel / 8; + int tga_comp, tga_rgb16=0; int tga_inverted = stbi__get8(s); + // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?) // image data unsigned char *tga_data; unsigned char *tga_palette = NULL; int i, j; - unsigned char raw_data[4]; + unsigned char raw_data[4] = {0}; int RLE_count = 0; int RLE_repeating = 0; int read_next_pixel = 1; + STBI_NOTUSED(ri); + STBI_NOTUSED(tga_x_origin); // @TODO + STBI_NOTUSED(tga_y_origin); // @TODO - // do a tiny bit of processing + if (tga_height > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (tga_width > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + // do a tiny bit of precessing if ( tga_image_type >= 8 ) { tga_image_type -= 8; tga_is_RLE = 1; } - /* int tga_alpha_bits = tga_inverted & 15; */ tga_inverted = 1 - ((tga_inverted >> 5) & 1); - // error check - if ( //(tga_indexed) || - (tga_width < 1) || (tga_height < 1) || - (tga_image_type < 1) || (tga_image_type > 3) || - ((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16) && - (tga_bits_per_pixel != 24) && (tga_bits_per_pixel != 32)) - ) - { - return NULL; // we don't report this as a bad TGA because we don't even know if it's TGA - } - // If I'm paletted, then I'll use the number of bits from the palette - if ( tga_indexed ) - { - tga_comp = tga_palette_bits / 8; - } + if ( tga_indexed ) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16); + else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16); + + if(!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency + return stbi__errpuc("bad format", "Can't find out TGA pixelformat"); // tga info *x = tga_width; *y = tga_height; if (comp) *comp = tga_comp; - tga_data = (unsigned char*)stbi__malloc( (size_t)tga_width * tga_height * tga_comp ); + if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0)) + return stbi__errpuc("too large", "Corrupt TGA"); + + tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0); if (!tga_data) return stbi__errpuc("outofmem", "Out of memory"); // skip to the data's starting position (offset usually = 0) stbi__skip(s, tga_offset ); - if ( !tga_indexed && !tga_is_RLE) { + if ( !tga_indexed && !tga_is_RLE && !tga_rgb16 ) { for (i=0; i < tga_height; ++i) { int row = tga_inverted ? tga_height -i - 1 : i; stbi_uc *tga_row = tga_data + row*tga_width*tga_comp; @@ -4946,18 +5939,30 @@ static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int // do I need to load a palette? if ( tga_indexed) { + if (tga_palette_len == 0) { /* you have to have at least one entry! */ + STBI_FREE(tga_data); + return stbi__errpuc("bad palette", "Corrupt TGA"); + } + // any data to skip? (offset usually = 0) stbi__skip(s, tga_palette_start ); // load the palette - tga_palette = (unsigned char*)stbi__malloc( tga_palette_len * tga_palette_bits / 8 ); + tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0); if (!tga_palette) { STBI_FREE(tga_data); return stbi__errpuc("outofmem", "Out of memory"); } - if (!stbi__getn(s, tga_palette, tga_palette_len * tga_palette_bits / 8 )) { - STBI_FREE(tga_data); - STBI_FREE(tga_palette); - return stbi__errpuc("bad palette", "Corrupt TGA"); + if (tga_rgb16) { + stbi_uc *pal_entry = tga_palette; + STBI_ASSERT(tga_comp == STBI_rgb); + for (i=0; i < tga_palette_len; ++i) { + stbi__tga_read_rgb16(s, pal_entry); + pal_entry += tga_comp; + } + } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) { + STBI_FREE(tga_data); + STBI_FREE(tga_palette); + return stbi__errpuc("bad palette", "Corrupt TGA"); } } // load the data @@ -4987,23 +5992,22 @@ static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int // load however much data we did have if ( tga_indexed ) { - // read in 1 byte, then perform the lookup - int pal_idx = stbi__get8(s); - if ( pal_idx >= tga_palette_len ) - { - // invalid index + // read in index, then perform the lookup + int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s); + if ( pal_idx >= tga_palette_len ) { + // invalid index pal_idx = 0; } - pal_idx *= tga_bits_per_pixel / 8; - for (j = 0; j*8 < tga_bits_per_pixel; ++j) - { + pal_idx *= tga_comp; + for (j = 0; j < tga_comp; ++j) { raw_data[j] = tga_palette[pal_idx+j]; } - } else - { + } else if(tga_rgb16) { + STBI_ASSERT(tga_comp == STBI_rgb); + stbi__tga_read_rgb16(s, raw_data); + } else { // read in the data raw - for (j = 0; j*8 < tga_bits_per_pixel; ++j) - { + for (j = 0; j < tga_comp; ++j) { raw_data[j] = stbi__get8(s); } } @@ -5042,8 +6046,8 @@ static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int } } - // swap RGB - if (tga_comp >= 3) + // swap RGB - if the source data was RGB16, it already is in the right order + if (tga_comp >= 3 && !tga_rgb16) { unsigned char* tga_pixel = tga_data; for (i=0; i < tga_width * tga_height; ++i) @@ -5063,6 +6067,7 @@ static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int // Microsoft's C compilers happy... [8^( tga_palette_start = tga_palette_len = tga_palette_bits = tga_x_origin = tga_y_origin = 0; + STBI_NOTUSED(tga_palette_start); // OK, done return tga_data; } @@ -5079,14 +6084,53 @@ static int stbi__psd_test(stbi__context *s) return r; } -static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +static int stbi__psd_decode_rle(stbi__context *s, stbi_uc *p, int pixelCount) { - int pixelCount; + int count, nleft, len; + + count = 0; + while ((nleft = pixelCount - count) > 0) { + len = stbi__get8(s); + if (len == 128) { + // No-op. + } else if (len < 128) { + // Copy next len+1 bytes literally. + len++; + if (len > nleft) return 0; // corrupt data + count += len; + while (len) { + *p = stbi__get8(s); + p += 4; + len--; + } + } else if (len > 128) { + stbi_uc val; + // Next -len+1 bytes in the dest are replicated from next source byte. + // (Interpret len as a negative 8-bit int.) + len = 257 - len; + if (len > nleft) return 0; // corrupt data + val = stbi__get8(s); + count += len; + while (len) { + *p = val; + p += 4; + len--; + } + } + } + + return 1; +} + +static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) +{ + int pixelCount; int channelCount, compression; - int channel, i, count, len; + int channel, i; int bitdepth; int w,h; stbi_uc *out; + STBI_NOTUSED(ri); // Check identifier if (stbi__get32be(s) != 0x38425053) // "8BPS" @@ -5108,6 +6152,9 @@ static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int h = stbi__get32be(s); w = stbi__get32be(s); + if (h > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (w > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + // Make sure the depth is 8 bits. bitdepth = stbi__get16be(s); if (bitdepth != 8 && bitdepth != 16) @@ -5143,8 +6190,18 @@ static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int if (compression > 1) return stbi__errpuc("bad compression", "PSD has an unknown compression format"); + // Check size + if (!stbi__mad3sizes_valid(4, w, h, 0)) + return stbi__errpuc("too large", "Corrupt PSD"); + // Create the destination image. - out = (stbi_uc *) stbi__malloc(4 * w*h); + + if (!compression && bitdepth == 16 && bpc == 16) { + out = (stbi_uc *) stbi__malloc_mad3(8, w, h, 0); + ri->bits_per_channel = 16; + } else + out = (stbi_uc *) stbi__malloc(4 * w*h); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); pixelCount = w*h; @@ -5176,67 +6233,86 @@ static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int *p = (channel == 3 ? 255 : 0); } else { // Read the RLE data. - count = 0; - while (count < pixelCount) { - len = stbi__get8(s); - if (len == 128) { - // No-op. - } else if (len < 128) { - // Copy next len+1 bytes literally. - len++; - count += len; - while (len) { - *p = stbi__get8(s); - p += 4; - len--; - } - } else if (len > 128) { - stbi_uc val; - // Next -len+1 bytes in the dest are replicated from next source byte. - // (Interpret len as a negative 8-bit int.) - len ^= 0x0FF; - len += 2; - val = stbi__get8(s); - count += len; - while (len) { - *p = val; - p += 4; - len--; - } - } + if (!stbi__psd_decode_rle(s, p, pixelCount)) { + STBI_FREE(out); + return stbi__errpuc("corrupt", "bad RLE data"); } } } } else { // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) - // where each channel consists of an 8-bit value for each pixel in the image. + // where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image. // Read the data by channel. for (channel = 0; channel < 4; channel++) { - stbi_uc *p; - - p = out + channel; if (channel >= channelCount) { // Fill this channel with default data. - stbi_uc val = channel == 3 ? 255 : 0; - for (i = 0; i < pixelCount; i++, p += 4) - *p = val; - } else { - // Read the data. - if (bitdepth == 16) { - for (i = 0; i < pixelCount; i++, p += 4) - *p = (stbi_uc) (stbi__get16be(s) >> 8); + if (bitdepth == 16 && bpc == 16) { + stbi__uint16 *q = ((stbi__uint16 *) out) + channel; + stbi__uint16 val = channel == 3 ? 65535 : 0; + for (i = 0; i < pixelCount; i++, q += 4) + *q = val; } else { + stbi_uc *p = out+channel; + stbi_uc val = channel == 3 ? 255 : 0; for (i = 0; i < pixelCount; i++, p += 4) - *p = stbi__get8(s); + *p = val; + } + } else { + if (ri->bits_per_channel == 16) { // output bpc + stbi__uint16 *q = ((stbi__uint16 *) out) + channel; + for (i = 0; i < pixelCount; i++, q += 4) + *q = (stbi__uint16) stbi__get16be(s); + } else { + stbi_uc *p = out+channel; + if (bitdepth == 16) { // input bpc + for (i = 0; i < pixelCount; i++, p += 4) + *p = (stbi_uc) (stbi__get16be(s) >> 8); + } else { + for (i = 0; i < pixelCount; i++, p += 4) + *p = stbi__get8(s); + } } } } } + // remove weird white matte from PSD + if (channelCount >= 4) { + if (ri->bits_per_channel == 16) { + for (i=0; i < w*h; ++i) { + stbi__uint16 *pixel = (stbi__uint16 *) out + 4*i; + if (pixel[3] != 0 && pixel[3] != 65535) { + float a = pixel[3] / 65535.0f; + float ra = 1.0f / a; + float inv_a = 65535.0f * (1 - ra); + pixel[0] = (stbi__uint16) (pixel[0]*ra + inv_a); + pixel[1] = (stbi__uint16) (pixel[1]*ra + inv_a); + pixel[2] = (stbi__uint16) (pixel[2]*ra + inv_a); + } + } + } else { + for (i=0; i < w*h; ++i) { + unsigned char *pixel = out + 4*i; + if (pixel[3] != 0 && pixel[3] != 255) { + float a = pixel[3] / 255.0f; + float ra = 1.0f / a; + float inv_a = 255.0f * (1 - ra); + pixel[0] = (unsigned char) (pixel[0]*ra + inv_a); + pixel[1] = (unsigned char) (pixel[1]*ra + inv_a); + pixel[2] = (unsigned char) (pixel[2]*ra + inv_a); + } + } + } + } + + // convert to desired output format if (req_comp && req_comp != 4) { - out = stbi__convert_format(out, 4, req_comp, w, h); + if (ri->bits_per_channel == 16) + out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4, req_comp, w, h); + else + out = stbi__convert_format(out, 4, req_comp, w, h); if (out == NULL) return out; // stbi__convert_format frees input on failure } @@ -5420,25 +6496,33 @@ static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *c return result; } -static stbi_uc *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp) +static void *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp, stbi__result_info *ri) { stbi_uc *result; - int i, x,y; + int i, x,y, internal_comp; + STBI_NOTUSED(ri); + + if (!comp) comp = &internal_comp; for (i=0; i<92; ++i) stbi__get8(s); x = stbi__get16be(s); y = stbi__get16be(s); + + if (y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)"); - if ((1 << 28) / x < y) return stbi__errpuc("too large", "Image too large to decode"); + if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode"); stbi__get32be(s); //skip `ratio' stbi__get16be(s); //skip `fields' stbi__get16be(s); //skip `pad' // intermediate buffer is RGBA - result = (stbi_uc *) stbi__malloc(x*y*4); + result = (stbi_uc *) stbi__malloc_mad3(x, y, 4, 0); + if (!result) return stbi__errpuc("outofmem", "Out of memory"); memset(result, 0xff, x*y*4); if (!stbi__pic_load_core(s,x,y,comp, result)) { @@ -5475,11 +6559,13 @@ typedef struct typedef struct { int w,h; - stbi_uc *out, *old_out; // output buffer (always 4 components) - int flags, bgindex, ratio, transparent, eflags, delay; + stbi_uc *out; // output buffer (always 4 components) + stbi_uc *background; // The current "background" as far as a gif is concerned + stbi_uc *history; + int flags, bgindex, ratio, transparent, eflags; stbi_uc pal[256][4]; stbi_uc lpal[256][4]; - stbi__gif_lzw codes[4096]; + stbi__gif_lzw codes[8192]; stbi_uc *color_table; int parse, step; int lflags; @@ -5487,6 +6573,7 @@ typedef struct int max_x, max_y; int cur_x, cur_y; int line_size; + int delay; } stbi__gif; static int stbi__gif_test_raw(stbi__context *s) @@ -5535,6 +6622,9 @@ static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_in g->ratio = stbi__get8(s); g->transparent = -1; + if (g->w > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (g->h > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments if (is_info) return 1; @@ -5547,19 +6637,23 @@ static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_in static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp) { - stbi__gif g; - if (!stbi__gif_header(s, &g, comp, 1)) { + stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif)); + if (!g) return stbi__err("outofmem", "Out of memory"); + if (!stbi__gif_header(s, g, comp, 1)) { + STBI_FREE(g); stbi__rewind( s ); return 0; } - if (x) *x = g.w; - if (y) *y = g.h; + if (x) *x = g->w; + if (y) *y = g->h; + STBI_FREE(g); return 1; } static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code) { stbi_uc *p, *c; + int idx; // recurse to decode the prefixes, since the linked-list is backwards, // and working backwards through an interleaved image would be nasty @@ -5568,10 +6662,12 @@ static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code) if (g->cur_y >= g->max_y) return; - p = &g->out[g->cur_x + g->cur_y]; - c = &g->color_table[g->codes[code].suffix * 4]; + idx = g->cur_x + g->cur_y; + p = &g->out[idx]; + g->history[idx / 4] = 1; - if (c[3] >= 128) { + c = &g->color_table[g->codes[code].suffix * 4]; + if (c[3] > 128) { // don't render transparent pixels; p[0] = c[2]; p[1] = c[1]; p[2] = c[0]; @@ -5645,11 +6741,16 @@ static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) stbi__skip(s,len); return g->out; } else if (code <= avail) { - if (first) return stbi__errpuc("no clear code", "Corrupt GIF"); + if (first) { + return stbi__errpuc("no clear code", "Corrupt GIF"); + } if (oldcode >= 0) { p = &g->codes[avail++]; - if (avail > 4096) return stbi__errpuc("too many codes", "Corrupt GIF"); + if (avail > 8192) { + return stbi__errpuc("too many codes", "Corrupt GIF"); + } + p->prefix = (stbi__int16) oldcode; p->first = g->codes[oldcode].first; p->suffix = (code == avail) ? p->first : g->codes[code].first; @@ -5671,59 +6772,77 @@ static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) } } -static void stbi__fill_gif_background(stbi__gif *g, int x0, int y0, int x1, int y1) -{ - int x, y; - stbi_uc *c = g->pal[g->bgindex]; - for (y = y0; y < y1; y += 4 * g->w) { - for (x = x0; x < x1; x += 4) { - stbi_uc *p = &g->out[y + x]; - p[0] = c[2]; - p[1] = c[1]; - p[2] = c[0]; - p[3] = 0; - } - } -} - // this function is designed to support animated gifs, although stb_image doesn't support it -static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp) +// two back is the image from two frames ago, used for a very specific disposal format +static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp, stbi_uc *two_back) { - int i; - stbi_uc *prev_out = 0; + int dispose; + int first_frame; + int pi; + int pcount; + STBI_NOTUSED(req_comp); - if (g->out == 0 && !stbi__gif_header(s, g, comp,0)) - return 0; // stbi__g_failure_reason set by stbi__gif_header + // on first frame, any non-written pixels get the background colour (non-transparent) + first_frame = 0; + if (g->out == 0) { + if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header + if (!stbi__mad3sizes_valid(4, g->w, g->h, 0)) + return stbi__errpuc("too large", "GIF image is too large"); + pcount = g->w * g->h; + g->out = (stbi_uc *) stbi__malloc(4 * pcount); + g->background = (stbi_uc *) stbi__malloc(4 * pcount); + g->history = (stbi_uc *) stbi__malloc(pcount); + if (!g->out || !g->background || !g->history) + return stbi__errpuc("outofmem", "Out of memory"); - prev_out = g->out; - g->out = (stbi_uc *) stbi__malloc(4 * g->w * g->h); - if (g->out == 0) return stbi__errpuc("outofmem", "Out of memory"); + // image is treated as "transparent" at the start - ie, nothing overwrites the current background; + // background colour is only used for pixels that are not rendered first frame, after that "background" + // color refers to the color that was there the previous frame. + memset(g->out, 0x00, 4 * pcount); + memset(g->background, 0x00, 4 * pcount); // state of the background (starts transparent) + memset(g->history, 0x00, pcount); // pixels that were affected previous frame + first_frame = 1; + } else { + // second frame - how do we dispose of the previous one? + dispose = (g->eflags & 0x1C) >> 2; + pcount = g->w * g->h; - switch ((g->eflags & 0x1C) >> 2) { - case 0: // unspecified (also always used on 1st frame) - stbi__fill_gif_background(g, 0, 0, 4 * g->w, 4 * g->w * g->h); - break; - case 1: // do not dispose - if (prev_out) memcpy(g->out, prev_out, 4 * g->w * g->h); - g->old_out = prev_out; - break; - case 2: // dispose to background - if (prev_out) memcpy(g->out, prev_out, 4 * g->w * g->h); - stbi__fill_gif_background(g, g->start_x, g->start_y, g->max_x, g->max_y); - break; - case 3: // dispose to previous - if (g->old_out) { - for (i = g->start_y; i < g->max_y; i += 4 * g->w) - memcpy(&g->out[i + g->start_x], &g->old_out[i + g->start_x], g->max_x - g->start_x); + if ((dispose == 3) && (two_back == 0)) { + dispose = 2; // if I don't have an image to revert back to, default to the old background + } + + if (dispose == 3) { // use previous graphic + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy( &g->out[pi * 4], &two_back[pi * 4], 4 ); + } } - break; + } else if (dispose == 2) { + // restore what was changed last frame to background before that frame; + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy( &g->out[pi * 4], &g->background[pi * 4], 4 ); + } + } + } else { + // This is a non-disposal case eithe way, so just + // leave the pixels as is, and they will become the new background + // 1: do not dispose + // 0: not specified. + } + + // background is what out is after the undoing of the previou frame; + memcpy( g->background, g->out, 4 * g->w * g->h ); } + // clear my history; + memset( g->history, 0x00, g->w * g->h ); // pixels that were affected previous frame + for (;;) { - switch (stbi__get8(s)) { + int tag = stbi__get8(s); + switch (tag) { case 0x2C: /* Image Descriptor */ { - int prev_trans = -1; stbi__int32 x, y, w, h; stbi_uc *o; @@ -5742,6 +6861,13 @@ static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, i g->cur_x = g->start_x; g->cur_y = g->start_y; + // if the width of the specified rectangle is 0, that means + // we may not see *any* pixels or the image is malformed; + // to make sure this is caught, move the current y down to + // max_y (which is what out_gif_code checks). + if (w == 0) + g->cur_y = g->max_y; + g->lflags = stbi__get8(s); if (g->lflags & 0x40) { @@ -5756,19 +6882,24 @@ static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, i stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1); g->color_table = (stbi_uc *) g->lpal; } else if (g->flags & 0x80) { - if (g->transparent >= 0 && (g->eflags & 0x01)) { - prev_trans = g->pal[g->transparent][3]; - g->pal[g->transparent][3] = 0; - } g->color_table = (stbi_uc *) g->pal; } else return stbi__errpuc("missing color table", "Corrupt GIF"); o = stbi__process_gif_raster(s, g); - if (o == NULL) return NULL; + if (!o) return NULL; - if (prev_trans != -1) - g->pal[g->transparent][3] = (stbi_uc) prev_trans; + // if this was the first frame, + pcount = g->w * g->h; + if (first_frame && (g->bgindex > 0)) { + // if first frame, any pixel not drawn to gets the background color + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi] == 0) { + g->pal[g->bgindex][3] = 255; // just in case it was made transparent, undo that; It will be reset next frame if need be; + memcpy( &g->out[pi * 4], &g->pal[g->bgindex], 4 ); + } + } + } return o; } @@ -5776,19 +6907,35 @@ static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, i case 0x21: // Comment Extension. { int len; - if (stbi__get8(s) == 0xF9) { // Graphic Control Extension. + int ext = stbi__get8(s); + if (ext == 0xF9) { // Graphic Control Extension. len = stbi__get8(s); if (len == 4) { g->eflags = stbi__get8(s); - g->delay = stbi__get16le(s); - g->transparent = stbi__get8(s); + g->delay = 10 * stbi__get16le(s); // delay - 1/100th of a second, saving as 1/1000ths. + + // unset old transparent + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 255; + } + if (g->eflags & 0x01) { + g->transparent = stbi__get8(s); + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 0; + } + } else { + // don't need transparent + stbi__skip(s, 1); + g->transparent = -1; + } } else { stbi__skip(s, len); break; } } - while ((len = stbi__get8(s)) != 0) + while ((len = stbi__get8(s)) != 0) { stbi__skip(s, len); + } break; } @@ -5799,26 +6946,129 @@ static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, i return stbi__errpuc("unknown code", "Corrupt GIF"); } } - - STBI_NOTUSED(req_comp); } -static stbi_uc *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +static void *stbi__load_gif_main_outofmem(stbi__gif *g, stbi_uc *out, int **delays) +{ + STBI_FREE(g->out); + STBI_FREE(g->history); + STBI_FREE(g->background); + + if (out) STBI_FREE(out); + if (delays && *delays) STBI_FREE(*delays); + return stbi__errpuc("outofmem", "Out of memory"); +} + +static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp) +{ + if (stbi__gif_test(s)) { + int layers = 0; + stbi_uc *u = 0; + stbi_uc *out = 0; + stbi_uc *two_back = 0; + stbi__gif g; + int stride; + int out_size = 0; + int delays_size = 0; + + STBI_NOTUSED(out_size); + STBI_NOTUSED(delays_size); + + memset(&g, 0, sizeof(g)); + if (delays) { + *delays = 0; + } + + do { + u = stbi__gif_load_next(s, &g, comp, req_comp, two_back); + if (u == (stbi_uc *) s) u = 0; // end of animated gif marker + + if (u) { + *x = g.w; + *y = g.h; + ++layers; + stride = g.w * g.h * 4; + + if (out) { + void *tmp = (stbi_uc*) STBI_REALLOC_SIZED( out, out_size, layers * stride ); + if (!tmp) + return stbi__load_gif_main_outofmem(&g, out, delays); + else { + out = (stbi_uc*) tmp; + out_size = layers * stride; + } + + if (delays) { + int *new_delays = (int*) STBI_REALLOC_SIZED( *delays, delays_size, sizeof(int) * layers ); + if (!new_delays) + return stbi__load_gif_main_outofmem(&g, out, delays); + *delays = new_delays; + delays_size = layers * sizeof(int); + } + } else { + out = (stbi_uc*)stbi__malloc( layers * stride ); + if (!out) + return stbi__load_gif_main_outofmem(&g, out, delays); + out_size = layers * stride; + if (delays) { + *delays = (int*) stbi__malloc( layers * sizeof(int) ); + if (!*delays) + return stbi__load_gif_main_outofmem(&g, out, delays); + delays_size = layers * sizeof(int); + } + } + memcpy( out + ((layers - 1) * stride), u, stride ); + if (layers >= 2) { + two_back = out - 2 * stride; + } + + if (delays) { + (*delays)[layers - 1U] = g.delay; + } + } + } while (u != 0); + + // free temp buffer; + STBI_FREE(g.out); + STBI_FREE(g.history); + STBI_FREE(g.background); + + // do the final conversion after loading everything; + if (req_comp && req_comp != 4) + out = stbi__convert_format(out, 4, req_comp, layers * g.w, g.h); + + *z = layers; + return out; + } else { + return stbi__errpuc("not GIF", "Image was not as a gif type."); + } +} + +static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { stbi_uc *u = 0; stbi__gif g; memset(&g, 0, sizeof(g)); + STBI_NOTUSED(ri); - u = stbi__gif_load_next(s, &g, comp, req_comp); + u = stbi__gif_load_next(s, &g, comp, req_comp, 0); if (u == (stbi_uc *) s) u = 0; // end of animated gif marker if (u) { *x = g.w; *y = g.h; + + // moved conversion to after successful load so that the same + // can be done for multiple frames. if (req_comp && req_comp != 4) u = stbi__convert_format(u, 4, req_comp, g.w, g.h); - } - else if (g.out) + } else if (g.out) { + // if there was an error and we allocated an image buffer, free it! STBI_FREE(g.out); + } + + // free buffers needed for multiple frame loading; + STBI_FREE(g.history); + STBI_FREE(g.background); return u; } @@ -5833,20 +7083,24 @@ static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp) // Radiance RGBE HDR loader // originally by Nicolas Schulz #ifndef STBI_NO_HDR -static int stbi__hdr_test_core(stbi__context *s) +static int stbi__hdr_test_core(stbi__context *s, const char *signature) { - const char *signature = "#?RADIANCE\n"; int i; for (i=0; signature[i]; ++i) if (stbi__get8(s) != signature[i]) - return 0; + return 0; + stbi__rewind(s); return 1; } static int stbi__hdr_test(stbi__context* s) { - int r = stbi__hdr_test_core(s); + int r = stbi__hdr_test_core(s, "#?RADIANCE\n"); stbi__rewind(s); + if(!r) { + r = stbi__hdr_test_core(s, "#?RGBE\n"); + stbi__rewind(s); + } return r; } @@ -5900,7 +7154,7 @@ static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp) } } -static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { char buffer[STBI__HDR_BUFLEN]; char *token; @@ -5911,10 +7165,12 @@ static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int re int len; unsigned char count, value; int i, j, k, c1,c2, z; - + const char *headerToken; + STBI_NOTUSED(ri); // Check identifier - if (strcmp(stbi__hdr_gettoken(s,buffer), "#?RADIANCE") != 0) + headerToken = stbi__hdr_gettoken(s,buffer); + if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0) return stbi__errpf("not HDR", "Corrupt HDR image"); // Parse header @@ -5937,14 +7193,22 @@ static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int re token += 3; width = (int) strtol(token, NULL, 10); + if (height > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); + if (width > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); + *x = width; *y = height; if (comp) *comp = 3; if (req_comp == 0) req_comp = 3; + if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0)) + return stbi__errpf("too large", "HDR image is too large"); + // Read data - hdr_data = (float *) stbi__malloc(height * width * req_comp * sizeof(float)); + hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0); + if (!hdr_data) + return stbi__errpf("outofmem", "Out of memory"); // Load image data // image data is stored as some number of sca @@ -5983,20 +7247,29 @@ static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int re len <<= 8; len |= stbi__get8(s); if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); } - if (scanline == NULL) scanline = (stbi_uc *) stbi__malloc(width * 4); + if (scanline == NULL) { + scanline = (stbi_uc *) stbi__malloc_mad2(width, 4, 0); + if (!scanline) { + STBI_FREE(hdr_data); + return stbi__errpf("outofmem", "Out of memory"); + } + } for (k = 0; k < 4; ++k) { + int nleft; i = 0; - while (i < width) { + while ((nleft = width - i) > 0) { count = stbi__get8(s); if (count > 128) { // Run value = stbi__get8(s); count -= 128; + if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } for (z = 0; z < count; ++z) scanline[i++ * 4 + k] = value; } else { // Dump + if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } for (z = 0; z < count; ++z) scanline[i++ * 4 + k] = stbi__get8(s); } @@ -6005,7 +7278,8 @@ static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int re for (i=0; i < width; ++i) stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp); } - STBI_FREE(scanline); + if (scanline) + STBI_FREE(scanline); } return hdr_data; @@ -6016,8 +7290,13 @@ static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp) char buffer[STBI__HDR_BUFLEN]; char *token; int valid = 0; + int dummy; - if (strcmp(stbi__hdr_gettoken(s,buffer), "#?RADIANCE") != 0) { + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + if (stbi__hdr_test(s) == 0) { stbi__rewind( s ); return 0; } @@ -6054,29 +7333,23 @@ static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp) #ifndef STBI_NO_BMP static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp) { - int hsz; - if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') { - stbi__rewind( s ); - return 0; + void *p; + stbi__bmp_data info; + + info.all_a = 255; + p = stbi__bmp_parse_header(s, &info); + if (p == NULL) { + stbi__rewind( s ); + return 0; } - stbi__skip(s,12); - hsz = stbi__get32le(s); - if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) { - stbi__rewind( s ); - return 0; + if (x) *x = s->img_x; + if (y) *y = s->img_y; + if (comp) { + if (info.bpp == 24 && info.ma == 0xff000000) + *comp = 3; + else + *comp = info.ma ? 4 : 3; } - if (hsz == 12) { - *x = stbi__get16le(s); - *y = stbi__get16le(s); - } else { - *x = stbi__get32le(s); - *y = stbi__get32le(s); - } - if (stbi__get16le(s) != 1) { - stbi__rewind( s ); - return 0; - } - *comp = stbi__get16le(s) / 8; return 1; } #endif @@ -6084,7 +7357,10 @@ static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp) #ifndef STBI_NO_PSD static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) { - int channelCount; + int channelCount, dummy, depth; + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; if (stbi__get32be(s) != 0x38425053) { stbi__rewind( s ); return 0; @@ -6101,7 +7377,8 @@ static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) } *y = stbi__get32be(s); *x = stbi__get32be(s); - if (stbi__get16be(s) != 8) { + depth = stbi__get16be(s); + if (depth != 8 && depth != 16) { stbi__rewind( s ); return 0; } @@ -6112,14 +7389,45 @@ static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) *comp = 4; return 1; } + +static int stbi__psd_is16(stbi__context *s) +{ + int channelCount, depth; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind( s ); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind( s ); + return 0; + } + STBI_NOTUSED(stbi__get32be(s)); + STBI_NOTUSED(stbi__get32be(s)); + depth = stbi__get16be(s); + if (depth != 16) { + stbi__rewind( s ); + return 0; + } + return 1; +} #endif #ifndef STBI_NO_PIC static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp) { - int act_comp=0,num_packets=0,chained; + int act_comp=0,num_packets=0,chained,dummy; stbi__pic_packet packets[10]; + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) { stbi__rewind(s); return 0; @@ -6179,7 +7487,6 @@ static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp) // Known limitations: // Does not support comments in the header section // Does not support ASCII image data (formats P2 and P3) -// Does not support 16-bit-per-channel #ifndef STBI_NO_PNM @@ -6195,21 +7502,38 @@ static int stbi__pnm_test(stbi__context *s) return 1; } -static stbi_uc *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { stbi_uc *out; - if (!stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n)) + STBI_NOTUSED(ri); + + ri->bits_per_channel = stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n); + if (ri->bits_per_channel == 0) return 0; + + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + *x = s->img_x; *y = s->img_y; - *comp = s->img_n; + if (comp) *comp = s->img_n; - out = (stbi_uc *) stbi__malloc(s->img_n * s->img_x * s->img_y); + if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0)) + return stbi__errpuc("too large", "PNM too large"); + + out = (stbi_uc *) stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0); if (!out) return stbi__errpuc("outofmem", "Out of memory"); - stbi__getn(s, out, s->img_n * s->img_x * s->img_y); + if (!stbi__getn(s, out, s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8))) { + STBI_FREE(out); + return stbi__errpuc("bad PNM", "PNM file truncated"); + } if (req_comp && req_comp != s->img_n) { - out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); + if (ri->bits_per_channel == 16) { + out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, s->img_n, req_comp, s->img_x, s->img_y); + } else { + out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); + } if (out == NULL) return out; // stbi__convert_format frees input on failure } return out; @@ -6222,8 +7546,16 @@ static int stbi__pnm_isspace(char c) static void stbi__pnm_skip_whitespace(stbi__context *s, char *c) { - while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) - *c = (char) stbi__get8(s); + for (;;) { + while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) + *c = (char) stbi__get8(s); + + if (stbi__at_eof(s) || *c != '#') + break; + + while (!stbi__at_eof(s) && *c != '\n' && *c != '\r' ) + *c = (char) stbi__get8(s); + } } static int stbi__pnm_isdigit(char c) @@ -6238,6 +7570,8 @@ static int stbi__pnm_getinteger(stbi__context *s, char *c) while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) { value = value*10 + (*c - '0'); *c = (char) stbi__get8(s); + if((value > 214748364) || (value == 214748364 && *c > '7')) + return stbi__err("integer parse overflow", "Parsing an integer in the PPM header overflowed a 32-bit int"); } return value; @@ -6245,16 +7579,20 @@ static int stbi__pnm_getinteger(stbi__context *s, char *c) static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp) { - int maxv; + int maxv, dummy; char c, p, t; - stbi__rewind( s ); + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + stbi__rewind(s); // Get identifier p = (char) stbi__get8(s); t = (char) stbi__get8(s); if (p != 'P' || (t != '5' && t != '6')) { - stbi__rewind( s ); + stbi__rewind(s); return 0; } @@ -6264,17 +7602,29 @@ static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp) stbi__pnm_skip_whitespace(s, &c); *x = stbi__pnm_getinteger(s, &c); // read width + if(*x == 0) + return stbi__err("invalid width", "PPM image header had zero or overflowing width"); stbi__pnm_skip_whitespace(s, &c); *y = stbi__pnm_getinteger(s, &c); // read height + if (*y == 0) + return stbi__err("invalid width", "PPM image header had zero or overflowing width"); stbi__pnm_skip_whitespace(s, &c); maxv = stbi__pnm_getinteger(s, &c); // read max value - - if (maxv > 255) - return stbi__err("max value > 255", "PPM image not 8-bit"); + if (maxv > 65535) + return stbi__err("max value > 65535", "PPM image supports only 8-bit and 16-bit images"); + else if (maxv > 255) + return 16; else - return 1; + return 8; +} + +static int stbi__pnm_is16(stbi__context *s) +{ + if (stbi__pnm_info(s, NULL, NULL, NULL) == 16) + return 1; + return 0; } #endif @@ -6320,6 +7670,22 @@ static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp) return stbi__err("unknown image type", "Image not of any known type, or corrupt"); } +static int stbi__is_16_main(stbi__context *s) +{ + #ifndef STBI_NO_PNG + if (stbi__png_is16(s)) return 1; + #endif + + #ifndef STBI_NO_PSD + if (stbi__psd_is16(s)) return 1; + #endif + + #ifndef STBI_NO_PNM + if (stbi__pnm_is16(s)) return 1; + #endif + return 0; +} + #ifndef STBI_NO_STDIO STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp) { @@ -6341,6 +7707,27 @@ STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp) fseek(f,pos,SEEK_SET); return r; } + +STBIDEF int stbi_is_16_bit(char const *filename) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result; + if (!f) return stbi__err("can't fopen", "Unable to open file"); + result = stbi_is_16_bit_from_file(f); + fclose(f); + return result; +} + +STBIDEF int stbi_is_16_bit_from_file(FILE *f) +{ + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__is_16_main(&s); + fseek(f,pos,SEEK_SET); + return r; +} #endif // !STBI_NO_STDIO STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp) @@ -6357,14 +7744,62 @@ STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int return stbi__info_main(&s,x,y,comp); } +STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__is_16_main(&s); +} + +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); + return stbi__is_16_main(&s); +} + #endif // STB_IMAGE_IMPLEMENTATION /* revision history: + 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs + 2.19 (2018-02-11) fix warning + 2.18 (2018-01-30) fix warnings + 2.17 (2018-01-29) change sbti__shiftsigned to avoid clang -O2 bug + 1-bit BMP + *_is_16_bit api + avoid warnings + 2.16 (2017-07-23) all functions have 16-bit variants; + STBI_NO_STDIO works again; + compilation fixes; + fix rounding in unpremultiply; + optimize vertical flip; + disable raw_len validation; + documentation fixes + 2.15 (2017-03-18) fix png-1,2,4 bug; now all Imagenet JPGs decode; + warning fixes; disable run-time SSE detection on gcc; + uniform handling of optional "return" values; + thread-safe initialization of zlib tables + 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs + 2.13 (2016-11-29) add 16-bit API, only supported for PNG right now + 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes + 2.11 (2016-04-02) allocate large structures on the stack + remove white matting for transparent PSD + fix reported channel count for PNG & BMP + re-enable SSE2 in non-gcc 64-bit + support RGB-formatted JPEG + read 16-bit PNGs (only as 8-bit) + 2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED + 2.09 (2016-01-16) allow comments in PNM files + 16-bit-per-pixel TGA (not bit-per-component) + info() for TGA could break due to .hdr handling + info() for BMP to shares code instead of sloppy parse + can use STBI_REALLOC_SIZED if allocator doesn't support realloc + code cleanup 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA 2.07 (2015-09-13) fix compiler warnings partial animated GIF support - limited 16-bit PSD support + limited 16-bpc PSD support #ifdef unused functions bug with < 92 byte PIC,PNM,HDR,TGA 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value @@ -6429,7 +7864,7 @@ STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int 1.31 (2011-06-20) a few more leak fixes, bug in PNG handling (SpartanJ) 1.30 (2011-06-11) - added ability to load files via callbacks to accommodate custom input streams (Ben Wenger) + added ability to load files via callbacks to accomidate custom input streams (Ben Wenger) removed deprecated format-specific test/load functions removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha) @@ -6507,3 +7942,46 @@ STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int 0.50 (2006-11-19) first released version */ + + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/ From 2e918ed0049040376a2d8378f6ebd1883e0a1e17 Mon Sep 17 00:00:00 2001 From: Cameron Cawley Date: Thu, 16 Nov 2023 19:41:27 +0000 Subject: [PATCH 064/106] Build more demos with CI --- .github/workflows/ccpp.yml | 36 ++++++++++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ccpp.yml b/.github/workflows/ccpp.yml index d935f11..7f0d268 100644 --- a/.github/workflows/ccpp.yml +++ b/.github/workflows/ccpp.yml @@ -11,11 +11,39 @@ jobs: - uses: actions/checkout@v1 - name: apt-update run: sudo apt-get update -qq - - name: apt get glfw - run: sudo apt-get install -y --no-install-recommends libglfw3 libglfw3-dev libglew-dev - - name: build opengl2 + - name: apt get demo-libs + run: sudo apt-get install -y --no-install-recommends liballegro5-dev liballegro-image5-dev liballegro-ttf5-dev libglfw3 libglfw3-dev libglew-dev libsdl2-dev libwayland-dev libx11-dev libxft-dev wayland-protocols + - name: build allegro5 + run: make -C demo/allegro5 + - name: build glfw_opengl2 run: make -C demo/glfw_opengl2 - - name: build opengl3 + - name: build glfw_opengl3 run: make -C demo/glfw_opengl3 + - name: build glfw_opengl4 + run: make -C demo/glfw_opengl4 +# - name: build glfw_vulkan +# run: make -C demo/glfw_vulkan + - name: build sdl_opengl2 + run: make -C demo/sdl_opengl2 + - name: build sdl_opengl3 + run: make -C demo/sdl_opengl3 + - name: build sdl_opengles2 + run: make -C demo/sdl_opengles2 + - name: build sdl_renderer + run: make -C demo/sdl_renderer + - name: build sdl2surface_rawfb + run: make -C demo/sdl2surface_rawfb + - name: build wayland_rawfb + run: make -C demo/wayland_rawfb + - name: build x11 + run: make -C demo/x11 + - name: build x11_opengl2 + run: make -C demo/x11_opengl2 + - name: build x11_opengl3 + run: make -C demo/x11_opengl3 + - name: build x11_rawfb + run: make -C demo/x11_rawfb + - name: build x11_xft + run: make -C demo/x11_xft - name: build example run: make -C example From df13a41ada98e6204e40c8d372d5f5567c201515 Mon Sep 17 00:00:00 2001 From: Jacob Ahnstedt Date: Mon, 20 Nov 2023 13:56:19 +0100 Subject: [PATCH 065/106] Fixed C90 compliance issue --- nuklear.h | 6 +++--- src/nuklear_edit.c | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/nuklear.h b/nuklear.h index 314daa4..5c45145 100644 --- a/nuklear.h +++ b/nuklear.h @@ -27190,14 +27190,14 @@ nk_edit_draw_text(struct nk_command_buffer *out, float line_offset = 0; int line_count = 0; - foreground = nk_rgb_factor(foreground, style->color_factor); - background = nk_rgb_factor(background, style->color_factor); - struct nk_text txt; txt.padding = nk_vec2(0,0); txt.background = background; txt.text = foreground; + foreground = nk_rgb_factor(foreground, style->color_factor); + background = nk_rgb_factor(background, style->color_factor); + glyph_len = nk_utf_decode(text+text_len, &unicode, byte_len-text_len); if (!glyph_len) return; while ((text_len < byte_len) && glyph_len) diff --git a/src/nuklear_edit.c b/src/nuklear_edit.c index 4157dd8..a7b2bfc 100644 --- a/src/nuklear_edit.c +++ b/src/nuklear_edit.c @@ -89,14 +89,14 @@ nk_edit_draw_text(struct nk_command_buffer *out, float line_offset = 0; int line_count = 0; - foreground = nk_rgb_factor(foreground, style->color_factor); - background = nk_rgb_factor(background, style->color_factor); - struct nk_text txt; txt.padding = nk_vec2(0,0); txt.background = background; txt.text = foreground; + foreground = nk_rgb_factor(foreground, style->color_factor); + background = nk_rgb_factor(background, style->color_factor); + glyph_len = nk_utf_decode(text+text_len, &unicode, byte_len-text_len); if (!glyph_len) return; while ((text_len < byte_len) && glyph_len) From 304856e71eba639a1e1088a07da9409ac61658e8 Mon Sep 17 00:00:00 2001 From: Jacob Ahnstedt Date: Mon, 20 Nov 2023 13:57:45 +0100 Subject: [PATCH 066/106] Made disable widget example run on more types of widgets --- demo/common/overview.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/demo/common/overview.c b/demo/common/overview.c index 5822144..02b69bd 100644 --- a/demo/common/overview.c +++ b/demo/common/overview.c @@ -12,6 +12,8 @@ overview(struct nk_context *ctx) ctx->style.window.header.align = header_align; + static nk_bool disable_widgets = nk_false; + actual_window_flags = window_flags; if (!(actual_window_flags & NK_WINDOW_TITLE)) actual_window_flags &= ~(NK_WINDOW_MINIMIZABLE|NK_WINDOW_CLOSABLE); @@ -129,14 +131,19 @@ overview(struct nk_context *ctx) nk_checkbox_flags_label(ctx, "No Scrollbar", &window_flags, NK_WINDOW_NO_SCROLLBAR); nk_checkbox_flags_label(ctx, "Minimizable", &window_flags, NK_WINDOW_MINIMIZABLE); nk_checkbox_flags_label(ctx, "Scale Left", &window_flags, NK_WINDOW_SCALE_LEFT); + nk_checkbox_label(ctx, "Disable widgets", &disable_widgets); nk_tree_pop(ctx); } + if (disable_widgets) + nk_widget_disable_begin(ctx); + if (nk_tree_push(ctx, NK_TREE_TAB, "Widgets", NK_MINIMIZED)) { enum options {A,B,C}; static int checkbox; static int option; + if (nk_tree_push(ctx, NK_TREE_NODE, "Text", NK_MINIMIZED)) { /* Text Widgets */ @@ -1283,6 +1290,8 @@ overview(struct nk_context *ctx) } nk_tree_pop(ctx); } + if (disable_widgets) + nk_widget_disable_end(ctx); } nk_end(ctx); return !nk_window_is_closed(ctx, "Overview"); From afbd13391495efce07000998394df035ef1c2387 Mon Sep 17 00:00:00 2001 From: Jacob Ahnstedt Date: Mon, 20 Nov 2023 14:01:22 +0100 Subject: [PATCH 067/106] Fixed missing color factoring for widget disabling --- nuklear.h | 9 +++++---- src/nuklear_tree.c | 9 +++++---- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/nuklear.h b/nuklear.h index 5c45145..88ecccf 100644 --- a/nuklear.h +++ b/nuklear.h @@ -22673,15 +22673,16 @@ nk_tree_element_image_push_hashed_base(struct nk_context *ctx, enum nk_tree_type switch (background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, header, &background->data.image, nk_white); + nk_draw_image(out, header, &background->data.image, nk_rgb_factor(nk_white, style->tab.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, header, &background->data.slice, nk_white); + nk_draw_nine_slice(out, header, &background->data.slice, nk_rgb_factor(nk_white, style->tab.color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, header, 0, style->tab.border_color); + nk_fill_rect(out, header, 0, nk_rgb_factor(style->tab.border_color, style->tab.color_factor)); nk_fill_rect(out, nk_shrink_rect(header, style->tab.border), - style->tab.rounding, background->data.color); + style->tab.rounding, nk_rgb_factor(background->data.color, style->tab.color_factor)); + break; } } diff --git a/src/nuklear_tree.c b/src/nuklear_tree.c index 8ecc8c3..0ccf68e 100644 --- a/src/nuklear_tree.c +++ b/src/nuklear_tree.c @@ -242,15 +242,16 @@ nk_tree_element_image_push_hashed_base(struct nk_context *ctx, enum nk_tree_type switch (background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, header, &background->data.image, nk_white); + nk_draw_image(out, header, &background->data.image, nk_rgb_factor(nk_white, style->tab.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, header, &background->data.slice, nk_white); + nk_draw_nine_slice(out, header, &background->data.slice, nk_rgb_factor(nk_white, style->tab.color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, header, 0, style->tab.border_color); + nk_fill_rect(out, header, 0, nk_rgb_factor(style->tab.border_color, style->tab.color_factor)); nk_fill_rect(out, nk_shrink_rect(header, style->tab.border), - style->tab.rounding, background->data.color); + style->tab.rounding, nk_rgb_factor(background->data.color, style->tab.color_factor)); + break; } } From 39e2ee3ce4ccaef3f41319028261c23780eae7ac Mon Sep 17 00:00:00 2001 From: Jacob Ahnstedt Date: Mon, 20 Nov 2023 14:02:12 +0100 Subject: [PATCH 068/106] Removed color factoring for item colored selectables --- nuklear.h | 2 +- src/nuklear_selectable.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nuklear.h b/nuklear.h index 88ecccf..583dc03 100644 --- a/nuklear.h +++ b/nuklear.h @@ -25062,7 +25062,7 @@ nk_draw_selectable(struct nk_command_buffer *out, break; case NK_STYLE_ITEM_COLOR: text.background = background->data.color; - nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); + nk_fill_rect(out, *bounds, style->rounding, background->data.color); break; } if (icon) { diff --git a/src/nuklear_selectable.c b/src/nuklear_selectable.c index 3f4bfc4..1b8c0b2 100644 --- a/src/nuklear_selectable.c +++ b/src/nuklear_selectable.c @@ -56,7 +56,7 @@ nk_draw_selectable(struct nk_command_buffer *out, break; case NK_STYLE_ITEM_COLOR: text.background = background->data.color; - nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); + nk_fill_rect(out, *bounds, style->rounding, background->data.color); break; } if (icon) { From f187c39283c6b2abc89faf47808836df191c52b6 Mon Sep 17 00:00:00 2001 From: Jacob Ahnstedt Date: Fri, 24 Nov 2023 16:24:20 +0100 Subject: [PATCH 069/106] Added checkbox alignment right --- demo/common/overview.c | 42 ++++++++--------- nuklear.h | 105 ++++++++++++++++++++++++++--------------- src/nuklear.h | 31 ++++++++---- src/nuklear_internal.h | 4 +- src/nuklear_toggle.c | 70 ++++++++++++++++----------- 5 files changed, 155 insertions(+), 97 deletions(-) diff --git a/demo/common/overview.c b/demo/common/overview.c index ab66c84..8c7972c 100644 --- a/demo/common/overview.c +++ b/demo/common/overview.c @@ -41,7 +41,7 @@ overview(struct nk_context *ctx) show_app_about = nk_true; nk_progress(ctx, &prog, 100, NK_MODIFIABLE); nk_slider_int(ctx, 0, &slider, 16, 1); - nk_checkbox_label(ctx, "check", &check); + nk_checkbox_label(ctx, "check", &check, NK_WIDGET_LEFT); nk_menu_end(ctx); } /* menu #2 */ @@ -100,7 +100,7 @@ overview(struct nk_context *ctx) nk_layout_row_push(ctx, 70); nk_progress(ctx, &mprog, 100, NK_MODIFIABLE); nk_slider_int(ctx, 0, &mslider, 16, 1); - nk_checkbox_label(ctx, "check", &mcheck); + nk_checkbox_label(ctx, "check", &mcheck, NK_WIDGET_LEFT); nk_menubar_end(ctx); } @@ -121,14 +121,14 @@ overview(struct nk_context *ctx) /* window flags */ if (nk_tree_push(ctx, NK_TREE_TAB, "Window", NK_MINIMIZED)) { nk_layout_row_dynamic(ctx, 30, 2); - nk_checkbox_label(ctx, "Menu", &show_menu); - nk_checkbox_flags_label(ctx, "Titlebar", &window_flags, NK_WINDOW_TITLE); - nk_checkbox_flags_label(ctx, "Border", &window_flags, NK_WINDOW_BORDER); - nk_checkbox_flags_label(ctx, "Resizable", &window_flags, NK_WINDOW_SCALABLE); - nk_checkbox_flags_label(ctx, "Movable", &window_flags, NK_WINDOW_MOVABLE); - nk_checkbox_flags_label(ctx, "No Scrollbar", &window_flags, NK_WINDOW_NO_SCROLLBAR); - nk_checkbox_flags_label(ctx, "Minimizable", &window_flags, NK_WINDOW_MINIMIZABLE); - nk_checkbox_flags_label(ctx, "Scale Left", &window_flags, NK_WINDOW_SCALE_LEFT); + nk_checkbox_label(ctx, "Menu", &show_menu, NK_WIDGET_LEFT); + nk_checkbox_flags_label(ctx, "Titlebar", &window_flags, NK_WINDOW_TITLE, NK_WIDGET_LEFT); + nk_checkbox_flags_label(ctx, "Border", &window_flags, NK_WINDOW_BORDER, NK_WIDGET_LEFT); + nk_checkbox_flags_label(ctx, "Resizable", &window_flags, NK_WINDOW_SCALABLE, NK_WIDGET_LEFT); + nk_checkbox_flags_label(ctx, "Movable", &window_flags, NK_WINDOW_MOVABLE, NK_WIDGET_LEFT); + nk_checkbox_flags_label(ctx, "No Scrollbar", &window_flags, NK_WINDOW_NO_SCROLLBAR, NK_WIDGET_LEFT); + nk_checkbox_flags_label(ctx, "Minimizable", &window_flags, NK_WINDOW_MINIMIZABLE, NK_WIDGET_LEFT); + nk_checkbox_flags_label(ctx, "Scale Left", &window_flags, NK_WINDOW_SCALE_LEFT, NK_WIDGET_LEFT); nk_tree_pop(ctx); } @@ -201,8 +201,8 @@ overview(struct nk_context *ctx) static int range_int_max = 4096; static const float ratio[] = {120, 150}; - nk_layout_row_static(ctx, 30, 100, 1); - nk_checkbox_label(ctx, "Checkbox", &checkbox); + nk_layout_row_dynamic(ctx, 0, 1); + nk_checkbox_label(ctx, "HTESTH", &checkbox, NK_WIDGET_RIGHT); nk_layout_row_static(ctx, 30, 80, 3); option = nk_option_label(ctx, "optionA", option == A) ? A : option; @@ -244,7 +244,7 @@ overview(struct nk_context *ctx) { static int inactive = 1; nk_layout_row_dynamic(ctx, 30, 1); - nk_checkbox_label(ctx, "Inactive", &inactive); + nk_checkbox_label(ctx, "Inactive", &inactive, NK_WIDGET_LEFT); nk_layout_row_static(ctx, 30, 80, 1); if (inactive) { @@ -404,10 +404,10 @@ overview(struct nk_context *ctx) sprintf(buffer, "%lu", sum); if (nk_combo_begin_label(ctx, buffer, nk_vec2(200,200))) { nk_layout_row_dynamic(ctx, 30, 1); - nk_checkbox_label(ctx, weapons[0], &check_values[0]); - nk_checkbox_label(ctx, weapons[1], &check_values[1]); - nk_checkbox_label(ctx, weapons[2], &check_values[2]); - nk_checkbox_label(ctx, weapons[3], &check_values[3]); + nk_checkbox_label(ctx, weapons[0], &check_values[0], NK_WIDGET_LEFT); + nk_checkbox_label(ctx, weapons[1], &check_values[1], NK_WIDGET_LEFT); + nk_checkbox_label(ctx, weapons[2], &check_values[2], NK_WIDGET_LEFT); + nk_checkbox_label(ctx, weapons[3], &check_values[3], NK_WIDGET_LEFT); nk_combo_end(ctx); } @@ -716,7 +716,7 @@ overview(struct nk_context *ctx) static int slider = 10; nk_layout_row_dynamic(ctx, 25, 1); - nk_checkbox_label(ctx, "Menu", &show_menu); + nk_checkbox_label(ctx, "Menu", &show_menu, NK_WIDGET_LEFT); nk_progress(ctx, &prog, 100, NK_MODIFIABLE); nk_slider_int(ctx, 0, &slider, 16, 1); if (nk_contextual_item_label(ctx, "About", NK_TEXT_CENTERED)) @@ -883,9 +883,9 @@ overview(struct nk_context *ctx) if (group_titlebar) group_flags |= NK_WINDOW_TITLE; nk_layout_row_dynamic(ctx, 30, 3); - nk_checkbox_label(ctx, "Titlebar", &group_titlebar); - nk_checkbox_label(ctx, "Border", &group_border); - nk_checkbox_label(ctx, "No Scrollbar", &group_no_scrollbar); + nk_checkbox_label(ctx, "Titlebar", &group_titlebar, NK_WIDGET_LEFT); + nk_checkbox_label(ctx, "Border", &group_border, NK_WIDGET_LEFT); + nk_checkbox_label(ctx, "No Scrollbar", &group_no_scrollbar, NK_WIDGET_LEFT); nk_layout_row_begin(ctx, NK_STATIC, 22, 3); nk_layout_row_push(ctx, 50); diff --git a/nuklear.h b/nuklear.h index baac97f..7dfe23d 100644 --- a/nuklear.h +++ b/nuklear.h @@ -2290,6 +2290,21 @@ NK_API void nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, nk /// nk_layout_space_rect_to_screen | Converts rectangle from nk_layout_space coordinate space into screen space /// nk_layout_space_rect_to_local | Converts rectangle from screen space into nk_layout_space coordinates */ + +enum nk_widget_align { + NK_WIDGET_ALIGN_LEFT = 0x01, + NK_WIDGET_ALIGN_CENTERED = 0x02, + NK_WIDGET_ALIGN_RIGHT = 0x04, + NK_WIDGET_ALIGN_TOP = 0x08, + NK_WIDGET_ALIGN_MIDDLE = 0x10, + NK_WIDGET_ALIGN_BOTTOM = 0x20 +}; +enum nk_widget_alignment { + NK_WIDGET_LEFT = NK_WIDGET_ALIGN_MIDDLE|NK_WIDGET_ALIGN_LEFT, + NK_WIDGET_CENTERED = NK_WIDGET_ALIGN_MIDDLE|NK_WIDGET_ALIGN_CENTERED, + NK_WIDGET_RIGHT = NK_WIDGET_ALIGN_MIDDLE|NK_WIDGET_ALIGN_RIGHT +}; + /*/// #### nk_layout_set_min_row_height /// Sets the currently used minimum row height. /// !!! WARNING @@ -3187,14 +3202,14 @@ NK_API nk_bool nk_button_pop_behavior(struct nk_context*); * CHECKBOX * * ============================================================================= */ -NK_API nk_bool nk_check_label(struct nk_context*, const char*, nk_bool active); -NK_API nk_bool nk_check_text(struct nk_context*, const char*, int, nk_bool active); -NK_API unsigned nk_check_flags_label(struct nk_context*, const char*, unsigned int flags, unsigned int value); -NK_API unsigned nk_check_flags_text(struct nk_context*, const char*, int, unsigned int flags, unsigned int value); -NK_API nk_bool nk_checkbox_label(struct nk_context*, const char*, nk_bool *active); -NK_API nk_bool nk_checkbox_text(struct nk_context*, const char*, int, nk_bool *active); -NK_API nk_bool nk_checkbox_flags_label(struct nk_context*, const char*, unsigned int *flags, unsigned int value); -NK_API nk_bool nk_checkbox_flags_text(struct nk_context*, const char*, int, unsigned int *flags, unsigned int value); +NK_API nk_bool nk_check_label(struct nk_context*, const char*, nk_bool active, nk_flags alignment); +NK_API nk_bool nk_check_text(struct nk_context*, const char*, int, nk_bool active, nk_flags alignment); +NK_API unsigned nk_check_flags_label(struct nk_context*, const char*, unsigned int flags, unsigned int value, nk_flags alignment); +NK_API unsigned nk_check_flags_text(struct nk_context*, const char*, int, unsigned int flags, unsigned int value, nk_flags alignment); +NK_API nk_bool nk_checkbox_label(struct nk_context*, const char*, nk_bool *active, nk_flags alignment); +NK_API nk_bool nk_checkbox_text(struct nk_context*, const char*, int, nk_bool *active, nk_flags alignment); +NK_API nk_bool nk_checkbox_flags_label(struct nk_context*, const char*, unsigned int *flags, unsigned int value, nk_flags alignment); +NK_API nk_bool nk_checkbox_flags_text(struct nk_context*, const char*, int, unsigned int *flags, unsigned int value, nk_flags alignment); /* ============================================================================= * * RADIO BUTTON @@ -6030,9 +6045,9 @@ enum nk_toggle_type { NK_TOGGLE_OPTION }; NK_LIB nk_bool nk_toggle_behavior(const struct nk_input *in, struct nk_rect select, nk_flags *state, nk_bool active); -NK_LIB void nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font); +NK_LIB void nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags alignment); NK_LIB void nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font); -NK_LIB nk_bool nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, nk_bool *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, const struct nk_user_font *font); +NK_LIB nk_bool nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, nk_bool *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, const struct nk_user_font *font, nk_flags alignment); /* progress */ NK_LIB nk_size nk_progress_behavior(nk_flags *state, struct nk_input *in, struct nk_rect r, struct nk_rect cursor, nk_size max, nk_size value, nk_bool modifiable); @@ -24464,7 +24479,7 @@ nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, - const struct nk_user_font *font) + const struct nk_user_font *font, nk_flags alignment) { const struct nk_style_item *background; const struct nk_style_item *cursor; @@ -24485,6 +24500,11 @@ nk_draw_checkbox(struct nk_command_buffer *out, text.text = style->text_normal; } + text.padding.x = 0; + text.padding.y = 0; + text.background = style->text_background; + nk_widget_text(out, *label, string, len, &text, alignment, font); + /* draw background and cursor */ if (background->type == NK_STYLE_ITEM_COLOR) { nk_fill_rect(out, *selector, 0, style->border_color); @@ -24495,11 +24515,6 @@ nk_draw_checkbox(struct nk_command_buffer *out, nk_draw_image(out, *cursors, &cursor->data.image, nk_white); else nk_fill_rect(out, *cursors, 0, cursor->data.color); } - - text.padding.x = 0; - text.padding.y = 0; - text.background = style->text_background; - nk_widget_text(out, *label, string, len, &text, NK_TEXT_LEFT, font); } NK_LIB void nk_draw_option(struct nk_command_buffer *out, @@ -24548,9 +24563,10 @@ nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, nk_bool *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, - const struct nk_user_font *font) + const struct nk_user_font *font, nk_flags alignment) { int was_active; + struct nk_rect allocated_space; struct nk_rect bounds; struct nk_rect select; struct nk_rect cursor; @@ -24565,6 +24581,13 @@ nk_do_toggle(nk_flags *state, r.w = NK_MAX(r.w, font->height + 2 * style->padding.x); r.h = NK_MAX(r.h, font->height + 2 * style->padding.y); + allocated_space = r; + + if (alignment & NK_WIDGET_ALIGN_RIGHT) { + r.x = r.x + r.w - font->height - style->padding.x; + r.w = font->height; + } + /* add additional touch padding for touch screen devices */ bounds.x = r.x - style->touch_padding.x; bounds.y = r.y - style->touch_padding.y; @@ -24583,11 +24606,17 @@ nk_do_toggle(nk_flags *state, cursor.w = select.w - (2 * style->padding.x + 2 * style->border); cursor.h = select.h - (2 * style->padding.y + 2 * style->border); - /* label behind the selector */ - label.x = select.x + select.w + style->spacing; label.y = select.y; - label.w = NK_MAX(r.x + r.w, label.x) - label.x; label.h = select.w; + if (alignment & NK_WIDGET_ALIGN_LEFT) { + /* label behind the selector */ + label.x = select.x + select.w + style->spacing; + label.w = NK_MAX(r.x + r.w, label.x) - label.x; + } else { + /* label in front of the selector */ + label.x = allocated_space.x; + label.w = allocated_space.w - select.w - style->spacing * 2; + } /* update selector */ was_active = *active; @@ -24597,7 +24626,7 @@ nk_do_toggle(nk_flags *state, if (style->draw_begin) style->draw_begin(out, style->userdata); if (type == NK_TOGGLE_CHECK) { - nk_draw_checkbox(out, *state, style, *active, &label, &select, &cursor, str, len, font); + nk_draw_checkbox(out, *state, style, *active, &label, &select, &cursor, str, len, font, alignment); } else { nk_draw_option(out, *state, style, *active, &label, &select, &cursor, str, len, font); } @@ -24611,7 +24640,7 @@ nk_do_toggle(nk_flags *state, * * --------------------------------------------------------------*/ NK_API nk_bool -nk_check_text(struct nk_context *ctx, const char *text, int len, nk_bool active) +nk_check_text(struct nk_context *ctx, const char *text, int len, nk_bool active, nk_flags alignment) { struct nk_window *win; struct nk_panel *layout; @@ -24635,25 +24664,25 @@ nk_check_text(struct nk_context *ctx, const char *text, int len, nk_bool active) if (!state) return active; in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &active, - text, len, NK_TOGGLE_CHECK, &style->checkbox, in, style->font); + text, len, NK_TOGGLE_CHECK, &style->checkbox, in, style->font, alignment); return active; } NK_API unsigned int nk_check_flags_text(struct nk_context *ctx, const char *text, int len, - unsigned int flags, unsigned int value) + unsigned int flags, unsigned int value, nk_flags alignment) { int old_active; NK_ASSERT(ctx); NK_ASSERT(text); if (!ctx || !text) return flags; old_active = (int)((flags & value) & value); - if (nk_check_text(ctx, text, len, old_active)) + if (nk_check_text(ctx, text, len, old_active, alignment)) flags |= value; else flags &= ~value; return flags; } NK_API nk_bool -nk_checkbox_text(struct nk_context *ctx, const char *text, int len, nk_bool *active) +nk_checkbox_text(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags alignment) { int old_val; NK_ASSERT(ctx); @@ -24661,12 +24690,12 @@ nk_checkbox_text(struct nk_context *ctx, const char *text, int len, nk_bool *act NK_ASSERT(active); if (!ctx || !text || !active) return 0; old_val = *active; - *active = nk_check_text(ctx, text, len, *active); + *active = nk_check_text(ctx, text, len, *active, alignment); return old_val != *active; } NK_API nk_bool nk_checkbox_flags_text(struct nk_context *ctx, const char *text, int len, - unsigned int *flags, unsigned int value) + unsigned int *flags, unsigned int value, nk_flags alignment) { nk_bool active; NK_ASSERT(ctx); @@ -24675,30 +24704,30 @@ nk_checkbox_flags_text(struct nk_context *ctx, const char *text, int len, if (!ctx || !text || !flags) return 0; active = (int)((*flags & value) & value); - if (nk_checkbox_text(ctx, text, len, &active)) { + if (nk_checkbox_text(ctx, text, len, &active, alignment)) { if (active) *flags |= value; else *flags &= ~value; return 1; } return 0; } -NK_API nk_bool nk_check_label(struct nk_context *ctx, const char *label, nk_bool active) +NK_API nk_bool nk_check_label(struct nk_context *ctx, const char *label, nk_bool active, nk_flags alignment) { - return nk_check_text(ctx, label, nk_strlen(label), active); + return nk_check_text(ctx, label, nk_strlen(label), active, alignment); } NK_API unsigned int nk_check_flags_label(struct nk_context *ctx, const char *label, - unsigned int flags, unsigned int value) + unsigned int flags, unsigned int value, nk_flags alignment) { - return nk_check_flags_text(ctx, label, nk_strlen(label), flags, value); + return nk_check_flags_text(ctx, label, nk_strlen(label), flags, value, alignment); } -NK_API nk_bool nk_checkbox_label(struct nk_context *ctx, const char *label, nk_bool *active) +NK_API nk_bool nk_checkbox_label(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags alignment) { - return nk_checkbox_text(ctx, label, nk_strlen(label), active); + return nk_checkbox_text(ctx, label, nk_strlen(label), active, alignment); } NK_API nk_bool nk_checkbox_flags_label(struct nk_context *ctx, const char *label, - unsigned int *flags, unsigned int value) + unsigned int *flags, unsigned int value, nk_flags alignment) { - return nk_checkbox_flags_text(ctx, label, nk_strlen(label), flags, value); + return nk_checkbox_flags_text(ctx, label, nk_strlen(label), flags, value, alignment); } /*---------------------------------------------------------------- * @@ -24730,7 +24759,7 @@ nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_act if (!state) return (int)state; in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &is_active, - text, len, NK_TOGGLE_OPTION, &style->option, in, style->font); + text, len, NK_TOGGLE_OPTION, &style->option, in, style->font, NK_WIDGET_LEFT); return is_active; } NK_API nk_bool diff --git a/src/nuklear.h b/src/nuklear.h index 0b829c4..5527d04 100644 --- a/src/nuklear.h +++ b/src/nuklear.h @@ -2068,6 +2068,21 @@ NK_API void nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, nk /// nk_layout_space_rect_to_screen | Converts rectangle from nk_layout_space coordinate space into screen space /// nk_layout_space_rect_to_local | Converts rectangle from screen space into nk_layout_space coordinates */ + +enum nk_widget_align { + NK_WIDGET_ALIGN_LEFT = 0x01, + NK_WIDGET_ALIGN_CENTERED = 0x02, + NK_WIDGET_ALIGN_RIGHT = 0x04, + NK_WIDGET_ALIGN_TOP = 0x08, + NK_WIDGET_ALIGN_MIDDLE = 0x10, + NK_WIDGET_ALIGN_BOTTOM = 0x20 +}; +enum nk_widget_alignment { + NK_WIDGET_LEFT = NK_WIDGET_ALIGN_MIDDLE|NK_WIDGET_ALIGN_LEFT, + NK_WIDGET_CENTERED = NK_WIDGET_ALIGN_MIDDLE|NK_WIDGET_ALIGN_CENTERED, + NK_WIDGET_RIGHT = NK_WIDGET_ALIGN_MIDDLE|NK_WIDGET_ALIGN_RIGHT +}; + /*/// #### nk_layout_set_min_row_height /// Sets the currently used minimum row height. /// !!! WARNING @@ -2965,14 +2980,14 @@ NK_API nk_bool nk_button_pop_behavior(struct nk_context*); * CHECKBOX * * ============================================================================= */ -NK_API nk_bool nk_check_label(struct nk_context*, const char*, nk_bool active); -NK_API nk_bool nk_check_text(struct nk_context*, const char*, int, nk_bool active); -NK_API unsigned nk_check_flags_label(struct nk_context*, const char*, unsigned int flags, unsigned int value); -NK_API unsigned nk_check_flags_text(struct nk_context*, const char*, int, unsigned int flags, unsigned int value); -NK_API nk_bool nk_checkbox_label(struct nk_context*, const char*, nk_bool *active); -NK_API nk_bool nk_checkbox_text(struct nk_context*, const char*, int, nk_bool *active); -NK_API nk_bool nk_checkbox_flags_label(struct nk_context*, const char*, unsigned int *flags, unsigned int value); -NK_API nk_bool nk_checkbox_flags_text(struct nk_context*, const char*, int, unsigned int *flags, unsigned int value); +NK_API nk_bool nk_check_label(struct nk_context*, const char*, nk_bool active, nk_flags alignment); +NK_API nk_bool nk_check_text(struct nk_context*, const char*, int, nk_bool active, nk_flags alignment); +NK_API unsigned nk_check_flags_label(struct nk_context*, const char*, unsigned int flags, unsigned int value, nk_flags alignment); +NK_API unsigned nk_check_flags_text(struct nk_context*, const char*, int, unsigned int flags, unsigned int value, nk_flags alignment); +NK_API nk_bool nk_checkbox_label(struct nk_context*, const char*, nk_bool *active, nk_flags alignment); +NK_API nk_bool nk_checkbox_text(struct nk_context*, const char*, int, nk_bool *active, nk_flags alignment); +NK_API nk_bool nk_checkbox_flags_label(struct nk_context*, const char*, unsigned int *flags, unsigned int value, nk_flags alignment); +NK_API nk_bool nk_checkbox_flags_text(struct nk_context*, const char*, int, unsigned int *flags, unsigned int value, nk_flags alignment); /* ============================================================================= * * RADIO BUTTON diff --git a/src/nuklear_internal.h b/src/nuklear_internal.h index 4f71f30..f99a3bf 100644 --- a/src/nuklear_internal.h +++ b/src/nuklear_internal.h @@ -255,9 +255,9 @@ enum nk_toggle_type { NK_TOGGLE_OPTION }; NK_LIB nk_bool nk_toggle_behavior(const struct nk_input *in, struct nk_rect select, nk_flags *state, nk_bool active); -NK_LIB void nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font); +NK_LIB void nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags alignment); NK_LIB void nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font); -NK_LIB nk_bool nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, nk_bool *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, const struct nk_user_font *font); +NK_LIB nk_bool nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, nk_bool *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, const struct nk_user_font *font, nk_flags alignment); /* progress */ NK_LIB nk_size nk_progress_behavior(nk_flags *state, struct nk_input *in, struct nk_rect r, struct nk_rect cursor, nk_size max, nk_size value, nk_bool modifiable); diff --git a/src/nuklear_toggle.c b/src/nuklear_toggle.c index 0644a80..02e12b5 100644 --- a/src/nuklear_toggle.c +++ b/src/nuklear_toggle.c @@ -26,7 +26,7 @@ nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, - const struct nk_user_font *font) + const struct nk_user_font *font, nk_flags alignment) { const struct nk_style_item *background; const struct nk_style_item *cursor; @@ -47,6 +47,11 @@ nk_draw_checkbox(struct nk_command_buffer *out, text.text = style->text_normal; } + text.padding.x = 0; + text.padding.y = 0; + text.background = style->text_background; + nk_widget_text(out, *label, string, len, &text, alignment, font); + /* draw background and cursor */ if (background->type == NK_STYLE_ITEM_COLOR) { nk_fill_rect(out, *selector, 0, style->border_color); @@ -57,11 +62,6 @@ nk_draw_checkbox(struct nk_command_buffer *out, nk_draw_image(out, *cursors, &cursor->data.image, nk_white); else nk_fill_rect(out, *cursors, 0, cursor->data.color); } - - text.padding.x = 0; - text.padding.y = 0; - text.background = style->text_background; - nk_widget_text(out, *label, string, len, &text, NK_TEXT_LEFT, font); } NK_LIB void nk_draw_option(struct nk_command_buffer *out, @@ -110,9 +110,10 @@ nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, nk_bool *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, - const struct nk_user_font *font) + const struct nk_user_font *font, nk_flags alignment) { int was_active; + struct nk_rect allocated_space; struct nk_rect bounds; struct nk_rect select; struct nk_rect cursor; @@ -127,6 +128,13 @@ nk_do_toggle(nk_flags *state, r.w = NK_MAX(r.w, font->height + 2 * style->padding.x); r.h = NK_MAX(r.h, font->height + 2 * style->padding.y); + allocated_space = r; + + if (alignment & NK_WIDGET_ALIGN_RIGHT) { + r.x = r.x + r.w - font->height - style->padding.x; + r.w = font->height; + } + /* add additional touch padding for touch screen devices */ bounds.x = r.x - style->touch_padding.x; bounds.y = r.y - style->touch_padding.y; @@ -145,11 +153,17 @@ nk_do_toggle(nk_flags *state, cursor.w = select.w - (2 * style->padding.x + 2 * style->border); cursor.h = select.h - (2 * style->padding.y + 2 * style->border); - /* label behind the selector */ - label.x = select.x + select.w + style->spacing; label.y = select.y; - label.w = NK_MAX(r.x + r.w, label.x) - label.x; label.h = select.w; + if (alignment & NK_WIDGET_ALIGN_LEFT) { + /* label behind the selector */ + label.x = select.x + select.w + style->spacing; + label.w = NK_MAX(r.x + r.w, label.x) - label.x; + } else { + /* label in front of the selector */ + label.x = allocated_space.x; + label.w = allocated_space.w - select.w - style->spacing * 2; + } /* update selector */ was_active = *active; @@ -159,7 +173,7 @@ nk_do_toggle(nk_flags *state, if (style->draw_begin) style->draw_begin(out, style->userdata); if (type == NK_TOGGLE_CHECK) { - nk_draw_checkbox(out, *state, style, *active, &label, &select, &cursor, str, len, font); + nk_draw_checkbox(out, *state, style, *active, &label, &select, &cursor, str, len, font, alignment); } else { nk_draw_option(out, *state, style, *active, &label, &select, &cursor, str, len, font); } @@ -173,7 +187,7 @@ nk_do_toggle(nk_flags *state, * * --------------------------------------------------------------*/ NK_API nk_bool -nk_check_text(struct nk_context *ctx, const char *text, int len, nk_bool active) +nk_check_text(struct nk_context *ctx, const char *text, int len, nk_bool active, nk_flags alignment) { struct nk_window *win; struct nk_panel *layout; @@ -197,25 +211,25 @@ nk_check_text(struct nk_context *ctx, const char *text, int len, nk_bool active) if (!state) return active; in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &active, - text, len, NK_TOGGLE_CHECK, &style->checkbox, in, style->font); + text, len, NK_TOGGLE_CHECK, &style->checkbox, in, style->font, alignment); return active; } NK_API unsigned int nk_check_flags_text(struct nk_context *ctx, const char *text, int len, - unsigned int flags, unsigned int value) + unsigned int flags, unsigned int value, nk_flags alignment) { int old_active; NK_ASSERT(ctx); NK_ASSERT(text); if (!ctx || !text) return flags; old_active = (int)((flags & value) & value); - if (nk_check_text(ctx, text, len, old_active)) + if (nk_check_text(ctx, text, len, old_active, alignment)) flags |= value; else flags &= ~value; return flags; } NK_API nk_bool -nk_checkbox_text(struct nk_context *ctx, const char *text, int len, nk_bool *active) +nk_checkbox_text(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags alignment) { int old_val; NK_ASSERT(ctx); @@ -223,12 +237,12 @@ nk_checkbox_text(struct nk_context *ctx, const char *text, int len, nk_bool *act NK_ASSERT(active); if (!ctx || !text || !active) return 0; old_val = *active; - *active = nk_check_text(ctx, text, len, *active); + *active = nk_check_text(ctx, text, len, *active, alignment); return old_val != *active; } NK_API nk_bool nk_checkbox_flags_text(struct nk_context *ctx, const char *text, int len, - unsigned int *flags, unsigned int value) + unsigned int *flags, unsigned int value, nk_flags alignment) { nk_bool active; NK_ASSERT(ctx); @@ -237,30 +251,30 @@ nk_checkbox_flags_text(struct nk_context *ctx, const char *text, int len, if (!ctx || !text || !flags) return 0; active = (int)((*flags & value) & value); - if (nk_checkbox_text(ctx, text, len, &active)) { + if (nk_checkbox_text(ctx, text, len, &active, alignment)) { if (active) *flags |= value; else *flags &= ~value; return 1; } return 0; } -NK_API nk_bool nk_check_label(struct nk_context *ctx, const char *label, nk_bool active) +NK_API nk_bool nk_check_label(struct nk_context *ctx, const char *label, nk_bool active, nk_flags alignment) { - return nk_check_text(ctx, label, nk_strlen(label), active); + return nk_check_text(ctx, label, nk_strlen(label), active, alignment); } NK_API unsigned int nk_check_flags_label(struct nk_context *ctx, const char *label, - unsigned int flags, unsigned int value) + unsigned int flags, unsigned int value, nk_flags alignment) { - return nk_check_flags_text(ctx, label, nk_strlen(label), flags, value); + return nk_check_flags_text(ctx, label, nk_strlen(label), flags, value, alignment); } -NK_API nk_bool nk_checkbox_label(struct nk_context *ctx, const char *label, nk_bool *active) +NK_API nk_bool nk_checkbox_label(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags alignment) { - return nk_checkbox_text(ctx, label, nk_strlen(label), active); + return nk_checkbox_text(ctx, label, nk_strlen(label), active, alignment); } NK_API nk_bool nk_checkbox_flags_label(struct nk_context *ctx, const char *label, - unsigned int *flags, unsigned int value) + unsigned int *flags, unsigned int value, nk_flags alignment) { - return nk_checkbox_flags_text(ctx, label, nk_strlen(label), flags, value); + return nk_checkbox_flags_text(ctx, label, nk_strlen(label), flags, value, alignment); } /*---------------------------------------------------------------- * @@ -292,7 +306,7 @@ nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_act if (!state) return (int)state; in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &is_active, - text, len, NK_TOGGLE_OPTION, &style->option, in, style->font); + text, len, NK_TOGGLE_OPTION, &style->option, in, style->font, NK_WIDGET_LEFT); return is_active; } NK_API nk_bool From e782760da3e0cee98fe0e6211f556eb6ac9fa3aa Mon Sep 17 00:00:00 2001 From: Jacob Ahnstedt Date: Fri, 24 Nov 2023 16:33:16 +0100 Subject: [PATCH 070/106] Added option alignment right --- demo/common/overview.c | 15 ++++++++------- nuklear.h | 40 ++++++++++++++++++++-------------------- src/nuklear.h | 8 ++++---- src/nuklear_internal.h | 2 +- src/nuklear_toggle.c | 30 +++++++++++++++--------------- 5 files changed, 48 insertions(+), 47 deletions(-) diff --git a/demo/common/overview.c b/demo/common/overview.c index 8c7972c..fc6fff2 100644 --- a/demo/common/overview.c +++ b/demo/common/overview.c @@ -201,13 +201,14 @@ overview(struct nk_context *ctx) static int range_int_max = 4096; static const float ratio[] = {120, 150}; - nk_layout_row_dynamic(ctx, 0, 1); - nk_checkbox_label(ctx, "HTESTH", &checkbox, NK_WIDGET_RIGHT); + nk_layout_row_dynamic(ctx, 0, 2); + nk_checkbox_label(ctx, "Checkbox Left", &checkbox, NK_WIDGET_LEFT); + nk_checkbox_label(ctx, "Checkbox Right", &checkbox, NK_WIDGET_RIGHT); nk_layout_row_static(ctx, 30, 80, 3); - option = nk_option_label(ctx, "optionA", option == A) ? A : option; - option = nk_option_label(ctx, "optionB", option == B) ? B : option; - option = nk_option_label(ctx, "optionC", option == C) ? C : option; + option = nk_option_label(ctx, "optionA", option == A, NK_WIDGET_LEFT) ? A : option; + option = nk_option_label(ctx, "optionB", option == B, NK_WIDGET_LEFT) ? B : option; + option = nk_option_label(ctx, "optionC", option == C, NK_WIDGET_LEFT) ? C : option; nk_layout_row(ctx, NK_STATIC, 30, 2, ratio); nk_labelf(ctx, NK_TEXT_LEFT, "Slider int"); @@ -367,8 +368,8 @@ overview(struct nk_context *ctx) #endif nk_layout_row_dynamic(ctx, 25, 2); - col_mode = nk_option_label(ctx, "RGB", col_mode == COL_RGB) ? COL_RGB : col_mode; - col_mode = nk_option_label(ctx, "HSV", col_mode == COL_HSV) ? COL_HSV : col_mode; + col_mode = nk_option_label(ctx, "RGB", col_mode == COL_RGB, NK_WIDGET_LEFT) ? COL_RGB : col_mode; + col_mode = nk_option_label(ctx, "HSV", col_mode == COL_HSV, NK_WIDGET_LEFT) ? COL_HSV : col_mode; nk_layout_row_dynamic(ctx, 25, 1); if (col_mode == COL_RGB) { diff --git a/nuklear.h b/nuklear.h index 7dfe23d..5b76d43 100644 --- a/nuklear.h +++ b/nuklear.h @@ -3215,10 +3215,10 @@ NK_API nk_bool nk_checkbox_flags_text(struct nk_context*, const char*, int, unsi * RADIO BUTTON * * ============================================================================= */ -NK_API nk_bool nk_radio_label(struct nk_context*, const char*, nk_bool *active); -NK_API nk_bool nk_radio_text(struct nk_context*, const char*, int, nk_bool *active); -NK_API nk_bool nk_option_label(struct nk_context*, const char*, nk_bool active); -NK_API nk_bool nk_option_text(struct nk_context*, const char*, int, nk_bool active); +NK_API nk_bool nk_radio_label(struct nk_context*, const char*, nk_bool *active, nk_flags alignment); +NK_API nk_bool nk_radio_text(struct nk_context*, const char*, int, nk_bool *active, nk_flags alignment); +NK_API nk_bool nk_option_label(struct nk_context*, const char*, nk_bool active, nk_flags alignment); +NK_API nk_bool nk_option_text(struct nk_context*, const char*, int, nk_bool active, nk_flags alignment); /* ============================================================================= * * SELECTABLE @@ -6046,7 +6046,7 @@ enum nk_toggle_type { }; NK_LIB nk_bool nk_toggle_behavior(const struct nk_input *in, struct nk_rect select, nk_flags *state, nk_bool active); NK_LIB void nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags alignment); -NK_LIB void nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font); +NK_LIB void nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags alignment); NK_LIB nk_bool nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, nk_bool *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, const struct nk_user_font *font, nk_flags alignment); /* progress */ @@ -24521,7 +24521,7 @@ nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, - const struct nk_user_font *font) + const struct nk_user_font *font, nk_flags alignment) { const struct nk_style_item *background; const struct nk_style_item *cursor; @@ -24542,6 +24542,11 @@ nk_draw_option(struct nk_command_buffer *out, text.text = style->text_normal; } + text.padding.x = 0; + text.padding.y = 0; + text.background = style->text_background; + nk_widget_text(out, *label, string, len, &text, alignment, font); + /* draw background and cursor */ if (background->type == NK_STYLE_ITEM_COLOR) { nk_fill_circle(out, *selector, style->border_color); @@ -24552,11 +24557,6 @@ nk_draw_option(struct nk_command_buffer *out, nk_draw_image(out, *cursors, &cursor->data.image, nk_white); else nk_fill_circle(out, *cursors, cursor->data.color); } - - text.padding.x = 0; - text.padding.y = 0; - text.background = style->text_background; - nk_widget_text(out, *label, string, len, &text, NK_TEXT_LEFT, font); } NK_LIB nk_bool nk_do_toggle(nk_flags *state, @@ -24628,7 +24628,7 @@ nk_do_toggle(nk_flags *state, if (type == NK_TOGGLE_CHECK) { nk_draw_checkbox(out, *state, style, *active, &label, &select, &cursor, str, len, font, alignment); } else { - nk_draw_option(out, *state, style, *active, &label, &select, &cursor, str, len, font); + nk_draw_option(out, *state, style, *active, &label, &select, &cursor, str, len, font, alignment); } if (style->draw_end) style->draw_end(out, style->userdata); @@ -24735,7 +24735,7 @@ NK_API nk_bool nk_checkbox_flags_label(struct nk_context *ctx, const char *label * * --------------------------------------------------------------*/ NK_API nk_bool -nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_active) +nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_active, nk_flags alignment) { struct nk_window *win; struct nk_panel *layout; @@ -24759,11 +24759,11 @@ nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_act if (!state) return (int)state; in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &is_active, - text, len, NK_TOGGLE_OPTION, &style->option, in, style->font, NK_WIDGET_LEFT); + text, len, NK_TOGGLE_OPTION, &style->option, in, style->font, alignment); return is_active; } NK_API nk_bool -nk_radio_text(struct nk_context *ctx, const char *text, int len, nk_bool *active) +nk_radio_text(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags alignment) { int old_value; NK_ASSERT(ctx); @@ -24771,18 +24771,18 @@ nk_radio_text(struct nk_context *ctx, const char *text, int len, nk_bool *active NK_ASSERT(active); if (!ctx || !text || !active) return 0; old_value = *active; - *active = nk_option_text(ctx, text, len, old_value); + *active = nk_option_text(ctx, text, len, old_value, alignment); return old_value != *active; } NK_API nk_bool -nk_option_label(struct nk_context *ctx, const char *label, nk_bool active) +nk_option_label(struct nk_context *ctx, const char *label, nk_bool active, nk_flags alignment) { - return nk_option_text(ctx, label, nk_strlen(label), active); + return nk_option_text(ctx, label, nk_strlen(label), active, alignment); } NK_API nk_bool -nk_radio_label(struct nk_context *ctx, const char *label, nk_bool *active) +nk_radio_label(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags alignment) { - return nk_radio_text(ctx, label, nk_strlen(label), active); + return nk_radio_text(ctx, label, nk_strlen(label), active, alignment); } diff --git a/src/nuklear.h b/src/nuklear.h index 5527d04..bac3243 100644 --- a/src/nuklear.h +++ b/src/nuklear.h @@ -2993,10 +2993,10 @@ NK_API nk_bool nk_checkbox_flags_text(struct nk_context*, const char*, int, unsi * RADIO BUTTON * * ============================================================================= */ -NK_API nk_bool nk_radio_label(struct nk_context*, const char*, nk_bool *active); -NK_API nk_bool nk_radio_text(struct nk_context*, const char*, int, nk_bool *active); -NK_API nk_bool nk_option_label(struct nk_context*, const char*, nk_bool active); -NK_API nk_bool nk_option_text(struct nk_context*, const char*, int, nk_bool active); +NK_API nk_bool nk_radio_label(struct nk_context*, const char*, nk_bool *active, nk_flags alignment); +NK_API nk_bool nk_radio_text(struct nk_context*, const char*, int, nk_bool *active, nk_flags alignment); +NK_API nk_bool nk_option_label(struct nk_context*, const char*, nk_bool active, nk_flags alignment); +NK_API nk_bool nk_option_text(struct nk_context*, const char*, int, nk_bool active, nk_flags alignment); /* ============================================================================= * * SELECTABLE diff --git a/src/nuklear_internal.h b/src/nuklear_internal.h index f99a3bf..9f6a6dc 100644 --- a/src/nuklear_internal.h +++ b/src/nuklear_internal.h @@ -256,7 +256,7 @@ enum nk_toggle_type { }; NK_LIB nk_bool nk_toggle_behavior(const struct nk_input *in, struct nk_rect select, nk_flags *state, nk_bool active); NK_LIB void nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags alignment); -NK_LIB void nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font); +NK_LIB void nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags alignment); NK_LIB nk_bool nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, nk_bool *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, const struct nk_user_font *font, nk_flags alignment); /* progress */ diff --git a/src/nuklear_toggle.c b/src/nuklear_toggle.c index 02e12b5..ccf5a08 100644 --- a/src/nuklear_toggle.c +++ b/src/nuklear_toggle.c @@ -68,7 +68,7 @@ nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, - const struct nk_user_font *font) + const struct nk_user_font *font, nk_flags alignment) { const struct nk_style_item *background; const struct nk_style_item *cursor; @@ -89,6 +89,11 @@ nk_draw_option(struct nk_command_buffer *out, text.text = style->text_normal; } + text.padding.x = 0; + text.padding.y = 0; + text.background = style->text_background; + nk_widget_text(out, *label, string, len, &text, alignment, font); + /* draw background and cursor */ if (background->type == NK_STYLE_ITEM_COLOR) { nk_fill_circle(out, *selector, style->border_color); @@ -99,11 +104,6 @@ nk_draw_option(struct nk_command_buffer *out, nk_draw_image(out, *cursors, &cursor->data.image, nk_white); else nk_fill_circle(out, *cursors, cursor->data.color); } - - text.padding.x = 0; - text.padding.y = 0; - text.background = style->text_background; - nk_widget_text(out, *label, string, len, &text, NK_TEXT_LEFT, font); } NK_LIB nk_bool nk_do_toggle(nk_flags *state, @@ -175,7 +175,7 @@ nk_do_toggle(nk_flags *state, if (type == NK_TOGGLE_CHECK) { nk_draw_checkbox(out, *state, style, *active, &label, &select, &cursor, str, len, font, alignment); } else { - nk_draw_option(out, *state, style, *active, &label, &select, &cursor, str, len, font); + nk_draw_option(out, *state, style, *active, &label, &select, &cursor, str, len, font, alignment); } if (style->draw_end) style->draw_end(out, style->userdata); @@ -282,7 +282,7 @@ NK_API nk_bool nk_checkbox_flags_label(struct nk_context *ctx, const char *label * * --------------------------------------------------------------*/ NK_API nk_bool -nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_active) +nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_active, nk_flags alignment) { struct nk_window *win; struct nk_panel *layout; @@ -306,11 +306,11 @@ nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_act if (!state) return (int)state; in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &is_active, - text, len, NK_TOGGLE_OPTION, &style->option, in, style->font, NK_WIDGET_LEFT); + text, len, NK_TOGGLE_OPTION, &style->option, in, style->font, alignment); return is_active; } NK_API nk_bool -nk_radio_text(struct nk_context *ctx, const char *text, int len, nk_bool *active) +nk_radio_text(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags alignment) { int old_value; NK_ASSERT(ctx); @@ -318,17 +318,17 @@ nk_radio_text(struct nk_context *ctx, const char *text, int len, nk_bool *active NK_ASSERT(active); if (!ctx || !text || !active) return 0; old_value = *active; - *active = nk_option_text(ctx, text, len, old_value); + *active = nk_option_text(ctx, text, len, old_value, alignment); return old_value != *active; } NK_API nk_bool -nk_option_label(struct nk_context *ctx, const char *label, nk_bool active) +nk_option_label(struct nk_context *ctx, const char *label, nk_bool active, nk_flags alignment) { - return nk_option_text(ctx, label, nk_strlen(label), active); + return nk_option_text(ctx, label, nk_strlen(label), active, alignment); } NK_API nk_bool -nk_radio_label(struct nk_context *ctx, const char *label, nk_bool *active) +nk_radio_label(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags alignment) { - return nk_radio_text(ctx, label, nk_strlen(label), active); + return nk_radio_text(ctx, label, nk_strlen(label), active, alignment); } From 060dbf96410db76e03cb5183aa3ab6987984924e Mon Sep 17 00:00:00 2001 From: Jacob Ahnstedt Date: Fri, 24 Nov 2023 16:57:50 +0100 Subject: [PATCH 071/106] Fixed the overview example for option & checkbox alignment right --- demo/common/overview.c | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/demo/common/overview.c b/demo/common/overview.c index fc6fff2..d01cdf4 100644 --- a/demo/common/overview.c +++ b/demo/common/overview.c @@ -135,8 +135,10 @@ overview(struct nk_context *ctx) if (nk_tree_push(ctx, NK_TREE_TAB, "Widgets", NK_MINIMIZED)) { enum options {A,B,C}; - static int checkbox; - static int option; + static int checkbox_left; + static int checkbox_right; + static int option_left; + static int option_right; if (nk_tree_push(ctx, NK_TREE_NODE, "Text", NK_MINIMIZED)) { /* Text Widgets */ @@ -201,14 +203,19 @@ overview(struct nk_context *ctx) static int range_int_max = 4096; static const float ratio[] = {120, 150}; - nk_layout_row_dynamic(ctx, 0, 2); - nk_checkbox_label(ctx, "Checkbox Left", &checkbox, NK_WIDGET_LEFT); - nk_checkbox_label(ctx, "Checkbox Right", &checkbox, NK_WIDGET_RIGHT); + nk_layout_row_dynamic(ctx, 0, 1); + nk_checkbox_label(ctx, "Checkbox Left", &checkbox_left, NK_WIDGET_LEFT); + nk_checkbox_label(ctx, "Checkbox Right", &checkbox_right, NK_WIDGET_RIGHT); nk_layout_row_static(ctx, 30, 80, 3); - option = nk_option_label(ctx, "optionA", option == A, NK_WIDGET_LEFT) ? A : option; - option = nk_option_label(ctx, "optionB", option == B, NK_WIDGET_LEFT) ? B : option; - option = nk_option_label(ctx, "optionC", option == C, NK_WIDGET_LEFT) ? C : option; + option_left = nk_option_label(ctx, "optionA", option_left == A, NK_WIDGET_LEFT) ? A : option_left; + option_left = nk_option_label(ctx, "optionB", option_left == B, NK_WIDGET_LEFT) ? B : option_left; + option_left = nk_option_label(ctx, "optionC", option_left == C, NK_WIDGET_LEFT) ? C : option_left; + + nk_layout_row_static(ctx, 30, 80, 3); + option_right = nk_option_label(ctx, "optionA", option_right == A, NK_WIDGET_RIGHT) ? A : option_right; + option_right = nk_option_label(ctx, "optionB", option_right == B, NK_WIDGET_RIGHT) ? B : option_right; + option_right = nk_option_label(ctx, "optionC", option_right == C, NK_WIDGET_RIGHT) ? C : option_right; nk_layout_row(ctx, NK_STATIC, 30, 2, ratio); nk_labelf(ctx, NK_TEXT_LEFT, "Slider int"); From c5ee9a58ed065536c52b8af9d97fe63661f33546 Mon Sep 17 00:00:00 2001 From: Jacob Ahnstedt Date: Sun, 26 Nov 2023 10:25:36 +0100 Subject: [PATCH 072/106] Added text alignment to toggleables --- demo/common/overview.c | 68 ++++++++++++++------------- nuklear.h | 104 ++++++++++++++++++++--------------------- src/nuklear.h | 24 +++++----- src/nuklear_internal.h | 6 +-- src/nuklear_toggle.c | 74 ++++++++++++++--------------- 5 files changed, 140 insertions(+), 136 deletions(-) diff --git a/demo/common/overview.c b/demo/common/overview.c index 2907aa4..dff9796 100644 --- a/demo/common/overview.c +++ b/demo/common/overview.c @@ -43,7 +43,7 @@ overview(struct nk_context *ctx) show_app_about = nk_true; nk_progress(ctx, &prog, 100, NK_MODIFIABLE); nk_slider_int(ctx, 0, &slider, 16, 1); - nk_checkbox_label(ctx, "check", &check, NK_WIDGET_LEFT); + nk_checkbox_label(ctx, "check", &check, NK_WIDGET_LEFT, NK_TEXT_LEFT); nk_menu_end(ctx); } /* menu #2 */ @@ -102,7 +102,7 @@ overview(struct nk_context *ctx) nk_layout_row_push(ctx, 70); nk_progress(ctx, &mprog, 100, NK_MODIFIABLE); nk_slider_int(ctx, 0, &mslider, 16, 1); - nk_checkbox_label(ctx, "check", &mcheck, NK_WIDGET_LEFT); + nk_checkbox_label(ctx, "check", &mcheck, NK_WIDGET_LEFT, NK_TEXT_LEFT); nk_menubar_end(ctx); } @@ -123,15 +123,15 @@ overview(struct nk_context *ctx) /* window flags */ if (nk_tree_push(ctx, NK_TREE_TAB, "Window", NK_MINIMIZED)) { nk_layout_row_dynamic(ctx, 30, 2); - nk_checkbox_label(ctx, "Menu", &show_menu, NK_WIDGET_LEFT); - nk_checkbox_flags_label(ctx, "Titlebar", &window_flags, NK_WINDOW_TITLE, NK_WIDGET_LEFT); - nk_checkbox_flags_label(ctx, "Border", &window_flags, NK_WINDOW_BORDER, NK_WIDGET_LEFT); - nk_checkbox_flags_label(ctx, "Resizable", &window_flags, NK_WINDOW_SCALABLE, NK_WIDGET_LEFT); - nk_checkbox_flags_label(ctx, "Movable", &window_flags, NK_WINDOW_MOVABLE, NK_WIDGET_LEFT); - nk_checkbox_flags_label(ctx, "No Scrollbar", &window_flags, NK_WINDOW_NO_SCROLLBAR, NK_WIDGET_LEFT); - nk_checkbox_flags_label(ctx, "Minimizable", &window_flags, NK_WINDOW_MINIMIZABLE, NK_WIDGET_LEFT); - nk_checkbox_flags_label(ctx, "Scale Left", &window_flags, NK_WINDOW_SCALE_LEFT, NK_WIDGET_LEFT); - nk_checkbox_label(ctx, "Disable widgets", &disable_widgets, NK_WIDGET_LEFT); + nk_checkbox_label(ctx, "Menu", &show_menu, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_flags_label(ctx, "Titlebar", &window_flags, NK_WINDOW_TITLE, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_flags_label(ctx, "Border", &window_flags, NK_WINDOW_BORDER, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_flags_label(ctx, "Resizable", &window_flags, NK_WINDOW_SCALABLE, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_flags_label(ctx, "Movable", &window_flags, NK_WINDOW_MOVABLE, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_flags_label(ctx, "No Scrollbar", &window_flags, NK_WINDOW_NO_SCROLLBAR, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_flags_label(ctx, "Minimizable", &window_flags, NK_WINDOW_MINIMIZABLE, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_flags_label(ctx, "Scale Left", &window_flags, NK_WINDOW_SCALE_LEFT, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_label(ctx, "Disable widgets", &disable_widgets, NK_WIDGET_LEFT, NK_TEXT_LEFT); nk_tree_pop(ctx); } @@ -141,8 +141,10 @@ overview(struct nk_context *ctx) if (nk_tree_push(ctx, NK_TREE_TAB, "Widgets", NK_MINIMIZED)) { enum options {A,B,C}; - static int checkbox_left; - static int checkbox_right; + static int checkbox_left_text_left; + static int checkbox_left_text_right; + static int checkbox_right_text_right; + static int checkbox_right_text_left; static int option_left; static int option_right; if (nk_tree_push(ctx, NK_TREE_NODE, "Text", NK_MINIMIZED)) @@ -211,18 +213,20 @@ overview(struct nk_context *ctx) static const float ratio[] = {120, 150}; nk_layout_row_dynamic(ctx, 0, 1); - nk_checkbox_label(ctx, "Checkbox Left", &checkbox_left, NK_WIDGET_LEFT); - nk_checkbox_label(ctx, "Checkbox Right", &checkbox_right, NK_WIDGET_RIGHT); + nk_checkbox_label(ctx, "Checkbox Left Text Left", &checkbox_left_text_left, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_label(ctx, "Checkbox Left Text Right", &checkbox_left_text_right, NK_WIDGET_LEFT, NK_TEXT_RIGHT); + nk_checkbox_label(ctx, "Checkbox Right Text Right", &checkbox_right_text_right, NK_WIDGET_RIGHT, NK_TEXT_RIGHT); + nk_checkbox_label(ctx, "Checkbox Right Text Left", &checkbox_right_text_left, NK_WIDGET_RIGHT, NK_TEXT_LEFT); nk_layout_row_static(ctx, 30, 80, 3); - option_left = nk_option_label(ctx, "optionA", option_left == A, NK_WIDGET_LEFT) ? A : option_left; - option_left = nk_option_label(ctx, "optionB", option_left == B, NK_WIDGET_LEFT) ? B : option_left; - option_left = nk_option_label(ctx, "optionC", option_left == C, NK_WIDGET_LEFT) ? C : option_left; + option_left = nk_option_label(ctx, "optionA", option_left == A, NK_WIDGET_LEFT, NK_TEXT_LEFT) ? A : option_left; + option_left = nk_option_label(ctx, "optionB", option_left == B, NK_WIDGET_LEFT, NK_TEXT_LEFT) ? B : option_left; + option_left = nk_option_label(ctx, "optionC", option_left == C, NK_WIDGET_LEFT, NK_TEXT_LEFT) ? C : option_left; nk_layout_row_static(ctx, 30, 80, 3); - option_right = nk_option_label(ctx, "optionA", option_right == A, NK_WIDGET_RIGHT) ? A : option_right; - option_right = nk_option_label(ctx, "optionB", option_right == B, NK_WIDGET_RIGHT) ? B : option_right; - option_right = nk_option_label(ctx, "optionC", option_right == C, NK_WIDGET_RIGHT) ? C : option_right; + option_right = nk_option_label(ctx, "optionA", option_right == A, NK_WIDGET_RIGHT, NK_TEXT_RIGHT) ? A : option_right; + option_right = nk_option_label(ctx, "optionB", option_right == B, NK_WIDGET_RIGHT, NK_TEXT_RIGHT) ? B : option_right; + option_right = nk_option_label(ctx, "optionC", option_right == C, NK_WIDGET_RIGHT, NK_TEXT_RIGHT) ? C : option_right; nk_layout_row(ctx, NK_STATIC, 30, 2, ratio); nk_labelf(ctx, NK_TEXT_LEFT, "Slider int"); @@ -259,7 +263,7 @@ overview(struct nk_context *ctx) { static int inactive = 1; nk_layout_row_dynamic(ctx, 30, 1); - nk_checkbox_label(ctx, "Inactive", &inactive, NK_WIDGET_LEFT); + nk_checkbox_label(ctx, "Inactive", &inactive, NK_WIDGET_LEFT, NK_TEXT_LEFT); nk_layout_row_static(ctx, 30, 80, 1); if (inactive) { @@ -375,8 +379,8 @@ overview(struct nk_context *ctx) #endif nk_layout_row_dynamic(ctx, 25, 2); - col_mode = nk_option_label(ctx, "RGB", col_mode == COL_RGB, NK_WIDGET_LEFT) ? COL_RGB : col_mode; - col_mode = nk_option_label(ctx, "HSV", col_mode == COL_HSV, NK_WIDGET_LEFT) ? COL_HSV : col_mode; + col_mode = nk_option_label(ctx, "RGB", col_mode == COL_RGB, NK_WIDGET_LEFT, NK_TEXT_LEFT) ? COL_RGB : col_mode; + col_mode = nk_option_label(ctx, "HSV", col_mode == COL_HSV, NK_WIDGET_LEFT, NK_TEXT_LEFT) ? COL_HSV : col_mode; nk_layout_row_dynamic(ctx, 25, 1); if (col_mode == COL_RGB) { @@ -412,10 +416,10 @@ overview(struct nk_context *ctx) sprintf(buffer, "%lu", sum); if (nk_combo_begin_label(ctx, buffer, nk_vec2(200,200))) { nk_layout_row_dynamic(ctx, 30, 1); - nk_checkbox_label(ctx, weapons[0], &check_values[0], NK_WIDGET_LEFT); - nk_checkbox_label(ctx, weapons[1], &check_values[1], NK_WIDGET_LEFT); - nk_checkbox_label(ctx, weapons[2], &check_values[2], NK_WIDGET_LEFT); - nk_checkbox_label(ctx, weapons[3], &check_values[3], NK_WIDGET_LEFT); + nk_checkbox_label(ctx, weapons[0], &check_values[0], NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_label(ctx, weapons[1], &check_values[1], NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_label(ctx, weapons[2], &check_values[2], NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_label(ctx, weapons[3], &check_values[3], NK_WIDGET_LEFT, NK_TEXT_LEFT); nk_combo_end(ctx); } @@ -724,7 +728,7 @@ overview(struct nk_context *ctx) static int slider = 10; nk_layout_row_dynamic(ctx, 25, 1); - nk_checkbox_label(ctx, "Menu", &show_menu, NK_WIDGET_LEFT); + nk_checkbox_label(ctx, "Menu", &show_menu, NK_WIDGET_LEFT, NK_TEXT_LEFT); nk_progress(ctx, &prog, 100, NK_MODIFIABLE); nk_slider_int(ctx, 0, &slider, 16, 1); if (nk_contextual_item_label(ctx, "About", NK_TEXT_CENTERED)) @@ -891,9 +895,9 @@ overview(struct nk_context *ctx) if (group_titlebar) group_flags |= NK_WINDOW_TITLE; nk_layout_row_dynamic(ctx, 30, 3); - nk_checkbox_label(ctx, "Titlebar", &group_titlebar, NK_WIDGET_LEFT); - nk_checkbox_label(ctx, "Border", &group_border, NK_WIDGET_LEFT); - nk_checkbox_label(ctx, "No Scrollbar", &group_no_scrollbar, NK_WIDGET_LEFT); + nk_checkbox_label(ctx, "Titlebar", &group_titlebar, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_label(ctx, "Border", &group_border, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_label(ctx, "No Scrollbar", &group_no_scrollbar, NK_WIDGET_LEFT, NK_TEXT_LEFT); nk_layout_row_begin(ctx, NK_STATIC, 22, 3); nk_layout_row_push(ctx, 50); diff --git a/nuklear.h b/nuklear.h index b062073..b2a3f51 100644 --- a/nuklear.h +++ b/nuklear.h @@ -3205,23 +3205,23 @@ NK_API nk_bool nk_button_pop_behavior(struct nk_context*); * CHECKBOX * * ============================================================================= */ -NK_API nk_bool nk_check_label(struct nk_context*, const char*, nk_bool active, nk_flags alignment); -NK_API nk_bool nk_check_text(struct nk_context*, const char*, int, nk_bool active, nk_flags alignment); -NK_API unsigned nk_check_flags_label(struct nk_context*, const char*, unsigned int flags, unsigned int value, nk_flags alignment); -NK_API unsigned nk_check_flags_text(struct nk_context*, const char*, int, unsigned int flags, unsigned int value, nk_flags alignment); -NK_API nk_bool nk_checkbox_label(struct nk_context*, const char*, nk_bool *active, nk_flags alignment); -NK_API nk_bool nk_checkbox_text(struct nk_context*, const char*, int, nk_bool *active, nk_flags alignment); -NK_API nk_bool nk_checkbox_flags_label(struct nk_context*, const char*, unsigned int *flags, unsigned int value, nk_flags alignment); -NK_API nk_bool nk_checkbox_flags_text(struct nk_context*, const char*, int, unsigned int *flags, unsigned int value, nk_flags alignment); +NK_API nk_bool nk_check_label(struct nk_context*, const char*, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_check_text(struct nk_context*, const char*, int, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API unsigned nk_check_flags_label(struct nk_context*, const char*, unsigned int flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment); +NK_API unsigned nk_check_flags_text(struct nk_context*, const char*, int, unsigned int flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_checkbox_label(struct nk_context*, const char*, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_checkbox_text(struct nk_context*, const char*, int, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_checkbox_flags_label(struct nk_context*, const char*, unsigned int *flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_checkbox_flags_text(struct nk_context*, const char*, int, unsigned int *flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment); /* ============================================================================= * * RADIO BUTTON * * ============================================================================= */ -NK_API nk_bool nk_radio_label(struct nk_context*, const char*, nk_bool *active, nk_flags alignment); -NK_API nk_bool nk_radio_text(struct nk_context*, const char*, int, nk_bool *active, nk_flags alignment); -NK_API nk_bool nk_option_label(struct nk_context*, const char*, nk_bool active, nk_flags alignment); -NK_API nk_bool nk_option_text(struct nk_context*, const char*, int, nk_bool active, nk_flags alignment); +NK_API nk_bool nk_radio_label(struct nk_context*, const char*, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_radio_text(struct nk_context*, const char*, int, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_option_label(struct nk_context*, const char*, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_option_text(struct nk_context*, const char*, int, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); /* ============================================================================= * * SELECTABLE @@ -6078,9 +6078,9 @@ enum nk_toggle_type { NK_TOGGLE_OPTION }; NK_LIB nk_bool nk_toggle_behavior(const struct nk_input *in, struct nk_rect select, nk_flags *state, nk_bool active); -NK_LIB void nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags alignment); -NK_LIB void nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags alignment); -NK_LIB nk_bool nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, nk_bool *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, const struct nk_user_font *font, nk_flags alignment); +NK_LIB void nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment); +NK_LIB void nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment); +NK_LIB nk_bool nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, nk_bool *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment); /* progress */ NK_LIB nk_size nk_progress_behavior(nk_flags *state, struct nk_input *in, struct nk_rect r, struct nk_rect cursor, nk_size max, nk_size value, nk_bool modifiable); @@ -24722,7 +24722,7 @@ nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, - const struct nk_user_font *font, nk_flags alignment) + const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment) { const struct nk_style_item *background; const struct nk_style_item *cursor; @@ -24747,7 +24747,7 @@ nk_draw_checkbox(struct nk_command_buffer *out, text.padding.x = 0; text.padding.y = 0; text.background = style->text_background; - nk_widget_text(out, *label, string, len, &text, alignment, font); + nk_widget_text(out, *label, string, len, &text, text_alignment, font); /* draw background and cursor */ if (background->type == NK_STYLE_ITEM_COLOR) { @@ -24765,7 +24765,7 @@ nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, - const struct nk_user_font *font, nk_flags alignment) + const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment) { const struct nk_style_item *background; const struct nk_style_item *cursor; @@ -24790,7 +24790,7 @@ nk_draw_option(struct nk_command_buffer *out, text.padding.x = 0; text.padding.y = 0; text.background = style->text_background; - nk_widget_text(out, *label, string, len, &text, alignment, font); + nk_widget_text(out, *label, string, len, &text, text_alignment, font); /* draw background and cursor */ if (background->type == NK_STYLE_ITEM_COLOR) { @@ -24808,7 +24808,7 @@ nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, nk_bool *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, - const struct nk_user_font *font, nk_flags alignment) + const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment) { int was_active; struct nk_rect allocated_space; @@ -24828,7 +24828,7 @@ nk_do_toggle(nk_flags *state, allocated_space = r; - if (alignment & NK_WIDGET_ALIGN_RIGHT) { + if (widget_alignment & NK_WIDGET_ALIGN_RIGHT) { r.x = r.x + r.w - font->height - style->padding.x; r.w = font->height; } @@ -24853,14 +24853,14 @@ nk_do_toggle(nk_flags *state, label.y = select.y; label.h = select.w; - if (alignment & NK_WIDGET_ALIGN_LEFT) { - /* label behind the selector */ - label.x = select.x + select.w + style->spacing; - label.w = NK_MAX(r.x + r.w, label.x) - label.x; - } else { + if (widget_alignment & NK_WIDGET_ALIGN_RIGHT) { /* label in front of the selector */ label.x = allocated_space.x; label.w = allocated_space.w - select.w - style->spacing * 2; + } else { + /* label behind the selector */ + label.x = select.x + select.w + style->spacing; + label.w = NK_MAX(r.x + r.w, label.x) - label.x; } /* update selector */ @@ -24871,9 +24871,9 @@ nk_do_toggle(nk_flags *state, if (style->draw_begin) style->draw_begin(out, style->userdata); if (type == NK_TOGGLE_CHECK) { - nk_draw_checkbox(out, *state, style, *active, &label, &select, &cursor, str, len, font, alignment); + nk_draw_checkbox(out, *state, style, *active, &label, &select, &cursor, str, len, font, widget_alignment, text_alignment); } else { - nk_draw_option(out, *state, style, *active, &label, &select, &cursor, str, len, font, alignment); + nk_draw_option(out, *state, style, *active, &label, &select, &cursor, str, len, font, widget_alignment, text_alignment); } if (style->draw_end) style->draw_end(out, style->userdata); @@ -24885,7 +24885,7 @@ nk_do_toggle(nk_flags *state, * * --------------------------------------------------------------*/ NK_API nk_bool -nk_check_text(struct nk_context *ctx, const char *text, int len, nk_bool active, nk_flags alignment) +nk_check_text(struct nk_context *ctx, const char *text, int len, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment) { struct nk_window *win; struct nk_panel *layout; @@ -24909,25 +24909,25 @@ nk_check_text(struct nk_context *ctx, const char *text, int len, nk_bool active, if (!state) return active; in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &active, - text, len, NK_TOGGLE_CHECK, &style->checkbox, in, style->font, alignment); + text, len, NK_TOGGLE_CHECK, &style->checkbox, in, style->font, widget_alignment, text_alignment); return active; } NK_API unsigned int nk_check_flags_text(struct nk_context *ctx, const char *text, int len, - unsigned int flags, unsigned int value, nk_flags alignment) + unsigned int flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment) { int old_active; NK_ASSERT(ctx); NK_ASSERT(text); if (!ctx || !text) return flags; old_active = (int)((flags & value) & value); - if (nk_check_text(ctx, text, len, old_active, alignment)) + if (nk_check_text(ctx, text, len, old_active, widget_alignment, text_alignment)) flags |= value; else flags &= ~value; return flags; } NK_API nk_bool -nk_checkbox_text(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags alignment) +nk_checkbox_text(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) { int old_val; NK_ASSERT(ctx); @@ -24935,12 +24935,12 @@ nk_checkbox_text(struct nk_context *ctx, const char *text, int len, nk_bool *act NK_ASSERT(active); if (!ctx || !text || !active) return 0; old_val = *active; - *active = nk_check_text(ctx, text, len, *active, alignment); + *active = nk_check_text(ctx, text, len, *active, widget_alignment, text_alignment); return old_val != *active; } NK_API nk_bool nk_checkbox_flags_text(struct nk_context *ctx, const char *text, int len, - unsigned int *flags, unsigned int value, nk_flags alignment) + unsigned int *flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment) { nk_bool active; NK_ASSERT(ctx); @@ -24949,30 +24949,30 @@ nk_checkbox_flags_text(struct nk_context *ctx, const char *text, int len, if (!ctx || !text || !flags) return 0; active = (int)((*flags & value) & value); - if (nk_checkbox_text(ctx, text, len, &active, alignment)) { + if (nk_checkbox_text(ctx, text, len, &active, widget_alignment, text_alignment)) { if (active) *flags |= value; else *flags &= ~value; return 1; } return 0; } -NK_API nk_bool nk_check_label(struct nk_context *ctx, const char *label, nk_bool active, nk_flags alignment) +NK_API nk_bool nk_check_label(struct nk_context *ctx, const char *label, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment) { - return nk_check_text(ctx, label, nk_strlen(label), active, alignment); + return nk_check_text(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); } NK_API unsigned int nk_check_flags_label(struct nk_context *ctx, const char *label, - unsigned int flags, unsigned int value, nk_flags alignment) + unsigned int flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment) { - return nk_check_flags_text(ctx, label, nk_strlen(label), flags, value, alignment); + return nk_check_flags_text(ctx, label, nk_strlen(label), flags, value, widget_alignment, text_alignment); } -NK_API nk_bool nk_checkbox_label(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags alignment) +NK_API nk_bool nk_checkbox_label(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) { - return nk_checkbox_text(ctx, label, nk_strlen(label), active, alignment); + return nk_checkbox_text(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); } NK_API nk_bool nk_checkbox_flags_label(struct nk_context *ctx, const char *label, - unsigned int *flags, unsigned int value, nk_flags alignment) + unsigned int *flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment) { - return nk_checkbox_flags_text(ctx, label, nk_strlen(label), flags, value, alignment); + return nk_checkbox_flags_text(ctx, label, nk_strlen(label), flags, value, widget_alignment, text_alignment); } /*---------------------------------------------------------------- * @@ -24980,7 +24980,7 @@ NK_API nk_bool nk_checkbox_flags_label(struct nk_context *ctx, const char *label * * --------------------------------------------------------------*/ NK_API nk_bool -nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_active, nk_flags alignment) +nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_active, nk_flags widget_alignment, nk_flags text_alignment) { struct nk_window *win; struct nk_panel *layout; @@ -25004,11 +25004,11 @@ nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_act if (!state) return (int)state; in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &is_active, - text, len, NK_TOGGLE_OPTION, &style->option, in, style->font, alignment); + text, len, NK_TOGGLE_OPTION, &style->option, in, style->font, widget_alignment, text_alignment); return is_active; } NK_API nk_bool -nk_radio_text(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags alignment) +nk_radio_text(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) { int old_value; NK_ASSERT(ctx); @@ -25016,18 +25016,18 @@ nk_radio_text(struct nk_context *ctx, const char *text, int len, nk_bool *active NK_ASSERT(active); if (!ctx || !text || !active) return 0; old_value = *active; - *active = nk_option_text(ctx, text, len, old_value, alignment); + *active = nk_option_text(ctx, text, len, old_value, widget_alignment, text_alignment); return old_value != *active; } NK_API nk_bool -nk_option_label(struct nk_context *ctx, const char *label, nk_bool active, nk_flags alignment) +nk_option_label(struct nk_context *ctx, const char *label, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment) { - return nk_option_text(ctx, label, nk_strlen(label), active, alignment); + return nk_option_text(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); } NK_API nk_bool -nk_radio_label(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags alignment) +nk_radio_label(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) { - return nk_radio_text(ctx, label, nk_strlen(label), active, alignment); + return nk_radio_text(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); } diff --git a/src/nuklear.h b/src/nuklear.h index 26c3b4f..d7a6ad2 100644 --- a/src/nuklear.h +++ b/src/nuklear.h @@ -2983,23 +2983,23 @@ NK_API nk_bool nk_button_pop_behavior(struct nk_context*); * CHECKBOX * * ============================================================================= */ -NK_API nk_bool nk_check_label(struct nk_context*, const char*, nk_bool active, nk_flags alignment); -NK_API nk_bool nk_check_text(struct nk_context*, const char*, int, nk_bool active, nk_flags alignment); -NK_API unsigned nk_check_flags_label(struct nk_context*, const char*, unsigned int flags, unsigned int value, nk_flags alignment); -NK_API unsigned nk_check_flags_text(struct nk_context*, const char*, int, unsigned int flags, unsigned int value, nk_flags alignment); -NK_API nk_bool nk_checkbox_label(struct nk_context*, const char*, nk_bool *active, nk_flags alignment); -NK_API nk_bool nk_checkbox_text(struct nk_context*, const char*, int, nk_bool *active, nk_flags alignment); -NK_API nk_bool nk_checkbox_flags_label(struct nk_context*, const char*, unsigned int *flags, unsigned int value, nk_flags alignment); -NK_API nk_bool nk_checkbox_flags_text(struct nk_context*, const char*, int, unsigned int *flags, unsigned int value, nk_flags alignment); +NK_API nk_bool nk_check_label(struct nk_context*, const char*, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_check_text(struct nk_context*, const char*, int, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API unsigned nk_check_flags_label(struct nk_context*, const char*, unsigned int flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment); +NK_API unsigned nk_check_flags_text(struct nk_context*, const char*, int, unsigned int flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_checkbox_label(struct nk_context*, const char*, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_checkbox_text(struct nk_context*, const char*, int, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_checkbox_flags_label(struct nk_context*, const char*, unsigned int *flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_checkbox_flags_text(struct nk_context*, const char*, int, unsigned int *flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment); /* ============================================================================= * * RADIO BUTTON * * ============================================================================= */ -NK_API nk_bool nk_radio_label(struct nk_context*, const char*, nk_bool *active, nk_flags alignment); -NK_API nk_bool nk_radio_text(struct nk_context*, const char*, int, nk_bool *active, nk_flags alignment); -NK_API nk_bool nk_option_label(struct nk_context*, const char*, nk_bool active, nk_flags alignment); -NK_API nk_bool nk_option_text(struct nk_context*, const char*, int, nk_bool active, nk_flags alignment); +NK_API nk_bool nk_radio_label(struct nk_context*, const char*, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_radio_text(struct nk_context*, const char*, int, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_option_label(struct nk_context*, const char*, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_option_text(struct nk_context*, const char*, int, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); /* ============================================================================= * * SELECTABLE diff --git a/src/nuklear_internal.h b/src/nuklear_internal.h index 9f6a6dc..31689db 100644 --- a/src/nuklear_internal.h +++ b/src/nuklear_internal.h @@ -255,9 +255,9 @@ enum nk_toggle_type { NK_TOGGLE_OPTION }; NK_LIB nk_bool nk_toggle_behavior(const struct nk_input *in, struct nk_rect select, nk_flags *state, nk_bool active); -NK_LIB void nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags alignment); -NK_LIB void nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags alignment); -NK_LIB nk_bool nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, nk_bool *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, const struct nk_user_font *font, nk_flags alignment); +NK_LIB void nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment); +NK_LIB void nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment); +NK_LIB nk_bool nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, nk_bool *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment); /* progress */ NK_LIB nk_size nk_progress_behavior(nk_flags *state, struct nk_input *in, struct nk_rect r, struct nk_rect cursor, nk_size max, nk_size value, nk_bool modifiable); diff --git a/src/nuklear_toggle.c b/src/nuklear_toggle.c index 930ac33..92f032c 100644 --- a/src/nuklear_toggle.c +++ b/src/nuklear_toggle.c @@ -26,7 +26,7 @@ nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, - const struct nk_user_font *font, nk_flags alignment) + const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment) { const struct nk_style_item *background; const struct nk_style_item *cursor; @@ -51,7 +51,7 @@ nk_draw_checkbox(struct nk_command_buffer *out, text.padding.x = 0; text.padding.y = 0; text.background = style->text_background; - nk_widget_text(out, *label, string, len, &text, alignment, font); + nk_widget_text(out, *label, string, len, &text, text_alignment, font); /* draw background and cursor */ if (background->type == NK_STYLE_ITEM_COLOR) { @@ -69,7 +69,7 @@ nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, - const struct nk_user_font *font, nk_flags alignment) + const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment) { const struct nk_style_item *background; const struct nk_style_item *cursor; @@ -94,7 +94,7 @@ nk_draw_option(struct nk_command_buffer *out, text.padding.x = 0; text.padding.y = 0; text.background = style->text_background; - nk_widget_text(out, *label, string, len, &text, alignment, font); + nk_widget_text(out, *label, string, len, &text, text_alignment, font); /* draw background and cursor */ if (background->type == NK_STYLE_ITEM_COLOR) { @@ -112,7 +112,7 @@ nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, nk_bool *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, - const struct nk_user_font *font, nk_flags alignment) + const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment) { int was_active; struct nk_rect allocated_space; @@ -132,7 +132,7 @@ nk_do_toggle(nk_flags *state, allocated_space = r; - if (alignment & NK_WIDGET_ALIGN_RIGHT) { + if (widget_alignment & NK_WIDGET_ALIGN_RIGHT) { r.x = r.x + r.w - font->height - style->padding.x; r.w = font->height; } @@ -157,14 +157,14 @@ nk_do_toggle(nk_flags *state, label.y = select.y; label.h = select.w; - if (alignment & NK_WIDGET_ALIGN_LEFT) { - /* label behind the selector */ - label.x = select.x + select.w + style->spacing; - label.w = NK_MAX(r.x + r.w, label.x) - label.x; - } else { + if (widget_alignment & NK_WIDGET_ALIGN_RIGHT) { /* label in front of the selector */ label.x = allocated_space.x; label.w = allocated_space.w - select.w - style->spacing * 2; + } else { + /* label behind the selector */ + label.x = select.x + select.w + style->spacing; + label.w = NK_MAX(r.x + r.w, label.x) - label.x; } /* update selector */ @@ -175,9 +175,9 @@ nk_do_toggle(nk_flags *state, if (style->draw_begin) style->draw_begin(out, style->userdata); if (type == NK_TOGGLE_CHECK) { - nk_draw_checkbox(out, *state, style, *active, &label, &select, &cursor, str, len, font, alignment); + nk_draw_checkbox(out, *state, style, *active, &label, &select, &cursor, str, len, font, widget_alignment, text_alignment); } else { - nk_draw_option(out, *state, style, *active, &label, &select, &cursor, str, len, font, alignment); + nk_draw_option(out, *state, style, *active, &label, &select, &cursor, str, len, font, widget_alignment, text_alignment); } if (style->draw_end) style->draw_end(out, style->userdata); @@ -189,7 +189,7 @@ nk_do_toggle(nk_flags *state, * * --------------------------------------------------------------*/ NK_API nk_bool -nk_check_text(struct nk_context *ctx, const char *text, int len, nk_bool active, nk_flags alignment) +nk_check_text(struct nk_context *ctx, const char *text, int len, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment) { struct nk_window *win; struct nk_panel *layout; @@ -213,25 +213,25 @@ nk_check_text(struct nk_context *ctx, const char *text, int len, nk_bool active, if (!state) return active; in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &active, - text, len, NK_TOGGLE_CHECK, &style->checkbox, in, style->font, alignment); + text, len, NK_TOGGLE_CHECK, &style->checkbox, in, style->font, widget_alignment, text_alignment); return active; } NK_API unsigned int nk_check_flags_text(struct nk_context *ctx, const char *text, int len, - unsigned int flags, unsigned int value, nk_flags alignment) + unsigned int flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment) { int old_active; NK_ASSERT(ctx); NK_ASSERT(text); if (!ctx || !text) return flags; old_active = (int)((flags & value) & value); - if (nk_check_text(ctx, text, len, old_active, alignment)) + if (nk_check_text(ctx, text, len, old_active, widget_alignment, text_alignment)) flags |= value; else flags &= ~value; return flags; } NK_API nk_bool -nk_checkbox_text(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags alignment) +nk_checkbox_text(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) { int old_val; NK_ASSERT(ctx); @@ -239,12 +239,12 @@ nk_checkbox_text(struct nk_context *ctx, const char *text, int len, nk_bool *act NK_ASSERT(active); if (!ctx || !text || !active) return 0; old_val = *active; - *active = nk_check_text(ctx, text, len, *active, alignment); + *active = nk_check_text(ctx, text, len, *active, widget_alignment, text_alignment); return old_val != *active; } NK_API nk_bool nk_checkbox_flags_text(struct nk_context *ctx, const char *text, int len, - unsigned int *flags, unsigned int value, nk_flags alignment) + unsigned int *flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment) { nk_bool active; NK_ASSERT(ctx); @@ -253,30 +253,30 @@ nk_checkbox_flags_text(struct nk_context *ctx, const char *text, int len, if (!ctx || !text || !flags) return 0; active = (int)((*flags & value) & value); - if (nk_checkbox_text(ctx, text, len, &active, alignment)) { + if (nk_checkbox_text(ctx, text, len, &active, widget_alignment, text_alignment)) { if (active) *flags |= value; else *flags &= ~value; return 1; } return 0; } -NK_API nk_bool nk_check_label(struct nk_context *ctx, const char *label, nk_bool active, nk_flags alignment) +NK_API nk_bool nk_check_label(struct nk_context *ctx, const char *label, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment) { - return nk_check_text(ctx, label, nk_strlen(label), active, alignment); + return nk_check_text(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); } NK_API unsigned int nk_check_flags_label(struct nk_context *ctx, const char *label, - unsigned int flags, unsigned int value, nk_flags alignment) + unsigned int flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment) { - return nk_check_flags_text(ctx, label, nk_strlen(label), flags, value, alignment); + return nk_check_flags_text(ctx, label, nk_strlen(label), flags, value, widget_alignment, text_alignment); } -NK_API nk_bool nk_checkbox_label(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags alignment) +NK_API nk_bool nk_checkbox_label(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) { - return nk_checkbox_text(ctx, label, nk_strlen(label), active, alignment); + return nk_checkbox_text(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); } NK_API nk_bool nk_checkbox_flags_label(struct nk_context *ctx, const char *label, - unsigned int *flags, unsigned int value, nk_flags alignment) + unsigned int *flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment) { - return nk_checkbox_flags_text(ctx, label, nk_strlen(label), flags, value, alignment); + return nk_checkbox_flags_text(ctx, label, nk_strlen(label), flags, value, widget_alignment, text_alignment); } /*---------------------------------------------------------------- * @@ -284,7 +284,7 @@ NK_API nk_bool nk_checkbox_flags_label(struct nk_context *ctx, const char *label * * --------------------------------------------------------------*/ NK_API nk_bool -nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_active, nk_flags alignment) +nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_active, nk_flags widget_alignment, nk_flags text_alignment) { struct nk_window *win; struct nk_panel *layout; @@ -308,11 +308,11 @@ nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_act if (!state) return (int)state; in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &is_active, - text, len, NK_TOGGLE_OPTION, &style->option, in, style->font, alignment); + text, len, NK_TOGGLE_OPTION, &style->option, in, style->font, widget_alignment, text_alignment); return is_active; } NK_API nk_bool -nk_radio_text(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags alignment) +nk_radio_text(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) { int old_value; NK_ASSERT(ctx); @@ -320,17 +320,17 @@ nk_radio_text(struct nk_context *ctx, const char *text, int len, nk_bool *active NK_ASSERT(active); if (!ctx || !text || !active) return 0; old_value = *active; - *active = nk_option_text(ctx, text, len, old_value, alignment); + *active = nk_option_text(ctx, text, len, old_value, widget_alignment, text_alignment); return old_value != *active; } NK_API nk_bool -nk_option_label(struct nk_context *ctx, const char *label, nk_bool active, nk_flags alignment) +nk_option_label(struct nk_context *ctx, const char *label, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment) { - return nk_option_text(ctx, label, nk_strlen(label), active, alignment); + return nk_option_text(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); } NK_API nk_bool -nk_radio_label(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags alignment) +nk_radio_label(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) { - return nk_radio_text(ctx, label, nk_strlen(label), active, alignment); + return nk_radio_text(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); } From 2a528263928535a02c09ec7dd80bb56e50693484 Mon Sep 17 00:00:00 2001 From: Jacob Ahnstedt Date: Sun, 26 Nov 2023 10:44:37 +0100 Subject: [PATCH 073/106] Removed widget alignment for the draw functions of toggleables --- nuklear.h | 12 ++++++------ src/nuklear_internal.h | 4 ++-- src/nuklear_toggle.c | 8 ++++---- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/nuklear.h b/nuklear.h index b2a3f51..12696cb 100644 --- a/nuklear.h +++ b/nuklear.h @@ -6078,8 +6078,8 @@ enum nk_toggle_type { NK_TOGGLE_OPTION }; NK_LIB nk_bool nk_toggle_behavior(const struct nk_input *in, struct nk_rect select, nk_flags *state, nk_bool active); -NK_LIB void nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment); -NK_LIB void nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment); +NK_LIB void nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags text_alignment); +NK_LIB void nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags text_alignment); NK_LIB nk_bool nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, nk_bool *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment); /* progress */ @@ -24722,7 +24722,7 @@ nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, - const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment) + const struct nk_user_font *font, nk_flags text_alignment) { const struct nk_style_item *background; const struct nk_style_item *cursor; @@ -24765,7 +24765,7 @@ nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, - const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment) + const struct nk_user_font *font, nk_flags text_alignment) { const struct nk_style_item *background; const struct nk_style_item *cursor; @@ -24871,9 +24871,9 @@ nk_do_toggle(nk_flags *state, if (style->draw_begin) style->draw_begin(out, style->userdata); if (type == NK_TOGGLE_CHECK) { - nk_draw_checkbox(out, *state, style, *active, &label, &select, &cursor, str, len, font, widget_alignment, text_alignment); + nk_draw_checkbox(out, *state, style, *active, &label, &select, &cursor, str, len, font, text_alignment); } else { - nk_draw_option(out, *state, style, *active, &label, &select, &cursor, str, len, font, widget_alignment, text_alignment); + nk_draw_option(out, *state, style, *active, &label, &select, &cursor, str, len, font, text_alignment); } if (style->draw_end) style->draw_end(out, style->userdata); diff --git a/src/nuklear_internal.h b/src/nuklear_internal.h index 31689db..9f20d0d 100644 --- a/src/nuklear_internal.h +++ b/src/nuklear_internal.h @@ -255,8 +255,8 @@ enum nk_toggle_type { NK_TOGGLE_OPTION }; NK_LIB nk_bool nk_toggle_behavior(const struct nk_input *in, struct nk_rect select, nk_flags *state, nk_bool active); -NK_LIB void nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment); -NK_LIB void nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment); +NK_LIB void nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags text_alignment); +NK_LIB void nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags text_alignment); NK_LIB nk_bool nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, nk_bool *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment); /* progress */ diff --git a/src/nuklear_toggle.c b/src/nuklear_toggle.c index 92f032c..9985925 100644 --- a/src/nuklear_toggle.c +++ b/src/nuklear_toggle.c @@ -26,7 +26,7 @@ nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, - const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment) + const struct nk_user_font *font, nk_flags text_alignment) { const struct nk_style_item *background; const struct nk_style_item *cursor; @@ -69,7 +69,7 @@ nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, - const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment) + const struct nk_user_font *font, nk_flags text_alignment) { const struct nk_style_item *background; const struct nk_style_item *cursor; @@ -175,9 +175,9 @@ nk_do_toggle(nk_flags *state, if (style->draw_begin) style->draw_begin(out, style->userdata); if (type == NK_TOGGLE_CHECK) { - nk_draw_checkbox(out, *state, style, *active, &label, &select, &cursor, str, len, font, widget_alignment, text_alignment); + nk_draw_checkbox(out, *state, style, *active, &label, &select, &cursor, str, len, font, text_alignment); } else { - nk_draw_option(out, *state, style, *active, &label, &select, &cursor, str, len, font, widget_alignment, text_alignment); + nk_draw_option(out, *state, style, *active, &label, &select, &cursor, str, len, font, text_alignment); } if (style->draw_end) style->draw_end(out, style->userdata); From 6c0f814c4e47d033622011cf3f775682df0fbe73 Mon Sep 17 00:00:00 2001 From: Jacob Ahnstedt Date: Sun, 26 Nov 2023 11:01:02 +0100 Subject: [PATCH 074/106] Applied toggleable alignment to demos --- demo/allegro5/main.c | 4 ++-- demo/d3d11/main.c | 4 ++-- demo/d3d12/main.c | 4 ++-- demo/d3d9/main.c | 4 ++-- demo/gdi/main.c | 4 ++-- demo/gdip/main.c | 4 ++-- demo/glfw_opengl2/main.c | 4 ++-- demo/glfw_opengl3/main.c | 4 ++-- demo/glfw_opengl4/main.c | 4 ++-- demo/glfw_vulkan/main.c | 4 ++-- demo/sdl2surface_rawfb/main.c | 4 ++-- demo/sdl_opengl2/main.c | 4 ++-- demo/sdl_opengl3/main.c | 4 ++-- demo/sdl_opengles2/main.c | 4 ++-- demo/sdl_renderer/main.c | 4 ++-- demo/sfml_opengl2/main.cpp | 4 ++-- demo/sfml_opengl3/main.cpp | 4 ++-- demo/wayland_rawfb/main.c | 4 ++-- demo/x11/main.c | 4 ++-- demo/x11_opengl2/main.c | 4 ++-- demo/x11_opengl3/main.c | 4 ++-- demo/x11_rawfb/main.c | 4 ++-- demo/x11_xft/main.c | 4 ++-- 23 files changed, 46 insertions(+), 46 deletions(-) diff --git a/demo/allegro5/main.c b/demo/allegro5/main.c index ee01de7..ff2228c 100644 --- a/demo/allegro5/main.c +++ b/demo/allegro5/main.c @@ -165,8 +165,8 @@ int main(void) if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; nk_layout_row_dynamic(ctx, 22, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); } diff --git a/demo/d3d11/main.c b/demo/d3d11/main.c index 338dde2..63bb495 100644 --- a/demo/d3d11/main.c +++ b/demo/d3d11/main.c @@ -250,8 +250,8 @@ int main(void) if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; nk_layout_row_dynamic(ctx, 22, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/d3d12/main.c b/demo/d3d12/main.c index 57e7bc3..90d8ab9 100644 --- a/demo/d3d12/main.c +++ b/demo/d3d12/main.c @@ -342,8 +342,8 @@ int main(void) if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; nk_layout_row_dynamic(ctx, 22, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/d3d9/main.c b/demo/d3d9/main.c index 638c584..03a9530 100644 --- a/demo/d3d9/main.c +++ b/demo/d3d9/main.c @@ -255,8 +255,8 @@ int main(void) if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; nk_layout_row_dynamic(ctx, 22, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/gdi/main.c b/demo/gdi/main.c index 281f82b..9410e97 100644 --- a/demo/gdi/main.c +++ b/demo/gdi/main.c @@ -164,8 +164,8 @@ int main(void) if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; nk_layout_row_dynamic(ctx, 22, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); } diff --git a/demo/gdip/main.c b/demo/gdip/main.c index 7151964..78db5ed 100644 --- a/demo/gdip/main.c +++ b/demo/gdip/main.c @@ -159,8 +159,8 @@ int main(void) if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; nk_layout_row_dynamic(ctx, 22, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); } diff --git a/demo/glfw_opengl2/main.c b/demo/glfw_opengl2/main.c index 8d97773..6296a76 100644 --- a/demo/glfw_opengl2/main.c +++ b/demo/glfw_opengl2/main.c @@ -172,8 +172,8 @@ int main(void) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/glfw_opengl3/main.c b/demo/glfw_opengl3/main.c index 8eb749d..cbe692e 100644 --- a/demo/glfw_opengl3/main.c +++ b/demo/glfw_opengl3/main.c @@ -158,8 +158,8 @@ int main(void) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/glfw_opengl4/main.c b/demo/glfw_opengl4/main.c index 176a1ef..502d1ad 100644 --- a/demo/glfw_opengl4/main.c +++ b/demo/glfw_opengl4/main.c @@ -168,8 +168,8 @@ int main(void) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/glfw_vulkan/main.c b/demo/glfw_vulkan/main.c index 555a5aa..0bc17b4 100644 --- a/demo/glfw_vulkan/main.c +++ b/demo/glfw_vulkan/main.c @@ -2148,9 +2148,9 @@ int main(void) { fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY)) + if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD)) + if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); diff --git a/demo/sdl2surface_rawfb/main.c b/demo/sdl2surface_rawfb/main.c index a8b661a..c2238d9 100644 --- a/demo/sdl2surface_rawfb/main.c +++ b/demo/sdl2surface_rawfb/main.c @@ -216,8 +216,8 @@ int main(int argc, char **argv) printf("button pressed\n"); } nk_layout_row_dynamic(&(context->ctx), 40, 2); - if (nk_option_label(&(context->ctx), "easy", op == EASY)) op = EASY; - if (nk_option_label(&(context->ctx), "hard", op == HARD)) op = HARD; + if (nk_option_label(&(context->ctx), "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; + if (nk_option_label(&(context->ctx), "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; nk_layout_row_dynamic(&(context->ctx), 45, 1); nk_property_int(&(context->ctx), "Compression:", 0, &property, 100, 10, 1); } diff --git a/demo/sdl_opengl2/main.c b/demo/sdl_opengl2/main.c index 45c51d2..508d42a 100644 --- a/demo/sdl_opengl2/main.c +++ b/demo/sdl_opengl2/main.c @@ -154,8 +154,8 @@ main(int argc, char *argv[]) if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/sdl_opengl3/main.c b/demo/sdl_opengl3/main.c index e039a2f..0483626 100644 --- a/demo/sdl_opengl3/main.c +++ b/demo/sdl_opengl3/main.c @@ -164,8 +164,8 @@ int main(int argc, char *argv[]) if (nk_button_label(ctx, "button")) printf("button pressed!\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; nk_layout_row_dynamic(ctx, 22, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/sdl_opengles2/main.c b/demo/sdl_opengles2/main.c index b114159..c527e5f 100644 --- a/demo/sdl_opengles2/main.c +++ b/demo/sdl_opengles2/main.c @@ -128,8 +128,8 @@ MainLoop(void* loopArg){ if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); } diff --git a/demo/sdl_renderer/main.c b/demo/sdl_renderer/main.c index 940ea84..a8af16b 100644 --- a/demo/sdl_renderer/main.c +++ b/demo/sdl_renderer/main.c @@ -192,8 +192,8 @@ main(int argc, char *argv[]) if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/sfml_opengl2/main.cpp b/demo/sfml_opengl2/main.cpp index 82f8e0f..6594ad3 100644 --- a/demo/sfml_opengl2/main.cpp +++ b/demo/sfml_opengl2/main.cpp @@ -139,8 +139,8 @@ int main(void) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/sfml_opengl3/main.cpp b/demo/sfml_opengl3/main.cpp index 22aafcc..8fa6df8 100644 --- a/demo/sfml_opengl3/main.cpp +++ b/demo/sfml_opengl3/main.cpp @@ -146,8 +146,8 @@ int main(void) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/wayland_rawfb/main.c b/demo/wayland_rawfb/main.c index cf60eed..baf4cc8 100644 --- a/demo/wayland_rawfb/main.c +++ b/demo/wayland_rawfb/main.c @@ -533,8 +533,8 @@ int main () printf("button pressed\n"); } nk_layout_row_dynamic(&(nk_wayland_ctx.ctx), 30, 2); - if (nk_option_label(&(nk_wayland_ctx.ctx), "easy", op == EASY)) op = EASY; - if (nk_option_label(&(nk_wayland_ctx.ctx), "hard", op == HARD)) op = HARD; + if (nk_option_label(&(nk_wayland_ctx.ctx), "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; + if (nk_option_label(&(nk_wayland_ctx.ctx), "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; nk_layout_row_dynamic(&(nk_wayland_ctx.ctx), 25, 1); nk_property_int(&(nk_wayland_ctx.ctx), "Compression:", 0, &property, 100, 10, 1); } diff --git a/demo/x11/main.c b/demo/x11/main.c index 0d02ad7..4cbf4c4 100644 --- a/demo/x11/main.c +++ b/demo/x11/main.c @@ -192,8 +192,8 @@ main(void) if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); } diff --git a/demo/x11_opengl2/main.c b/demo/x11_opengl2/main.c index 2dc845e..679f7b1 100644 --- a/demo/x11_opengl2/main.c +++ b/demo/x11_opengl2/main.c @@ -296,8 +296,8 @@ int main(void) if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/x11_opengl3/main.c b/demo/x11_opengl3/main.c index a4a3008..4553469 100644 --- a/demo/x11_opengl3/main.c +++ b/demo/x11_opengl3/main.c @@ -293,8 +293,8 @@ int main(void) if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/x11_rawfb/main.c b/demo/x11_rawfb/main.c index 52a1c93..5a19bb3 100644 --- a/demo/x11_rawfb/main.c +++ b/demo/x11_rawfb/main.c @@ -229,8 +229,8 @@ main(void) if (nk_button_label(&rawfb->ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(&rawfb->ctx, 30, 2); - if (nk_option_label(&rawfb->ctx, "easy", op == EASY)) op = EASY; - if (nk_option_label(&rawfb->ctx, "hard", op == HARD)) op = HARD; + if (nk_option_label(&rawfb->ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; + if (nk_option_label(&rawfb->ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; nk_layout_row_dynamic(&rawfb->ctx, 25, 1); nk_property_int(&rawfb->ctx, "Compression:", 0, &property, 100, 10, 1); } diff --git a/demo/x11_xft/main.c b/demo/x11_xft/main.c index 263f43b..b4cc2ca 100644 --- a/demo/x11_xft/main.c +++ b/demo/x11_xft/main.c @@ -196,8 +196,8 @@ main(void) if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); } From 9614f5f99def2fc73d18f80aa4639cd4c7cdd079 Mon Sep 17 00:00:00 2001 From: Jacob Ahnstedt Date: Sun, 26 Nov 2023 11:04:52 +0100 Subject: [PATCH 075/106] Applied toggleable alignment to example extended --- example/extended.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/example/extended.c b/example/extended.c index 4e1211b..491af60 100644 --- a/example/extended.c +++ b/example/extended.c @@ -201,7 +201,7 @@ grid_demo(struct nk_context *ctx, struct media *media) nk_label(ctx, "Binary:", NK_TEXT_RIGHT); nk_edit_string(ctx, NK_EDIT_FIELD, text[2], &text_len[2], 64, nk_filter_binary); nk_label(ctx, "Checkbox:", NK_TEXT_RIGHT); - nk_checkbox_label(ctx, "Check me", &check); + nk_checkbox_label(ctx, "Check me", &check, NK_WIDGET_LEFT, NK_TEXT_LEFT); nk_label(ctx, "Combobox:", NK_TEXT_RIGHT); if (nk_combo_begin_label(ctx, items[selected_item], nk_vec2(nk_widget_width(ctx), 200))) { nk_layout_row_dynamic(ctx, 25, 1); @@ -433,9 +433,9 @@ basic_demo(struct nk_context *ctx, struct media *media) *------------------------------------------------*/ ui_header(ctx, media, "Checkbox"); ui_widget(ctx, media, 30); - nk_checkbox_label(ctx, "Flag 1", &check0); + nk_checkbox_label(ctx, "Flag 1", &check0, NK_WIDGET_LEFT, NK_TEXT_LEFT); ui_widget(ctx, media, 30); - nk_checkbox_label(ctx, "Flag 2", &check1); + nk_checkbox_label(ctx, "Flag 2", &check1, NK_WIDGET_LEFT, NK_TEXT_LEFT); /*------------------------------------------------ * PROGRESSBAR From aa9959204544f82f4c65c62a86abb701f3326b5a Mon Sep 17 00:00:00 2001 From: Jacob Ahnstedt Date: Sun, 26 Nov 2023 11:08:05 +0100 Subject: [PATCH 076/106] Applied toggleable alignment to example skinning --- example/skinning.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/example/skinning.c b/example/skinning.c index fab9ce3..fb6c352 100644 --- a/example/skinning.c +++ b/example/skinning.c @@ -754,10 +754,10 @@ int main(int argc, char *argv[]) nk_layout_row_dynamic(&ctx, 20, 1); nk_label(&ctx, "Label", NK_TEXT_LEFT); nk_layout_row_dynamic(&ctx, 30, 2); - nk_check_label(&ctx, "inactive", 0); - nk_check_label(&ctx, "active", 1); - nk_option_label(&ctx, "active", 1); - nk_option_label(&ctx, "inactive", 0); + nk_check_label(&ctx, "inactive", 0, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_check_label(&ctx, "active", 1, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_option_label(&ctx, "active", 1, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_option_label(&ctx, "inactive", 0, NK_WIDGET_LEFT, NK_TEXT_LEFT); nk_layout_row_dynamic(&ctx, 30, 1); nk_slider_int(&ctx, 0, &slider, 16, 1); From 8abee2451313ef58023c028e072f33342bf28366 Mon Sep 17 00:00:00 2001 From: Jacob Ahnstedt Date: Sun, 26 Nov 2023 11:22:28 +0100 Subject: [PATCH 077/106] Added changes to changelog and bumped clib.json --- clib.json | 2 +- src/CHANGELOG | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/clib.json b/clib.json index 1cad42b..c9605df 100644 --- a/clib.json +++ b/clib.json @@ -1,6 +1,6 @@ { "name": "nuklear", - "version": "4.11.0", + "version": "5.0.0", "repo": "Immediate-Mode-UI/Nuklear", "description": "A small ANSI C gui toolkit", "keywords": ["gl", "ui", "toolkit"], diff --git a/src/CHANGELOG b/src/CHANGELOG index a4a0ad9..b0376ac 100644 --- a/src/CHANGELOG +++ b/src/CHANGELOG @@ -7,6 +7,8 @@ /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// +/// - 2023/11/26 (5.0.0) - BREAKING CHANGE: Added alignment to check boxes and radio buttons. They +/// all now require a widget and text alignment parameter. /// - 2023/10/11 (4.11.0) - Added nk_widget_disable_begin() and nk_widget_disable_end() /// - 2022/12/23 (4.10.6) - Fix incorrect glyph index in nk_font_bake() /// - 2022/12/17 (4.10.5) - Fix nk_font_bake_pack() using TTC font offset incorrectly From 657e525ff8ac124174d1dcbff1e1e39fa72cef4f Mon Sep 17 00:00:00 2001 From: Jacob Ahnstedt Date: Sun, 26 Nov 2023 14:29:25 +0100 Subject: [PATCH 078/106] Added all alignments to toggleables --- demo/common/overview.c | 10 ++++---- nuklear.h | 55 +++++++++++++++++++++++++----------------- src/nuklear_toggle.c | 53 +++++++++++++++++++++++----------------- 3 files changed, 69 insertions(+), 49 deletions(-) diff --git a/demo/common/overview.c b/demo/common/overview.c index dff9796..d4c90b1 100644 --- a/demo/common/overview.c +++ b/demo/common/overview.c @@ -142,7 +142,7 @@ overview(struct nk_context *ctx) { enum options {A,B,C}; static int checkbox_left_text_left; - static int checkbox_left_text_right; + static int checkbox_centered_text_right; static int checkbox_right_text_right; static int checkbox_right_text_left; static int option_left; @@ -213,10 +213,10 @@ overview(struct nk_context *ctx) static const float ratio[] = {120, 150}; nk_layout_row_dynamic(ctx, 0, 1); - nk_checkbox_label(ctx, "Checkbox Left Text Left", &checkbox_left_text_left, NK_WIDGET_LEFT, NK_TEXT_LEFT); - nk_checkbox_label(ctx, "Checkbox Left Text Right", &checkbox_left_text_right, NK_WIDGET_LEFT, NK_TEXT_RIGHT); - nk_checkbox_label(ctx, "Checkbox Right Text Right", &checkbox_right_text_right, NK_WIDGET_RIGHT, NK_TEXT_RIGHT); - nk_checkbox_label(ctx, "Checkbox Right Text Left", &checkbox_right_text_left, NK_WIDGET_RIGHT, NK_TEXT_LEFT); + nk_checkbox_label(ctx, "CheckLeft TextLeft", &checkbox_left_text_left, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_label(ctx, "CheckCenter TextRight", &checkbox_centered_text_right, NK_WIDGET_ALIGN_CENTERED | NK_WIDGET_ALIGN_MIDDLE, NK_TEXT_RIGHT); + nk_checkbox_label(ctx, "CheckRight TextRight", &checkbox_right_text_right, NK_WIDGET_LEFT, NK_TEXT_RIGHT); + nk_checkbox_label(ctx, "CheckRight TextLeft", &checkbox_right_text_left, NK_WIDGET_RIGHT, NK_TEXT_LEFT); nk_layout_row_static(ctx, 30, 80, 3); option_left = nk_option_label(ctx, "optionA", option_left == A, NK_WIDGET_LEFT, NK_TEXT_LEFT) ? A : option_left; diff --git a/nuklear.h b/nuklear.h index 12696cb..4a93bae 100644 --- a/nuklear.h +++ b/nuklear.h @@ -24811,7 +24811,6 @@ nk_do_toggle(nk_flags *state, const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment) { int was_active; - struct nk_rect allocated_space; struct nk_rect bounds; struct nk_rect select; struct nk_rect cursor; @@ -24826,13 +24825,6 @@ nk_do_toggle(nk_flags *state, r.w = NK_MAX(r.w, font->height + 2 * style->padding.x); r.h = NK_MAX(r.h, font->height + 2 * style->padding.y); - allocated_space = r; - - if (widget_alignment & NK_WIDGET_ALIGN_RIGHT) { - r.x = r.x + r.w - font->height - style->padding.x; - r.w = font->height; - } - /* add additional touch padding for touch screen devices */ bounds.x = r.x - style->touch_padding.x; bounds.y = r.y - style->touch_padding.y; @@ -24842,8 +24834,37 @@ nk_do_toggle(nk_flags *state, /* calculate the selector space */ select.w = font->height; select.h = select.w; - select.y = r.y + r.h/2.0f - select.h/2.0f; - select.x = r.x; + + if (widget_alignment & NK_WIDGET_ALIGN_RIGHT) { + select.x = r.x + r.w - font->height; + + /* label in front of the selector */ + label.x = r.x; + label.w = r.w - select.w - style->spacing * 2; + } else if (widget_alignment & NK_WIDGET_ALIGN_CENTERED) { + select.x = (r.x + r.w) / 2; + + /* label in front of selector */ + label.x = r.x; + label.w = r.w / 2 - select.w - style->spacing * 2; + } else { /* Default: NK_WIDGET_ALIGN_LEFT */ + select.x = r.x; + + /* label behind the selector */ + label.x = select.x + select.w + style->spacing; + label.w = NK_MAX(r.x + r.w, label.x) - label.x; + } + + if (widget_alignment & NK_WIDGET_ALIGN_TOP) { + select.y = r.y; + } else if (widget_alignment & NK_WIDGET_ALIGN_BOTTOM) { + select.y = r.y + r.h - select.h - 2 * style->padding.y; + } else { /* Default: NK_WIDGET_ALIGN_MIDDLE */ + select.y = r.y + r.h/2.0f - select.h/2.0f; + } + + label.y = select.y; + label.h = select.w; /* calculate the bounds of the cursor inside the selector */ cursor.x = select.x + style->padding.x + style->border; @@ -24851,18 +24872,6 @@ nk_do_toggle(nk_flags *state, cursor.w = select.w - (2 * style->padding.x + 2 * style->border); cursor.h = select.h - (2 * style->padding.y + 2 * style->border); - label.y = select.y; - label.h = select.w; - if (widget_alignment & NK_WIDGET_ALIGN_RIGHT) { - /* label in front of the selector */ - label.x = allocated_space.x; - label.w = allocated_space.w - select.w - style->spacing * 2; - } else { - /* label behind the selector */ - label.x = select.x + select.w + style->spacing; - label.w = NK_MAX(r.x + r.w, label.x) - label.x; - } - /* update selector */ was_active = *active; *active = nk_toggle_behavior(in, bounds, state, *active); @@ -30013,6 +30022,8 @@ nk_tooltipfv(struct nk_context *ctx, const char *fmt, va_list args) /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// +/// - 2023/11/26 (5.0.0) - BREAKING CHANGE: Added alignment to check boxes and radio buttons. They +/// all now require a widget and text alignment parameter. /// - 2023/10/11 (4.11.0) - Added nk_widget_disable_begin() and nk_widget_disable_end() /// - 2022/12/23 (4.10.6) - Fix incorrect glyph index in nk_font_bake() /// - 2022/12/17 (4.10.5) - Fix nk_font_bake_pack() using TTC font offset incorrectly diff --git a/src/nuklear_toggle.c b/src/nuklear_toggle.c index 9985925..c4b8159 100644 --- a/src/nuklear_toggle.c +++ b/src/nuklear_toggle.c @@ -115,7 +115,6 @@ nk_do_toggle(nk_flags *state, const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment) { int was_active; - struct nk_rect allocated_space; struct nk_rect bounds; struct nk_rect select; struct nk_rect cursor; @@ -130,13 +129,6 @@ nk_do_toggle(nk_flags *state, r.w = NK_MAX(r.w, font->height + 2 * style->padding.x); r.h = NK_MAX(r.h, font->height + 2 * style->padding.y); - allocated_space = r; - - if (widget_alignment & NK_WIDGET_ALIGN_RIGHT) { - r.x = r.x + r.w - font->height - style->padding.x; - r.w = font->height; - } - /* add additional touch padding for touch screen devices */ bounds.x = r.x - style->touch_padding.x; bounds.y = r.y - style->touch_padding.y; @@ -146,8 +138,37 @@ nk_do_toggle(nk_flags *state, /* calculate the selector space */ select.w = font->height; select.h = select.w; - select.y = r.y + r.h/2.0f - select.h/2.0f; - select.x = r.x; + + if (widget_alignment & NK_WIDGET_ALIGN_RIGHT) { + select.x = r.x + r.w - font->height; + + /* label in front of the selector */ + label.x = r.x; + label.w = r.w - select.w - style->spacing * 2; + } else if (widget_alignment & NK_WIDGET_ALIGN_CENTERED) { + select.x = (r.x + r.w) / 2; + + /* label in front of selector */ + label.x = r.x; + label.w = r.w / 2 - select.w - style->spacing * 2; + } else { /* Default: NK_WIDGET_ALIGN_LEFT */ + select.x = r.x; + + /* label behind the selector */ + label.x = select.x + select.w + style->spacing; + label.w = NK_MAX(r.x + r.w, label.x) - label.x; + } + + if (widget_alignment & NK_WIDGET_ALIGN_TOP) { + select.y = r.y; + } else if (widget_alignment & NK_WIDGET_ALIGN_BOTTOM) { + select.y = r.y + r.h - select.h - 2 * style->padding.y; + } else { /* Default: NK_WIDGET_ALIGN_MIDDLE */ + select.y = r.y + r.h/2.0f - select.h/2.0f; + } + + label.y = select.y; + label.h = select.w; /* calculate the bounds of the cursor inside the selector */ cursor.x = select.x + style->padding.x + style->border; @@ -155,18 +176,6 @@ nk_do_toggle(nk_flags *state, cursor.w = select.w - (2 * style->padding.x + 2 * style->border); cursor.h = select.h - (2 * style->padding.y + 2 * style->border); - label.y = select.y; - label.h = select.w; - if (widget_alignment & NK_WIDGET_ALIGN_RIGHT) { - /* label in front of the selector */ - label.x = allocated_space.x; - label.w = allocated_space.w - select.w - style->spacing * 2; - } else { - /* label behind the selector */ - label.x = select.x + select.w + style->spacing; - label.w = NK_MAX(r.x + r.w, label.x) - label.x; - } - /* update selector */ was_active = *active; *active = nk_toggle_behavior(in, bounds, state, *active); From 8af4468cce12acb979024c2778fd07e95a18e6a4 Mon Sep 17 00:00:00 2001 From: Jacob Ahnstedt Date: Sun, 26 Nov 2023 14:45:06 +0100 Subject: [PATCH 079/106] Fixed centered not being quite in the center --- nuklear.h | 4 ++-- src/nuklear_toggle.c | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/nuklear.h b/nuklear.h index 4a93bae..ba03343 100644 --- a/nuklear.h +++ b/nuklear.h @@ -24842,11 +24842,11 @@ nk_do_toggle(nk_flags *state, label.x = r.x; label.w = r.w - select.w - style->spacing * 2; } else if (widget_alignment & NK_WIDGET_ALIGN_CENTERED) { - select.x = (r.x + r.w) / 2; + select.x = r.x + (r.w - select.w) / 2; /* label in front of selector */ label.x = r.x; - label.w = r.w / 2 - select.w - style->spacing * 2; + label.w = (r.w - select.w - style->spacing * 2) / 2; } else { /* Default: NK_WIDGET_ALIGN_LEFT */ select.x = r.x; diff --git a/src/nuklear_toggle.c b/src/nuklear_toggle.c index c4b8159..9cc9271 100644 --- a/src/nuklear_toggle.c +++ b/src/nuklear_toggle.c @@ -146,11 +146,11 @@ nk_do_toggle(nk_flags *state, label.x = r.x; label.w = r.w - select.w - style->spacing * 2; } else if (widget_alignment & NK_WIDGET_ALIGN_CENTERED) { - select.x = (r.x + r.w) / 2; + select.x = r.x + (r.w - select.w) / 2; /* label in front of selector */ label.x = r.x; - label.w = r.w / 2 - select.w - style->spacing * 2; + label.w = (r.w - select.w - style->spacing * 2) / 2; } else { /* Default: NK_WIDGET_ALIGN_LEFT */ select.x = r.x; From 44bd2385021835b45a1c447aa3e0a9f740ff9de0 Mon Sep 17 00:00:00 2001 From: Jacob Ahnstedt Date: Mon, 27 Nov 2023 16:56:03 +0100 Subject: [PATCH 080/106] Fixed typo --- nuklear.h | 2 +- src/CHANGELOG | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nuklear.h b/nuklear.h index ba03343..c196827 100644 --- a/nuklear.h +++ b/nuklear.h @@ -30022,7 +30022,7 @@ nk_tooltipfv(struct nk_context *ctx, const char *fmt, va_list args) /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// -/// - 2023/11/26 (5.0.0) - BREAKING CHANGE: Added alignment to check boxes and radio buttons. They +/// - 2023/11/26 (5.0.0) - BREAKING CHANGE: Added alignment to checkboxes and radio buttons. They /// all now require a widget and text alignment parameter. /// - 2023/10/11 (4.11.0) - Added nk_widget_disable_begin() and nk_widget_disable_end() /// - 2022/12/23 (4.10.6) - Fix incorrect glyph index in nk_font_bake() diff --git a/src/CHANGELOG b/src/CHANGELOG index b0376ac..7464b9d 100644 --- a/src/CHANGELOG +++ b/src/CHANGELOG @@ -7,7 +7,7 @@ /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// -/// - 2023/11/26 (5.0.0) - BREAKING CHANGE: Added alignment to check boxes and radio buttons. They +/// - 2023/11/26 (5.0.0) - BREAKING CHANGE: Added alignment to checkboxes and radio buttons. They /// all now require a widget and text alignment parameter. /// - 2023/10/11 (4.11.0) - Added nk_widget_disable_begin() and nk_widget_disable_end() /// - 2022/12/23 (4.10.6) - Fix incorrect glyph index in nk_font_bake() From 9af38697283b2df9b9e360feffdabdb6f7f8215a Mon Sep 17 00:00:00 2001 From: Jacob Ahnstedt Date: Tue, 28 Nov 2023 09:52:30 +0100 Subject: [PATCH 081/106] Made the PR not break current API --- clib.json | 2 +- demo/allegro5/main.c | 4 +- demo/common/overview.c | 64 ++++++------- demo/d3d11/main.c | 4 +- demo/d3d12/main.c | 4 +- demo/d3d9/main.c | 4 +- demo/gdi/main.c | 4 +- demo/gdip/main.c | 4 +- demo/glfw_opengl2/main.c | 4 +- demo/glfw_opengl3/main.c | 4 +- demo/glfw_opengl4/main.c | 4 +- demo/glfw_vulkan/main.c | 4 +- demo/sdl2surface_rawfb/main.c | 4 +- demo/sdl_opengl2/main.c | 4 +- demo/sdl_opengl3/main.c | 4 +- demo/sdl_opengles2/main.c | 4 +- demo/sdl_renderer/main.c | 4 +- demo/sfml_opengl2/main.cpp | 4 +- demo/sfml_opengl3/main.cpp | 4 +- demo/wayland_rawfb/main.c | 4 +- demo/x11/main.c | 4 +- demo/x11_opengl2/main.c | 4 +- demo/x11_opengl3/main.c | 4 +- demo/x11_rawfb/main.c | 4 +- demo/x11_xft/main.c | 4 +- example/extended.c | 6 +- example/skinning.c | 8 +- nuklear.h | 164 +++++++++++++++++++++++++++------- src/CHANGELOG | 3 +- src/nuklear.h | 23 +++-- src/nuklear_toggle.c | 138 +++++++++++++++++++++++----- 31 files changed, 350 insertions(+), 150 deletions(-) diff --git a/clib.json b/clib.json index c9605df..bf66e59 100644 --- a/clib.json +++ b/clib.json @@ -1,6 +1,6 @@ { "name": "nuklear", - "version": "5.0.0", + "version": "4.12.0", "repo": "Immediate-Mode-UI/Nuklear", "description": "A small ANSI C gui toolkit", "keywords": ["gl", "ui", "toolkit"], diff --git a/demo/allegro5/main.c b/demo/allegro5/main.c index ff2228c..ee01de7 100644 --- a/demo/allegro5/main.c +++ b/demo/allegro5/main.c @@ -165,8 +165,8 @@ int main(void) if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(ctx, 22, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); } diff --git a/demo/common/overview.c b/demo/common/overview.c index d4c90b1..261679c 100644 --- a/demo/common/overview.c +++ b/demo/common/overview.c @@ -43,7 +43,7 @@ overview(struct nk_context *ctx) show_app_about = nk_true; nk_progress(ctx, &prog, 100, NK_MODIFIABLE); nk_slider_int(ctx, 0, &slider, 16, 1); - nk_checkbox_label(ctx, "check", &check, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_label(ctx, "check", &check); nk_menu_end(ctx); } /* menu #2 */ @@ -102,7 +102,7 @@ overview(struct nk_context *ctx) nk_layout_row_push(ctx, 70); nk_progress(ctx, &mprog, 100, NK_MODIFIABLE); nk_slider_int(ctx, 0, &mslider, 16, 1); - nk_checkbox_label(ctx, "check", &mcheck, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_label(ctx, "check", &mcheck); nk_menubar_end(ctx); } @@ -123,15 +123,15 @@ overview(struct nk_context *ctx) /* window flags */ if (nk_tree_push(ctx, NK_TREE_TAB, "Window", NK_MINIMIZED)) { nk_layout_row_dynamic(ctx, 30, 2); - nk_checkbox_label(ctx, "Menu", &show_menu, NK_WIDGET_LEFT, NK_TEXT_LEFT); - nk_checkbox_flags_label(ctx, "Titlebar", &window_flags, NK_WINDOW_TITLE, NK_WIDGET_LEFT, NK_TEXT_LEFT); - nk_checkbox_flags_label(ctx, "Border", &window_flags, NK_WINDOW_BORDER, NK_WIDGET_LEFT, NK_TEXT_LEFT); - nk_checkbox_flags_label(ctx, "Resizable", &window_flags, NK_WINDOW_SCALABLE, NK_WIDGET_LEFT, NK_TEXT_LEFT); - nk_checkbox_flags_label(ctx, "Movable", &window_flags, NK_WINDOW_MOVABLE, NK_WIDGET_LEFT, NK_TEXT_LEFT); - nk_checkbox_flags_label(ctx, "No Scrollbar", &window_flags, NK_WINDOW_NO_SCROLLBAR, NK_WIDGET_LEFT, NK_TEXT_LEFT); - nk_checkbox_flags_label(ctx, "Minimizable", &window_flags, NK_WINDOW_MINIMIZABLE, NK_WIDGET_LEFT, NK_TEXT_LEFT); - nk_checkbox_flags_label(ctx, "Scale Left", &window_flags, NK_WINDOW_SCALE_LEFT, NK_WIDGET_LEFT, NK_TEXT_LEFT); - nk_checkbox_label(ctx, "Disable widgets", &disable_widgets, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_label(ctx, "Menu", &show_menu); + nk_checkbox_flags_label(ctx, "Titlebar", &window_flags, NK_WINDOW_TITLE); + nk_checkbox_flags_label(ctx, "Border", &window_flags, NK_WINDOW_BORDER); + nk_checkbox_flags_label(ctx, "Resizable", &window_flags, NK_WINDOW_SCALABLE); + nk_checkbox_flags_label(ctx, "Movable", &window_flags, NK_WINDOW_MOVABLE); + nk_checkbox_flags_label(ctx, "No Scrollbar", &window_flags, NK_WINDOW_NO_SCROLLBAR); + nk_checkbox_flags_label(ctx, "Minimizable", &window_flags, NK_WINDOW_MINIMIZABLE); + nk_checkbox_flags_label(ctx, "Scale Left", &window_flags, NK_WINDOW_SCALE_LEFT); + nk_checkbox_label(ctx, "Disable widgets", &disable_widgets); nk_tree_pop(ctx); } @@ -213,20 +213,20 @@ overview(struct nk_context *ctx) static const float ratio[] = {120, 150}; nk_layout_row_dynamic(ctx, 0, 1); - nk_checkbox_label(ctx, "CheckLeft TextLeft", &checkbox_left_text_left, NK_WIDGET_LEFT, NK_TEXT_LEFT); - nk_checkbox_label(ctx, "CheckCenter TextRight", &checkbox_centered_text_right, NK_WIDGET_ALIGN_CENTERED | NK_WIDGET_ALIGN_MIDDLE, NK_TEXT_RIGHT); - nk_checkbox_label(ctx, "CheckRight TextRight", &checkbox_right_text_right, NK_WIDGET_LEFT, NK_TEXT_RIGHT); - nk_checkbox_label(ctx, "CheckRight TextLeft", &checkbox_right_text_left, NK_WIDGET_RIGHT, NK_TEXT_LEFT); + nk_checkbox_label(ctx, "CheckLeft TextLeft", &checkbox_left_text_left); + nk_checkbox_label_align(ctx, "CheckCenter TextRight", &checkbox_centered_text_right, NK_WIDGET_ALIGN_CENTERED | NK_WIDGET_ALIGN_MIDDLE, NK_TEXT_RIGHT); + nk_checkbox_label_align(ctx, "CheckRight TextRight", &checkbox_right_text_right, NK_WIDGET_LEFT, NK_TEXT_RIGHT); + nk_checkbox_label_align(ctx, "CheckRight TextLeft", &checkbox_right_text_left, NK_WIDGET_RIGHT, NK_TEXT_LEFT); nk_layout_row_static(ctx, 30, 80, 3); - option_left = nk_option_label(ctx, "optionA", option_left == A, NK_WIDGET_LEFT, NK_TEXT_LEFT) ? A : option_left; - option_left = nk_option_label(ctx, "optionB", option_left == B, NK_WIDGET_LEFT, NK_TEXT_LEFT) ? B : option_left; - option_left = nk_option_label(ctx, "optionC", option_left == C, NK_WIDGET_LEFT, NK_TEXT_LEFT) ? C : option_left; + option_left = nk_option_label(ctx, "optionA", option_left == A) ? A : option_left; + option_left = nk_option_label(ctx, "optionB", option_left == B) ? B : option_left; + option_left = nk_option_label(ctx, "optionC", option_left == C) ? C : option_left; nk_layout_row_static(ctx, 30, 80, 3); - option_right = nk_option_label(ctx, "optionA", option_right == A, NK_WIDGET_RIGHT, NK_TEXT_RIGHT) ? A : option_right; - option_right = nk_option_label(ctx, "optionB", option_right == B, NK_WIDGET_RIGHT, NK_TEXT_RIGHT) ? B : option_right; - option_right = nk_option_label(ctx, "optionC", option_right == C, NK_WIDGET_RIGHT, NK_TEXT_RIGHT) ? C : option_right; + option_right = nk_option_label_align(ctx, "optionA", option_right == A, NK_WIDGET_RIGHT, NK_TEXT_RIGHT) ? A : option_right; + option_right = nk_option_label_align(ctx, "optionB", option_right == B, NK_WIDGET_RIGHT, NK_TEXT_RIGHT) ? B : option_right; + option_right = nk_option_label_align(ctx, "optionC", option_right == C, NK_WIDGET_RIGHT, NK_TEXT_RIGHT) ? C : option_right; nk_layout_row(ctx, NK_STATIC, 30, 2, ratio); nk_labelf(ctx, NK_TEXT_LEFT, "Slider int"); @@ -263,7 +263,7 @@ overview(struct nk_context *ctx) { static int inactive = 1; nk_layout_row_dynamic(ctx, 30, 1); - nk_checkbox_label(ctx, "Inactive", &inactive, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_label(ctx, "Inactive", &inactive); nk_layout_row_static(ctx, 30, 80, 1); if (inactive) { @@ -379,8 +379,8 @@ overview(struct nk_context *ctx) #endif nk_layout_row_dynamic(ctx, 25, 2); - col_mode = nk_option_label(ctx, "RGB", col_mode == COL_RGB, NK_WIDGET_LEFT, NK_TEXT_LEFT) ? COL_RGB : col_mode; - col_mode = nk_option_label(ctx, "HSV", col_mode == COL_HSV, NK_WIDGET_LEFT, NK_TEXT_LEFT) ? COL_HSV : col_mode; + col_mode = nk_option_label(ctx, "RGB", col_mode == COL_RGB) ? COL_RGB : col_mode; + col_mode = nk_option_label(ctx, "HSV", col_mode == COL_HSV) ? COL_HSV : col_mode; nk_layout_row_dynamic(ctx, 25, 1); if (col_mode == COL_RGB) { @@ -416,10 +416,10 @@ overview(struct nk_context *ctx) sprintf(buffer, "%lu", sum); if (nk_combo_begin_label(ctx, buffer, nk_vec2(200,200))) { nk_layout_row_dynamic(ctx, 30, 1); - nk_checkbox_label(ctx, weapons[0], &check_values[0], NK_WIDGET_LEFT, NK_TEXT_LEFT); - nk_checkbox_label(ctx, weapons[1], &check_values[1], NK_WIDGET_LEFT, NK_TEXT_LEFT); - nk_checkbox_label(ctx, weapons[2], &check_values[2], NK_WIDGET_LEFT, NK_TEXT_LEFT); - nk_checkbox_label(ctx, weapons[3], &check_values[3], NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_label(ctx, weapons[0], &check_values[0]); + nk_checkbox_label(ctx, weapons[1], &check_values[1]); + nk_checkbox_label(ctx, weapons[2], &check_values[2]); + nk_checkbox_label(ctx, weapons[3], &check_values[3]); nk_combo_end(ctx); } @@ -728,7 +728,7 @@ overview(struct nk_context *ctx) static int slider = 10; nk_layout_row_dynamic(ctx, 25, 1); - nk_checkbox_label(ctx, "Menu", &show_menu, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_label(ctx, "Menu", &show_menu); nk_progress(ctx, &prog, 100, NK_MODIFIABLE); nk_slider_int(ctx, 0, &slider, 16, 1); if (nk_contextual_item_label(ctx, "About", NK_TEXT_CENTERED)) @@ -895,9 +895,9 @@ overview(struct nk_context *ctx) if (group_titlebar) group_flags |= NK_WINDOW_TITLE; nk_layout_row_dynamic(ctx, 30, 3); - nk_checkbox_label(ctx, "Titlebar", &group_titlebar, NK_WIDGET_LEFT, NK_TEXT_LEFT); - nk_checkbox_label(ctx, "Border", &group_border, NK_WIDGET_LEFT, NK_TEXT_LEFT); - nk_checkbox_label(ctx, "No Scrollbar", &group_no_scrollbar, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_label(ctx, "Titlebar", &group_titlebar); + nk_checkbox_label(ctx, "Border", &group_border); + nk_checkbox_label(ctx, "No Scrollbar", &group_no_scrollbar); nk_layout_row_begin(ctx, NK_STATIC, 22, 3); nk_layout_row_push(ctx, 50); diff --git a/demo/d3d11/main.c b/demo/d3d11/main.c index 63bb495..338dde2 100644 --- a/demo/d3d11/main.c +++ b/demo/d3d11/main.c @@ -250,8 +250,8 @@ int main(void) if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(ctx, 22, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/d3d12/main.c b/demo/d3d12/main.c index 90d8ab9..57e7bc3 100644 --- a/demo/d3d12/main.c +++ b/demo/d3d12/main.c @@ -342,8 +342,8 @@ int main(void) if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(ctx, 22, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/d3d9/main.c b/demo/d3d9/main.c index 03a9530..638c584 100644 --- a/demo/d3d9/main.c +++ b/demo/d3d9/main.c @@ -255,8 +255,8 @@ int main(void) if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(ctx, 22, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/gdi/main.c b/demo/gdi/main.c index 9410e97..281f82b 100644 --- a/demo/gdi/main.c +++ b/demo/gdi/main.c @@ -164,8 +164,8 @@ int main(void) if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(ctx, 22, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); } diff --git a/demo/gdip/main.c b/demo/gdip/main.c index 78db5ed..7151964 100644 --- a/demo/gdip/main.c +++ b/demo/gdip/main.c @@ -159,8 +159,8 @@ int main(void) if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(ctx, 22, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); } diff --git a/demo/glfw_opengl2/main.c b/demo/glfw_opengl2/main.c index 6296a76..8d97773 100644 --- a/demo/glfw_opengl2/main.c +++ b/demo/glfw_opengl2/main.c @@ -172,8 +172,8 @@ int main(void) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/glfw_opengl3/main.c b/demo/glfw_opengl3/main.c index cbe692e..8eb749d 100644 --- a/demo/glfw_opengl3/main.c +++ b/demo/glfw_opengl3/main.c @@ -158,8 +158,8 @@ int main(void) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/glfw_opengl4/main.c b/demo/glfw_opengl4/main.c index 502d1ad..176a1ef 100644 --- a/demo/glfw_opengl4/main.c +++ b/demo/glfw_opengl4/main.c @@ -168,8 +168,8 @@ int main(void) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/glfw_vulkan/main.c b/demo/glfw_vulkan/main.c index 0bc17b4..555a5aa 100644 --- a/demo/glfw_vulkan/main.c +++ b/demo/glfw_vulkan/main.c @@ -2148,9 +2148,9 @@ int main(void) { fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) + if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) + if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); diff --git a/demo/sdl2surface_rawfb/main.c b/demo/sdl2surface_rawfb/main.c index c2238d9..a8b661a 100644 --- a/demo/sdl2surface_rawfb/main.c +++ b/demo/sdl2surface_rawfb/main.c @@ -216,8 +216,8 @@ int main(int argc, char **argv) printf("button pressed\n"); } nk_layout_row_dynamic(&(context->ctx), 40, 2); - if (nk_option_label(&(context->ctx), "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; - if (nk_option_label(&(context->ctx), "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; + if (nk_option_label(&(context->ctx), "easy", op == EASY)) op = EASY; + if (nk_option_label(&(context->ctx), "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(&(context->ctx), 45, 1); nk_property_int(&(context->ctx), "Compression:", 0, &property, 100, 10, 1); } diff --git a/demo/sdl_opengl2/main.c b/demo/sdl_opengl2/main.c index 508d42a..45c51d2 100644 --- a/demo/sdl_opengl2/main.c +++ b/demo/sdl_opengl2/main.c @@ -154,8 +154,8 @@ main(int argc, char *argv[]) if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/sdl_opengl3/main.c b/demo/sdl_opengl3/main.c index 0483626..e039a2f 100644 --- a/demo/sdl_opengl3/main.c +++ b/demo/sdl_opengl3/main.c @@ -164,8 +164,8 @@ int main(int argc, char *argv[]) if (nk_button_label(ctx, "button")) printf("button pressed!\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(ctx, 22, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/sdl_opengles2/main.c b/demo/sdl_opengles2/main.c index c527e5f..b114159 100644 --- a/demo/sdl_opengles2/main.c +++ b/demo/sdl_opengles2/main.c @@ -128,8 +128,8 @@ MainLoop(void* loopArg){ if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); } diff --git a/demo/sdl_renderer/main.c b/demo/sdl_renderer/main.c index a8af16b..940ea84 100644 --- a/demo/sdl_renderer/main.c +++ b/demo/sdl_renderer/main.c @@ -192,8 +192,8 @@ main(int argc, char *argv[]) if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/sfml_opengl2/main.cpp b/demo/sfml_opengl2/main.cpp index 6594ad3..82f8e0f 100644 --- a/demo/sfml_opengl2/main.cpp +++ b/demo/sfml_opengl2/main.cpp @@ -139,8 +139,8 @@ int main(void) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/sfml_opengl3/main.cpp b/demo/sfml_opengl3/main.cpp index 8fa6df8..22aafcc 100644 --- a/demo/sfml_opengl3/main.cpp +++ b/demo/sfml_opengl3/main.cpp @@ -146,8 +146,8 @@ int main(void) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/wayland_rawfb/main.c b/demo/wayland_rawfb/main.c index baf4cc8..cf60eed 100644 --- a/demo/wayland_rawfb/main.c +++ b/demo/wayland_rawfb/main.c @@ -533,8 +533,8 @@ int main () printf("button pressed\n"); } nk_layout_row_dynamic(&(nk_wayland_ctx.ctx), 30, 2); - if (nk_option_label(&(nk_wayland_ctx.ctx), "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; - if (nk_option_label(&(nk_wayland_ctx.ctx), "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; + if (nk_option_label(&(nk_wayland_ctx.ctx), "easy", op == EASY)) op = EASY; + if (nk_option_label(&(nk_wayland_ctx.ctx), "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(&(nk_wayland_ctx.ctx), 25, 1); nk_property_int(&(nk_wayland_ctx.ctx), "Compression:", 0, &property, 100, 10, 1); } diff --git a/demo/x11/main.c b/demo/x11/main.c index 4cbf4c4..0d02ad7 100644 --- a/demo/x11/main.c +++ b/demo/x11/main.c @@ -192,8 +192,8 @@ main(void) if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); } diff --git a/demo/x11_opengl2/main.c b/demo/x11_opengl2/main.c index 679f7b1..2dc845e 100644 --- a/demo/x11_opengl2/main.c +++ b/demo/x11_opengl2/main.c @@ -296,8 +296,8 @@ int main(void) if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/x11_opengl3/main.c b/demo/x11_opengl3/main.c index 4553469..a4a3008 100644 --- a/demo/x11_opengl3/main.c +++ b/demo/x11_opengl3/main.c @@ -293,8 +293,8 @@ int main(void) if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); diff --git a/demo/x11_rawfb/main.c b/demo/x11_rawfb/main.c index 5a19bb3..52a1c93 100644 --- a/demo/x11_rawfb/main.c +++ b/demo/x11_rawfb/main.c @@ -229,8 +229,8 @@ main(void) if (nk_button_label(&rawfb->ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(&rawfb->ctx, 30, 2); - if (nk_option_label(&rawfb->ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; - if (nk_option_label(&rawfb->ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; + if (nk_option_label(&rawfb->ctx, "easy", op == EASY)) op = EASY; + if (nk_option_label(&rawfb->ctx, "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(&rawfb->ctx, 25, 1); nk_property_int(&rawfb->ctx, "Compression:", 0, &property, 100, 10, 1); } diff --git a/demo/x11_xft/main.c b/demo/x11_xft/main.c index b4cc2ca..263f43b 100644 --- a/demo/x11_xft/main.c +++ b/demo/x11_xft/main.c @@ -196,8 +196,8 @@ main(void) if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); - if (nk_option_label(ctx, "easy", op == EASY, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = EASY; - if (nk_option_label(ctx, "hard", op == HARD, NK_WIDGET_LEFT, NK_TEXT_LEFT)) op = HARD; + if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; + if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(ctx, 25, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); } diff --git a/example/extended.c b/example/extended.c index 491af60..4e1211b 100644 --- a/example/extended.c +++ b/example/extended.c @@ -201,7 +201,7 @@ grid_demo(struct nk_context *ctx, struct media *media) nk_label(ctx, "Binary:", NK_TEXT_RIGHT); nk_edit_string(ctx, NK_EDIT_FIELD, text[2], &text_len[2], 64, nk_filter_binary); nk_label(ctx, "Checkbox:", NK_TEXT_RIGHT); - nk_checkbox_label(ctx, "Check me", &check, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_label(ctx, "Check me", &check); nk_label(ctx, "Combobox:", NK_TEXT_RIGHT); if (nk_combo_begin_label(ctx, items[selected_item], nk_vec2(nk_widget_width(ctx), 200))) { nk_layout_row_dynamic(ctx, 25, 1); @@ -433,9 +433,9 @@ basic_demo(struct nk_context *ctx, struct media *media) *------------------------------------------------*/ ui_header(ctx, media, "Checkbox"); ui_widget(ctx, media, 30); - nk_checkbox_label(ctx, "Flag 1", &check0, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_label(ctx, "Flag 1", &check0); ui_widget(ctx, media, 30); - nk_checkbox_label(ctx, "Flag 2", &check1, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_checkbox_label(ctx, "Flag 2", &check1); /*------------------------------------------------ * PROGRESSBAR diff --git a/example/skinning.c b/example/skinning.c index fb6c352..fab9ce3 100644 --- a/example/skinning.c +++ b/example/skinning.c @@ -754,10 +754,10 @@ int main(int argc, char *argv[]) nk_layout_row_dynamic(&ctx, 20, 1); nk_label(&ctx, "Label", NK_TEXT_LEFT); nk_layout_row_dynamic(&ctx, 30, 2); - nk_check_label(&ctx, "inactive", 0, NK_WIDGET_LEFT, NK_TEXT_LEFT); - nk_check_label(&ctx, "active", 1, NK_WIDGET_LEFT, NK_TEXT_LEFT); - nk_option_label(&ctx, "active", 1, NK_WIDGET_LEFT, NK_TEXT_LEFT); - nk_option_label(&ctx, "inactive", 0, NK_WIDGET_LEFT, NK_TEXT_LEFT); + nk_check_label(&ctx, "inactive", 0); + nk_check_label(&ctx, "active", 1); + nk_option_label(&ctx, "active", 1); + nk_option_label(&ctx, "inactive", 0); nk_layout_row_dynamic(&ctx, 30, 1); nk_slider_int(&ctx, 0, &slider, 16, 1); diff --git a/nuklear.h b/nuklear.h index c196827..6017837 100644 --- a/nuklear.h +++ b/nuklear.h @@ -3205,23 +3205,30 @@ NK_API nk_bool nk_button_pop_behavior(struct nk_context*); * CHECKBOX * * ============================================================================= */ -NK_API nk_bool nk_check_label(struct nk_context*, const char*, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); -NK_API nk_bool nk_check_text(struct nk_context*, const char*, int, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); -NK_API unsigned nk_check_flags_label(struct nk_context*, const char*, unsigned int flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment); -NK_API unsigned nk_check_flags_text(struct nk_context*, const char*, int, unsigned int flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment); -NK_API nk_bool nk_checkbox_label(struct nk_context*, const char*, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); -NK_API nk_bool nk_checkbox_text(struct nk_context*, const char*, int, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); -NK_API nk_bool nk_checkbox_flags_label(struct nk_context*, const char*, unsigned int *flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment); -NK_API nk_bool nk_checkbox_flags_text(struct nk_context*, const char*, int, unsigned int *flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_check_label(struct nk_context*, const char*, nk_bool active); +NK_API nk_bool nk_check_text(struct nk_context*, const char*, int, nk_bool active); +NK_API nk_bool nk_check_text_align(struct nk_context*, const char*, int, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API unsigned nk_check_flags_label(struct nk_context*, const char*, unsigned int flags, unsigned int value); +NK_API unsigned nk_check_flags_text(struct nk_context*, const char*, int, unsigned int flags, unsigned int value); +NK_API nk_bool nk_checkbox_label(struct nk_context*, const char*, nk_bool *active); +NK_API nk_bool nk_checkbox_label_align(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_checkbox_text(struct nk_context*, const char*, int, nk_bool *active); +NK_API nk_bool nk_checkbox_text_align(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_checkbox_flags_label(struct nk_context*, const char*, unsigned int *flags, unsigned int value); +NK_API nk_bool nk_checkbox_flags_text(struct nk_context*, const char*, int, unsigned int *flags, unsigned int value); /* ============================================================================= * * RADIO BUTTON * * ============================================================================= */ NK_API nk_bool nk_radio_label(struct nk_context*, const char*, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_radio_label_align(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); NK_API nk_bool nk_radio_text(struct nk_context*, const char*, int, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_radio_text_align(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); NK_API nk_bool nk_option_label(struct nk_context*, const char*, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_option_label_align(struct nk_context *ctx, const char *label, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); NK_API nk_bool nk_option_text(struct nk_context*, const char*, int, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_option_text_align(struct nk_context *ctx, const char *text, int len, nk_bool is_active, nk_flags widget_alignment, nk_flags text_alignment); /* ============================================================================= * * SELECTABLE @@ -24894,7 +24901,35 @@ nk_do_toggle(nk_flags *state, * * --------------------------------------------------------------*/ NK_API nk_bool -nk_check_text(struct nk_context *ctx, const char *text, int len, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment) +nk_check_text(struct nk_context *ctx, const char *text, int len, nk_bool active) +{ + struct nk_window *win; + struct nk_panel *layout; + const struct nk_input *in; + const struct nk_style *style; + + struct nk_rect bounds; + enum nk_widget_layout_states state; + + NK_ASSERT(ctx); + NK_ASSERT(ctx->current); + NK_ASSERT(ctx->current->layout); + if (!ctx || !ctx->current || !ctx->current->layout) + return active; + + win = ctx->current; + style = &ctx->style; + layout = win->layout; + + state = nk_widget(&bounds, ctx); + if (!state) return active; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &active, + text, len, NK_TOGGLE_CHECK, &style->checkbox, in, style->font, NK_WIDGET_LEFT, NK_TEXT_LEFT); + return active; +} +NK_API nk_bool +nk_check_text_align(struct nk_context *ctx, const char *text, int len, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment) { struct nk_window *win; struct nk_panel *layout; @@ -24923,20 +24958,20 @@ nk_check_text(struct nk_context *ctx, const char *text, int len, nk_bool active, } NK_API unsigned int nk_check_flags_text(struct nk_context *ctx, const char *text, int len, - unsigned int flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment) + unsigned int flags, unsigned int value) { int old_active; NK_ASSERT(ctx); NK_ASSERT(text); if (!ctx || !text) return flags; old_active = (int)((flags & value) & value); - if (nk_check_text(ctx, text, len, old_active, widget_alignment, text_alignment)) + if (nk_check_text(ctx, text, len, old_active)) flags |= value; else flags &= ~value; return flags; } NK_API nk_bool -nk_checkbox_text(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) +nk_checkbox_text(struct nk_context *ctx, const char *text, int len, nk_bool *active) { int old_val; NK_ASSERT(ctx); @@ -24944,12 +24979,24 @@ nk_checkbox_text(struct nk_context *ctx, const char *text, int len, nk_bool *act NK_ASSERT(active); if (!ctx || !text || !active) return 0; old_val = *active; - *active = nk_check_text(ctx, text, len, *active, widget_alignment, text_alignment); + *active = nk_check_text(ctx, text, len, *active); + return old_val != *active; +} +NK_API nk_bool +nk_checkbox_text_align(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) +{ + int old_val; + NK_ASSERT(ctx); + NK_ASSERT(text); + NK_ASSERT(active); + if (!ctx || !text || !active) return 0; + old_val = *active; + *active = nk_check_text_align(ctx, text, len, *active, widget_alignment, text_alignment); return old_val != *active; } NK_API nk_bool nk_checkbox_flags_text(struct nk_context *ctx, const char *text, int len, - unsigned int *flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment) + unsigned int *flags, unsigned int value) { nk_bool active; NK_ASSERT(ctx); @@ -24958,30 +25005,34 @@ nk_checkbox_flags_text(struct nk_context *ctx, const char *text, int len, if (!ctx || !text || !flags) return 0; active = (int)((*flags & value) & value); - if (nk_checkbox_text(ctx, text, len, &active, widget_alignment, text_alignment)) { + if (nk_checkbox_text(ctx, text, len, &active)) { if (active) *flags |= value; else *flags &= ~value; return 1; } return 0; } -NK_API nk_bool nk_check_label(struct nk_context *ctx, const char *label, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment) +NK_API nk_bool nk_check_label(struct nk_context *ctx, const char *label, nk_bool active) { - return nk_check_text(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); + return nk_check_text(ctx, label, nk_strlen(label), active); } NK_API unsigned int nk_check_flags_label(struct nk_context *ctx, const char *label, - unsigned int flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment) + unsigned int flags, unsigned int value) { - return nk_check_flags_text(ctx, label, nk_strlen(label), flags, value, widget_alignment, text_alignment); + return nk_check_flags_text(ctx, label, nk_strlen(label), flags, value); } -NK_API nk_bool nk_checkbox_label(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) +NK_API nk_bool nk_checkbox_label(struct nk_context *ctx, const char *label, nk_bool *active) { - return nk_checkbox_text(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); + return nk_checkbox_text(ctx, label, nk_strlen(label), active); +} +NK_API nk_bool nk_checkbox_label_align(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) +{ + return nk_checkbox_text_align(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); } NK_API nk_bool nk_checkbox_flags_label(struct nk_context *ctx, const char *label, - unsigned int *flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment) + unsigned int *flags, unsigned int value) { - return nk_checkbox_flags_text(ctx, label, nk_strlen(label), flags, value, widget_alignment, text_alignment); + return nk_checkbox_flags_text(ctx, label, nk_strlen(label), flags, value); } /*---------------------------------------------------------------- * @@ -24989,7 +25040,35 @@ NK_API nk_bool nk_checkbox_flags_label(struct nk_context *ctx, const char *label * * --------------------------------------------------------------*/ NK_API nk_bool -nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_active, nk_flags widget_alignment, nk_flags text_alignment) +nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_active) +{ + struct nk_window *win; + struct nk_panel *layout; + const struct nk_input *in; + const struct nk_style *style; + + struct nk_rect bounds; + enum nk_widget_layout_states state; + + NK_ASSERT(ctx); + NK_ASSERT(ctx->current); + NK_ASSERT(ctx->current->layout); + if (!ctx || !ctx->current || !ctx->current->layout) + return is_active; + + win = ctx->current; + style = &ctx->style; + layout = win->layout; + + state = nk_widget(&bounds, ctx); + if (!state) return (int)state; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &is_active, + text, len, NK_TOGGLE_OPTION, &style->option, in, style->font, NK_WIDGET_LEFT, NK_TEXT_LEFT); + return is_active; +} +NK_API nk_bool +nk_option_text_align(struct nk_context *ctx, const char *text, int len, nk_bool is_active, nk_flags widget_alignment, nk_flags text_alignment) { struct nk_window *win; struct nk_panel *layout; @@ -25017,7 +25096,7 @@ nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_act return is_active; } NK_API nk_bool -nk_radio_text(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) +nk_radio_text(struct nk_context *ctx, const char *text, int len, nk_bool *active) { int old_value; NK_ASSERT(ctx); @@ -25025,18 +25104,40 @@ nk_radio_text(struct nk_context *ctx, const char *text, int len, nk_bool *active NK_ASSERT(active); if (!ctx || !text || !active) return 0; old_value = *active; - *active = nk_option_text(ctx, text, len, old_value, widget_alignment, text_alignment); + *active = nk_option_text(ctx, text, len, old_value); return old_value != *active; } NK_API nk_bool -nk_option_label(struct nk_context *ctx, const char *label, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment) +nk_radio_text_align(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) { - return nk_option_text(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); + int old_value; + NK_ASSERT(ctx); + NK_ASSERT(text); + NK_ASSERT(active); + if (!ctx || !text || !active) return 0; + old_value = *active; + *active = nk_option_text_align(ctx, text, len, old_value, widget_alignment, text_alignment); + return old_value != *active; } NK_API nk_bool -nk_radio_label(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) +nk_option_label(struct nk_context *ctx, const char *label, nk_bool active) { - return nk_radio_text(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); + return nk_option_text(ctx, label, nk_strlen(label), active); +} +NK_API nk_bool +nk_option_label_align(struct nk_context *ctx, const char *label, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment) +{ + return nk_option_text_align(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); +} +NK_API nk_bool +nk_radio_label(struct nk_context *ctx, const char *label, nk_bool *active) +{ + return nk_radio_text(ctx, label, nk_strlen(label), active); +} +NK_API nk_bool +nk_radio_label_align(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) +{ + return nk_radio_text_align(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); } @@ -30022,8 +30123,7 @@ nk_tooltipfv(struct nk_context *ctx, const char *fmt, va_list args) /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// -/// - 2023/11/26 (5.0.0) - BREAKING CHANGE: Added alignment to checkboxes and radio buttons. They -/// all now require a widget and text alignment parameter. +/// - 2023/11/26 (4.12.0) - Added an alignment option to checkboxes and radio buttons. /// - 2023/10/11 (4.11.0) - Added nk_widget_disable_begin() and nk_widget_disable_end() /// - 2022/12/23 (4.10.6) - Fix incorrect glyph index in nk_font_bake() /// - 2022/12/17 (4.10.5) - Fix nk_font_bake_pack() using TTC font offset incorrectly diff --git a/src/CHANGELOG b/src/CHANGELOG index 7464b9d..b4114f8 100644 --- a/src/CHANGELOG +++ b/src/CHANGELOG @@ -7,8 +7,7 @@ /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// -/// - 2023/11/26 (5.0.0) - BREAKING CHANGE: Added alignment to checkboxes and radio buttons. They -/// all now require a widget and text alignment parameter. +/// - 2023/11/26 (4.12.0) - Added an alignment option to checkboxes and radio buttons. /// - 2023/10/11 (4.11.0) - Added nk_widget_disable_begin() and nk_widget_disable_end() /// - 2022/12/23 (4.10.6) - Fix incorrect glyph index in nk_font_bake() /// - 2022/12/17 (4.10.5) - Fix nk_font_bake_pack() using TTC font offset incorrectly diff --git a/src/nuklear.h b/src/nuklear.h index d7a6ad2..ba05180 100644 --- a/src/nuklear.h +++ b/src/nuklear.h @@ -2983,23 +2983,30 @@ NK_API nk_bool nk_button_pop_behavior(struct nk_context*); * CHECKBOX * * ============================================================================= */ -NK_API nk_bool nk_check_label(struct nk_context*, const char*, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); -NK_API nk_bool nk_check_text(struct nk_context*, const char*, int, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); -NK_API unsigned nk_check_flags_label(struct nk_context*, const char*, unsigned int flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment); -NK_API unsigned nk_check_flags_text(struct nk_context*, const char*, int, unsigned int flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment); -NK_API nk_bool nk_checkbox_label(struct nk_context*, const char*, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); -NK_API nk_bool nk_checkbox_text(struct nk_context*, const char*, int, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); -NK_API nk_bool nk_checkbox_flags_label(struct nk_context*, const char*, unsigned int *flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment); -NK_API nk_bool nk_checkbox_flags_text(struct nk_context*, const char*, int, unsigned int *flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_check_label(struct nk_context*, const char*, nk_bool active); +NK_API nk_bool nk_check_text(struct nk_context*, const char*, int, nk_bool active); +NK_API nk_bool nk_check_text_align(struct nk_context*, const char*, int, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API unsigned nk_check_flags_label(struct nk_context*, const char*, unsigned int flags, unsigned int value); +NK_API unsigned nk_check_flags_text(struct nk_context*, const char*, int, unsigned int flags, unsigned int value); +NK_API nk_bool nk_checkbox_label(struct nk_context*, const char*, nk_bool *active); +NK_API nk_bool nk_checkbox_label_align(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_checkbox_text(struct nk_context*, const char*, int, nk_bool *active); +NK_API nk_bool nk_checkbox_text_align(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_checkbox_flags_label(struct nk_context*, const char*, unsigned int *flags, unsigned int value); +NK_API nk_bool nk_checkbox_flags_text(struct nk_context*, const char*, int, unsigned int *flags, unsigned int value); /* ============================================================================= * * RADIO BUTTON * * ============================================================================= */ NK_API nk_bool nk_radio_label(struct nk_context*, const char*, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_radio_label_align(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); NK_API nk_bool nk_radio_text(struct nk_context*, const char*, int, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_radio_text_align(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); NK_API nk_bool nk_option_label(struct nk_context*, const char*, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_option_label_align(struct nk_context *ctx, const char *label, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); NK_API nk_bool nk_option_text(struct nk_context*, const char*, int, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_option_text_align(struct nk_context *ctx, const char *text, int len, nk_bool is_active, nk_flags widget_alignment, nk_flags text_alignment); /* ============================================================================= * * SELECTABLE diff --git a/src/nuklear_toggle.c b/src/nuklear_toggle.c index 9cc9271..a7c7f2a 100644 --- a/src/nuklear_toggle.c +++ b/src/nuklear_toggle.c @@ -198,7 +198,35 @@ nk_do_toggle(nk_flags *state, * * --------------------------------------------------------------*/ NK_API nk_bool -nk_check_text(struct nk_context *ctx, const char *text, int len, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment) +nk_check_text(struct nk_context *ctx, const char *text, int len, nk_bool active) +{ + struct nk_window *win; + struct nk_panel *layout; + const struct nk_input *in; + const struct nk_style *style; + + struct nk_rect bounds; + enum nk_widget_layout_states state; + + NK_ASSERT(ctx); + NK_ASSERT(ctx->current); + NK_ASSERT(ctx->current->layout); + if (!ctx || !ctx->current || !ctx->current->layout) + return active; + + win = ctx->current; + style = &ctx->style; + layout = win->layout; + + state = nk_widget(&bounds, ctx); + if (!state) return active; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &active, + text, len, NK_TOGGLE_CHECK, &style->checkbox, in, style->font, NK_WIDGET_LEFT, NK_TEXT_LEFT); + return active; +} +NK_API nk_bool +nk_check_text_align(struct nk_context *ctx, const char *text, int len, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment) { struct nk_window *win; struct nk_panel *layout; @@ -227,20 +255,20 @@ nk_check_text(struct nk_context *ctx, const char *text, int len, nk_bool active, } NK_API unsigned int nk_check_flags_text(struct nk_context *ctx, const char *text, int len, - unsigned int flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment) + unsigned int flags, unsigned int value) { int old_active; NK_ASSERT(ctx); NK_ASSERT(text); if (!ctx || !text) return flags; old_active = (int)((flags & value) & value); - if (nk_check_text(ctx, text, len, old_active, widget_alignment, text_alignment)) + if (nk_check_text(ctx, text, len, old_active)) flags |= value; else flags &= ~value; return flags; } NK_API nk_bool -nk_checkbox_text(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) +nk_checkbox_text(struct nk_context *ctx, const char *text, int len, nk_bool *active) { int old_val; NK_ASSERT(ctx); @@ -248,12 +276,24 @@ nk_checkbox_text(struct nk_context *ctx, const char *text, int len, nk_bool *act NK_ASSERT(active); if (!ctx || !text || !active) return 0; old_val = *active; - *active = nk_check_text(ctx, text, len, *active, widget_alignment, text_alignment); + *active = nk_check_text(ctx, text, len, *active); + return old_val != *active; +} +NK_API nk_bool +nk_checkbox_text_align(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) +{ + int old_val; + NK_ASSERT(ctx); + NK_ASSERT(text); + NK_ASSERT(active); + if (!ctx || !text || !active) return 0; + old_val = *active; + *active = nk_check_text_align(ctx, text, len, *active, widget_alignment, text_alignment); return old_val != *active; } NK_API nk_bool nk_checkbox_flags_text(struct nk_context *ctx, const char *text, int len, - unsigned int *flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment) + unsigned int *flags, unsigned int value) { nk_bool active; NK_ASSERT(ctx); @@ -262,30 +302,34 @@ nk_checkbox_flags_text(struct nk_context *ctx, const char *text, int len, if (!ctx || !text || !flags) return 0; active = (int)((*flags & value) & value); - if (nk_checkbox_text(ctx, text, len, &active, widget_alignment, text_alignment)) { + if (nk_checkbox_text(ctx, text, len, &active)) { if (active) *flags |= value; else *flags &= ~value; return 1; } return 0; } -NK_API nk_bool nk_check_label(struct nk_context *ctx, const char *label, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment) +NK_API nk_bool nk_check_label(struct nk_context *ctx, const char *label, nk_bool active) { - return nk_check_text(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); + return nk_check_text(ctx, label, nk_strlen(label), active); } NK_API unsigned int nk_check_flags_label(struct nk_context *ctx, const char *label, - unsigned int flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment) + unsigned int flags, unsigned int value) { - return nk_check_flags_text(ctx, label, nk_strlen(label), flags, value, widget_alignment, text_alignment); + return nk_check_flags_text(ctx, label, nk_strlen(label), flags, value); } -NK_API nk_bool nk_checkbox_label(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) +NK_API nk_bool nk_checkbox_label(struct nk_context *ctx, const char *label, nk_bool *active) { - return nk_checkbox_text(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); + return nk_checkbox_text(ctx, label, nk_strlen(label), active); +} +NK_API nk_bool nk_checkbox_label_align(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) +{ + return nk_checkbox_text_align(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); } NK_API nk_bool nk_checkbox_flags_label(struct nk_context *ctx, const char *label, - unsigned int *flags, unsigned int value, nk_flags widget_alignment, nk_flags text_alignment) + unsigned int *flags, unsigned int value) { - return nk_checkbox_flags_text(ctx, label, nk_strlen(label), flags, value, widget_alignment, text_alignment); + return nk_checkbox_flags_text(ctx, label, nk_strlen(label), flags, value); } /*---------------------------------------------------------------- * @@ -293,7 +337,35 @@ NK_API nk_bool nk_checkbox_flags_label(struct nk_context *ctx, const char *label * * --------------------------------------------------------------*/ NK_API nk_bool -nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_active, nk_flags widget_alignment, nk_flags text_alignment) +nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_active) +{ + struct nk_window *win; + struct nk_panel *layout; + const struct nk_input *in; + const struct nk_style *style; + + struct nk_rect bounds; + enum nk_widget_layout_states state; + + NK_ASSERT(ctx); + NK_ASSERT(ctx->current); + NK_ASSERT(ctx->current->layout); + if (!ctx || !ctx->current || !ctx->current->layout) + return is_active; + + win = ctx->current; + style = &ctx->style; + layout = win->layout; + + state = nk_widget(&bounds, ctx); + if (!state) return (int)state; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &is_active, + text, len, NK_TOGGLE_OPTION, &style->option, in, style->font, NK_WIDGET_LEFT, NK_TEXT_LEFT); + return is_active; +} +NK_API nk_bool +nk_option_text_align(struct nk_context *ctx, const char *text, int len, nk_bool is_active, nk_flags widget_alignment, nk_flags text_alignment) { struct nk_window *win; struct nk_panel *layout; @@ -321,7 +393,7 @@ nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_act return is_active; } NK_API nk_bool -nk_radio_text(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) +nk_radio_text(struct nk_context *ctx, const char *text, int len, nk_bool *active) { int old_value; NK_ASSERT(ctx); @@ -329,17 +401,39 @@ nk_radio_text(struct nk_context *ctx, const char *text, int len, nk_bool *active NK_ASSERT(active); if (!ctx || !text || !active) return 0; old_value = *active; - *active = nk_option_text(ctx, text, len, old_value, widget_alignment, text_alignment); + *active = nk_option_text(ctx, text, len, old_value); return old_value != *active; } NK_API nk_bool -nk_option_label(struct nk_context *ctx, const char *label, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment) +nk_radio_text_align(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) { - return nk_option_text(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); + int old_value; + NK_ASSERT(ctx); + NK_ASSERT(text); + NK_ASSERT(active); + if (!ctx || !text || !active) return 0; + old_value = *active; + *active = nk_option_text_align(ctx, text, len, old_value, widget_alignment, text_alignment); + return old_value != *active; } NK_API nk_bool -nk_radio_label(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) +nk_option_label(struct nk_context *ctx, const char *label, nk_bool active) { - return nk_radio_text(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); + return nk_option_text(ctx, label, nk_strlen(label), active); +} +NK_API nk_bool +nk_option_label_align(struct nk_context *ctx, const char *label, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment) +{ + return nk_option_text_align(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); +} +NK_API nk_bool +nk_radio_label(struct nk_context *ctx, const char *label, nk_bool *active) +{ + return nk_radio_text(ctx, label, nk_strlen(label), active); +} +NK_API nk_bool +nk_radio_label_align(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) +{ + return nk_radio_text_align(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); } From 0a7b4eec8ee7aba11ec2bc46b8581e29a07567cb Mon Sep 17 00:00:00 2001 From: Jacob Ahnstedt Date: Tue, 28 Nov 2023 09:58:43 +0100 Subject: [PATCH 082/106] Fixed missed removed alignment params --- nuklear.h | 8 ++++---- src/nuklear.h | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/nuklear.h b/nuklear.h index 6017837..bf41ea6 100644 --- a/nuklear.h +++ b/nuklear.h @@ -3221,13 +3221,13 @@ NK_API nk_bool nk_checkbox_flags_text(struct nk_context*, const char*, int, unsi * RADIO BUTTON * * ============================================================================= */ -NK_API nk_bool nk_radio_label(struct nk_context*, const char*, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_radio_label(struct nk_context*, const char*, nk_bool *active); NK_API nk_bool nk_radio_label_align(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); -NK_API nk_bool nk_radio_text(struct nk_context*, const char*, int, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_radio_text(struct nk_context*, const char*, int, nk_bool *active); NK_API nk_bool nk_radio_text_align(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); -NK_API nk_bool nk_option_label(struct nk_context*, const char*, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_option_label(struct nk_context*, const char*, nk_bool active); NK_API nk_bool nk_option_label_align(struct nk_context *ctx, const char *label, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); -NK_API nk_bool nk_option_text(struct nk_context*, const char*, int, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_option_text(struct nk_context*, const char*, int, nk_bool active); NK_API nk_bool nk_option_text_align(struct nk_context *ctx, const char *text, int len, nk_bool is_active, nk_flags widget_alignment, nk_flags text_alignment); /* ============================================================================= * diff --git a/src/nuklear.h b/src/nuklear.h index ba05180..7a4514b 100644 --- a/src/nuklear.h +++ b/src/nuklear.h @@ -2999,13 +2999,13 @@ NK_API nk_bool nk_checkbox_flags_text(struct nk_context*, const char*, int, unsi * RADIO BUTTON * * ============================================================================= */ -NK_API nk_bool nk_radio_label(struct nk_context*, const char*, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_radio_label(struct nk_context*, const char*, nk_bool *active); NK_API nk_bool nk_radio_label_align(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); -NK_API nk_bool nk_radio_text(struct nk_context*, const char*, int, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_radio_text(struct nk_context*, const char*, int, nk_bool *active); NK_API nk_bool nk_radio_text_align(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); -NK_API nk_bool nk_option_label(struct nk_context*, const char*, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_option_label(struct nk_context*, const char*, nk_bool active); NK_API nk_bool nk_option_label_align(struct nk_context *ctx, const char *label, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); -NK_API nk_bool nk_option_text(struct nk_context*, const char*, int, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); +NK_API nk_bool nk_option_text(struct nk_context*, const char*, int, nk_bool active); NK_API nk_bool nk_option_text_align(struct nk_context *ctx, const char *text, int len, nk_bool is_active, nk_flags widget_alignment, nk_flags text_alignment); /* ============================================================================= * From de3bf05b40b8ebadaa228cee47a35de1cbbfdd26 Mon Sep 17 00:00:00 2001 From: Jacob Ahnstedt Date: Tue, 12 Dec 2023 15:30:13 +0100 Subject: [PATCH 083/106] Replaced tabs with spaces --- src/nuklear_internal.h | 8 ++++---- src/nuklear_toggle.c | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/nuklear_internal.h b/src/nuklear_internal.h index 9f20d0d..a1c00bc 100644 --- a/src/nuklear_internal.h +++ b/src/nuklear_internal.h @@ -350,14 +350,14 @@ NK_LIB void nk_property(struct nk_context *ctx, const char *name, struct nk_prop #ifndef STBTT_malloc static void* nk_stbtt_malloc(nk_size size, void *user_data) { - struct nk_allocator *alloc = (struct nk_allocator *) user_data; - return alloc->alloc(alloc->userdata, 0, size); + struct nk_allocator *alloc = (struct nk_allocator *) user_data; + return alloc->alloc(alloc->userdata, 0, size); } static void nk_stbtt_free(void *ptr, void *user_data) { - struct nk_allocator *alloc = (struct nk_allocator *) user_data; - alloc->free(alloc->userdata, ptr); + struct nk_allocator *alloc = (struct nk_allocator *) user_data; + alloc->free(alloc->userdata, ptr); } #define STBTT_malloc(x,u) nk_stbtt_malloc(x,u) diff --git a/src/nuklear_toggle.c b/src/nuklear_toggle.c index a7c7f2a..cb9e56a 100644 --- a/src/nuklear_toggle.c +++ b/src/nuklear_toggle.c @@ -47,7 +47,7 @@ nk_draw_checkbox(struct nk_command_buffer *out, text.text = style->text_normal; } - text.text = nk_rgb_factor(text.text, style->color_factor); + text.text = nk_rgb_factor(text.text, style->color_factor); text.padding.x = 0; text.padding.y = 0; text.background = style->text_background; @@ -90,7 +90,7 @@ nk_draw_option(struct nk_command_buffer *out, text.text = style->text_normal; } - text.text = nk_rgb_factor(text.text, style->color_factor); + text.text = nk_rgb_factor(text.text, style->color_factor); text.padding.x = 0; text.padding.y = 0; text.background = style->text_background; From 319f79f177214e582a51871f4068e00108fca313 Mon Sep 17 00:00:00 2001 From: Jacob Ahnstedt Date: Tue, 12 Dec 2023 16:35:38 +0100 Subject: [PATCH 084/106] Built nuklear.h --- nuklear.h | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/nuklear.h b/nuklear.h index bf41ea6..4abcbc1 100644 --- a/nuklear.h +++ b/nuklear.h @@ -6180,14 +6180,14 @@ NK_LIB void nk_property(struct nk_context *ctx, const char *name, struct nk_prop #ifndef STBTT_malloc static void* nk_stbtt_malloc(nk_size size, void *user_data) { - struct nk_allocator *alloc = (struct nk_allocator *) user_data; - return alloc->alloc(alloc->userdata, 0, size); + struct nk_allocator *alloc = (struct nk_allocator *) user_data; + return alloc->alloc(alloc->userdata, 0, size); } static void nk_stbtt_free(void *ptr, void *user_data) { - struct nk_allocator *alloc = (struct nk_allocator *) user_data; - alloc->free(alloc->userdata, ptr); + struct nk_allocator *alloc = (struct nk_allocator *) user_data; + alloc->free(alloc->userdata, ptr); } #define STBTT_malloc(x,u) nk_stbtt_malloc(x,u) @@ -24750,7 +24750,7 @@ nk_draw_checkbox(struct nk_command_buffer *out, text.text = style->text_normal; } - text.text = nk_rgb_factor(text.text, style->color_factor); + text.text = nk_rgb_factor(text.text, style->color_factor); text.padding.x = 0; text.padding.y = 0; text.background = style->text_background; @@ -24793,7 +24793,7 @@ nk_draw_option(struct nk_command_buffer *out, text.text = style->text_normal; } - text.text = nk_rgb_factor(text.text, style->color_factor); + text.text = nk_rgb_factor(text.text, style->color_factor); text.padding.x = 0; text.padding.y = 0; text.background = style->text_background; From 029b558f571e035f9c22dc01214d6e3b9b76ecc4 Mon Sep 17 00:00:00 2001 From: Bruce Mitchener Date: Tue, 19 Dec 2023 20:18:36 -0500 Subject: [PATCH 085/106] ci: Update to `actions/checkout@v4`. This brings changes to keep up with the GitHub Actions internals (among other changes). This will remove some of the deprecation warnings in the GitHub Actions UI. --- .github/workflows/ccpp.yml | 2 +- .github/workflows/create-tag.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ccpp.yml b/.github/workflows/ccpp.yml index d935f11..d75a40b 100644 --- a/.github/workflows/ccpp.yml +++ b/.github/workflows/ccpp.yml @@ -8,7 +8,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v4 - name: apt-update run: sudo apt-get update -qq - name: apt get glfw diff --git a/.github/workflows/create-tag.yml b/.github/workflows/create-tag.yml index f5f30b0..bb5e0dd 100644 --- a/.github/workflows/create-tag.yml +++ b/.github/workflows/create-tag.yml @@ -9,7 +9,7 @@ jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - uses: butlerlogic/action-autotag@stable with: GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" From 16336450bbaaf7c5f0bfcea1d6a4406ace5afdb6 Mon Sep 17 00:00:00 2001 From: Bruce Mitchener Date: Wed, 20 Dec 2023 00:41:52 -0500 Subject: [PATCH 086/106] Fix typos. --- demo/sfml_opengl2/Readme.md | 2 +- demo/sfml_opengl3/Readme.md | 2 +- doc/index.html | 10 +++++----- nuklear.h | 16 ++++++++-------- src/CHANGELOG | 4 ++-- src/nuklear.h | 8 ++++---- src/stb_rect_pack.h | 4 ++-- 7 files changed, 23 insertions(+), 23 deletions(-) diff --git a/demo/sfml_opengl2/Readme.md b/demo/sfml_opengl2/Readme.md index e3879c0..ac055d6 100644 --- a/demo/sfml_opengl2/Readme.md +++ b/demo/sfml_opengl2/Readme.md @@ -6,4 +6,4 @@ This backend provides support for [SFML 2.4](http://www.sfml-dev.org). It will w You have to edit the Makefile provided so that you can build the demo. Edit the SFML_DIR variable to point to your SFML root folder. This will be the folder to which SFML was installed and contains the lib and include folders. -On Linux there is an extra step. You need to install the the udev development files. +On Linux there is an extra step. You need to install the udev development files. diff --git a/demo/sfml_opengl3/Readme.md b/demo/sfml_opengl3/Readme.md index ac03e75..4336fce 100644 --- a/demo/sfml_opengl3/Readme.md +++ b/demo/sfml_opengl3/Readme.md @@ -8,4 +8,4 @@ This backend uses Glad to handle OpenGL extensions. You can download the Glad fi Once SFML and Glad have been installed on your system you have to edit the Makefile provided so that you can build the demo. There are two variables that need to be edited: SFML_DIR and GLAD_DIR. Make these point to your SFML root folder and Glad root folder respectively. -On Linux there is an extra step. You need to install the the udev development files. +On Linux there is an extra step. You need to install the udev development files. diff --git a/doc/index.html b/doc/index.html index 919cd95..aa18a37 100644 --- a/doc/index.html +++ b/doc/index.html @@ -886,7 +886,7 @@ NK_WINDOW_NO_INPUT | Prevents window of scaling, moving or getting focu #### nk_collapse_states State | Description ----------------|----------------------------------------------------------- -__NK_MINIMIZED__| UI section is collased and not visible until maximized +__NK_MINIMIZED__| UI section is collapsed and not visible until maximized __NK_MAXIMIZED__| UI section is extended and visible until minimized

#### nk_begin @@ -1267,7 +1267,7 @@ Parameter | Description __ctx__ | Must point to an previously initialized `nk_context` struct __name__ | Identifier of the window to either hide or show __state__ | state with either visible or hidden to modify the window with -__cond__ | condition that has to be met to actually commit the visbility state change +__cond__ | condition that has to be met to actually commit the visibility state change ### Layouting Layouting in general describes placing widget inside a window with position and size. While in this particular implementation there are five different APIs for layouting @@ -1306,7 +1306,7 @@ functions should be fine. if the owning window grows in width. So the number of columns dictates the size of each widget dynamically by formula: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c - widget_width = (window_width - padding - spacing) * (1/colum_count) + widget_width = (window_width - padding - spacing) * (1/column_count) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Just like all other layouting APIs if you define more widget than columns this library will allocate a new row and keep all layouting parameters previously @@ -2760,7 +2760,7 @@ X...XXXXXXXXXXXXX...X - " dynamic and static widgets. - 2016/12/31 (1.30.0) - Extended scrollbar offset from 16-bit to 32-bit. - 2016/12/31 (1.29.2) - Fixed closing window bug of minimized windows. -- 2016/12/03 (1.29.1) - Fixed wrapped text with no seperator and C89 error. +- 2016/12/03 (1.29.1) - Fixed wrapped text with no separator and C89 error. - 2016/12/03 (1.29.0) - Changed text wrapping to process words not characters. - 2016/11/22 (1.28.6) - Fixed window minimized closing bug. - 2016/11/19 (1.28.5) - Fixed abstract combo box closing behavior. @@ -2898,7 +2898,7 @@ X...XXXXXXXXXXXXX...X - " precision. - 2016/08/08 (1.07.2) - Fixed compiling error without define `NK_INCLUDE_FIXED_TYPE`. - 2016/08/08 (1.07.1) - Fixed possible floating point error inside `nk_widget` leading - to wrong wiget width calculation which results in widgets falsely + to wrong widget width calculation which results in widgets falsely becoming tagged as not inside window and cannot be accessed. - 2016/08/08 (1.07.0) - Nuklear now differentiates between hiding a window (NK_WINDOW_HIDDEN) and closing a window (NK_WINDOW_CLOSED). A window can be hidden/shown diff --git a/nuklear.h b/nuklear.h index 583dc03..2b207b1 100644 --- a/nuklear.h +++ b/nuklear.h @@ -1463,7 +1463,7 @@ NK_API const struct nk_draw_command* nk__draw_next(const struct nk_draw_command* /// #### nk_collapse_states /// State | Description /// ----------------|----------------------------------------------------------- -/// __NK_MINIMIZED__| UI section is collased and not visible until maximized +/// __NK_MINIMIZED__| UI section is collapsed and not visible until maximized /// __NK_MAXIMIZED__| UI section is extended and visible until minimized ///

*/ @@ -2001,11 +2001,11 @@ NK_API void nk_window_show(struct nk_context*, const char *name, enum nk_show_st /// __ctx__ | Must point to an previously initialized `nk_context` struct /// __name__ | Identifier of the window to either hide or show /// __state__ | state with either visible or hidden to modify the window with -/// __cond__ | condition that has to be met to actually commit the visbility state change +/// __cond__ | condition that has to be met to actually commit the visibility state change */ NK_API void nk_window_show_if(struct nk_context*, const char *name, enum nk_show_states, int cond); /*/// #### nk_window_show_if -/// Line for visual seperation. Draws a line with thickness determined by the current row height. +/// Line for visual separation. Draws a line with thickness determined by the current row height. /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c /// void nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, NK_BOOL rounding) /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -2069,7 +2069,7 @@ NK_API void nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, nk /// the size of each widget dynamically by formula: /// /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// widget_width = (window_width - padding - spacing) * (1/colum_count) +/// widget_width = (window_width - padding - spacing) * (1/column_count) /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// /// Just like all other layouting APIs if you define more widget than columns this @@ -11120,7 +11120,7 @@ static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0 if (node->y > min_y) { /* raise min_y higher. */ /* we've accounted for all waste up to min_y, */ - /* but we'll now add more waste for everything we've visted */ + /* but we'll now add more waste for everything we've visited */ waste_area += visited_width * (node->y - min_y); min_y = node->y; /* the first time through, visited_width might be reduced */ @@ -11275,7 +11275,7 @@ static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, i /* insert the new node into the right starting point, and */ /* let 'cur' point to the remaining nodes needing to be */ - /* stiched back in */ + /* stitched back in */ cur = *res.prev_link; if (cur->x < res.x) { @@ -30131,7 +30131,7 @@ nk_tooltipfv(struct nk_context *ctx, const char *fmt, va_list args) /// dynamic and static widgets. /// - 2016/12/31 (1.30.0) - Extended scrollbar offset from 16-bit to 32-bit. /// - 2016/12/31 (1.29.2) - Fixed closing window bug of minimized windows. -/// - 2016/12/03 (1.29.1) - Fixed wrapped text with no seperator and C89 error. +/// - 2016/12/03 (1.29.1) - Fixed wrapped text with no separator and C89 error. /// - 2016/12/03 (1.29.0) - Changed text wrapping to process words not characters. /// - 2016/11/22 (1.28.6) - Fixed window minimized closing bug. /// - 2016/11/19 (1.28.5) - Fixed abstract combo box closing behavior. @@ -30269,7 +30269,7 @@ nk_tooltipfv(struct nk_context *ctx, const char *fmt, va_list args) /// precision. /// - 2016/08/08 (1.07.2) - Fixed compiling error without define `NK_INCLUDE_FIXED_TYPE`. /// - 2016/08/08 (1.07.1) - Fixed possible floating point error inside `nk_widget` leading -/// to wrong wiget width calculation which results in widgets falsely +/// to wrong widget width calculation which results in widgets falsely /// becoming tagged as not inside window and cannot be accessed. /// - 2016/08/08 (1.07.0) - Nuklear now differentiates between hiding a window (NK_WINDOW_HIDDEN) and /// closing a window (NK_WINDOW_CLOSED). A window can be hidden/shown diff --git a/src/CHANGELOG b/src/CHANGELOG index a4a0ad9..01442c4 100644 --- a/src/CHANGELOG +++ b/src/CHANGELOG @@ -152,7 +152,7 @@ /// dynamic and static widgets. /// - 2016/12/31 (1.30.0) - Extended scrollbar offset from 16-bit to 32-bit. /// - 2016/12/31 (1.29.2) - Fixed closing window bug of minimized windows. -/// - 2016/12/03 (1.29.1) - Fixed wrapped text with no seperator and C89 error. +/// - 2016/12/03 (1.29.1) - Fixed wrapped text with no separator and C89 error. /// - 2016/12/03 (1.29.0) - Changed text wrapping to process words not characters. /// - 2016/11/22 (1.28.6) - Fixed window minimized closing bug. /// - 2016/11/19 (1.28.5) - Fixed abstract combo box closing behavior. @@ -290,7 +290,7 @@ /// precision. /// - 2016/08/08 (1.07.2) - Fixed compiling error without define `NK_INCLUDE_FIXED_TYPE`. /// - 2016/08/08 (1.07.1) - Fixed possible floating point error inside `nk_widget` leading -/// to wrong wiget width calculation which results in widgets falsely +/// to wrong widget width calculation which results in widgets falsely /// becoming tagged as not inside window and cannot be accessed. /// - 2016/08/08 (1.07.0) - Nuklear now differentiates between hiding a window (NK_WINDOW_HIDDEN) and /// closing a window (NK_WINDOW_CLOSED). A window can be hidden/shown diff --git a/src/nuklear.h b/src/nuklear.h index a7a0243..66e26da 100644 --- a/src/nuklear.h +++ b/src/nuklear.h @@ -1241,7 +1241,7 @@ NK_API const struct nk_draw_command* nk__draw_next(const struct nk_draw_command* /// #### nk_collapse_states /// State | Description /// ----------------|----------------------------------------------------------- -/// __NK_MINIMIZED__| UI section is collased and not visible until maximized +/// __NK_MINIMIZED__| UI section is collapsed and not visible until maximized /// __NK_MAXIMIZED__| UI section is extended and visible until minimized ///

*/ @@ -1779,11 +1779,11 @@ NK_API void nk_window_show(struct nk_context*, const char *name, enum nk_show_st /// __ctx__ | Must point to an previously initialized `nk_context` struct /// __name__ | Identifier of the window to either hide or show /// __state__ | state with either visible or hidden to modify the window with -/// __cond__ | condition that has to be met to actually commit the visbility state change +/// __cond__ | condition that has to be met to actually commit the visibility state change */ NK_API void nk_window_show_if(struct nk_context*, const char *name, enum nk_show_states, int cond); /*/// #### nk_window_show_if -/// Line for visual seperation. Draws a line with thickness determined by the current row height. +/// Line for visual separation. Draws a line with thickness determined by the current row height. /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c /// void nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, NK_BOOL rounding) /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -1847,7 +1847,7 @@ NK_API void nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, nk /// the size of each widget dynamically by formula: /// /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// widget_width = (window_width - padding - spacing) * (1/colum_count) +/// widget_width = (window_width - padding - spacing) * (1/column_count) /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// /// Just like all other layouting APIs if you define more widget than columns this diff --git a/src/stb_rect_pack.h b/src/stb_rect_pack.h index 6a633ce..1417197 100644 --- a/src/stb_rect_pack.h +++ b/src/stb_rect_pack.h @@ -311,7 +311,7 @@ static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0 if (node->y > min_y) { // raise min_y higher. // we've accounted for all waste up to min_y, - // but we'll now add more waste for everything we've visted + // but we'll now add more waste for everything we've visited waste_area += visited_width * (node->y - min_y); min_y = node->y; // the first time through, visited_width might be reduced @@ -466,7 +466,7 @@ static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, i // insert the new node into the right starting point, and // let 'cur' point to the remaining nodes needing to be - // stiched back in + // stitched back in cur = *res.prev_link; if (cur->x < res.x) { From f31cb7f7e5c1c7ef25e922b9114055163d5b8e68 Mon Sep 17 00:00:00 2001 From: Brian Watling Date: Thu, 4 Jan 2024 21:24:02 -0500 Subject: [PATCH 087/106] Add a style option to disable point markers on charts Fixes #594 --- demo/common/overview.c | 4 ++++ nuklear.h | 17 +++++++++++++---- src/nuklear.h | 2 ++ src/nuklear_chart.c | 14 ++++++++++---- src/nuklear_style.c | 1 + 5 files changed, 30 insertions(+), 8 deletions(-) diff --git a/demo/common/overview.c b/demo/common/overview.c index 02b69bd..a006e2e 100644 --- a/demo/common/overview.c +++ b/demo/common/overview.c @@ -621,6 +621,7 @@ overview(struct nk_context *ctx) float id = 0; static int col_index = -1; static int line_index = -1; + static int hide_markers = nk_false; float step = (2*3.141592654f) / 32; int i; @@ -629,7 +630,10 @@ overview(struct nk_context *ctx) /* line chart */ id = 0; index = -1; + nk_layout_row_dynamic(ctx, 15, 1); + nk_checkbox_label(ctx, "Hide markers", &hide_markers); nk_layout_row_dynamic(ctx, 100, 1); + ctx->style.chart.hide_markers = hide_markers; if (nk_chart_begin(ctx, NK_CHART_LINES, 32, -1.0f, 1.0f)) { for (i = 0; i < 32; ++i) { nk_flags res = nk_chart_push(ctx, (float)cos(id)); diff --git a/nuklear.h b/nuklear.h index 583dc03..8cf381e 100644 --- a/nuklear.h +++ b/nuklear.h @@ -5198,6 +5198,7 @@ struct nk_style_chart { struct nk_vec2 padding; float color_factor; float disabled_factor; + nk_bool hide_markers; }; struct nk_style_combo { @@ -5388,6 +5389,7 @@ struct nk_chart_slot { int count; struct nk_vec2 last; int index; + nk_bool hide_markers; }; struct nk_chart { @@ -18656,6 +18658,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) chart->rounding = 0; chart->color_factor = 1.0f; chart->disabled_factor = NK_WIDGET_DISABLED_FACTOR; + chart->hide_markers = nk_false; /* combo */ combo = &style->combo; @@ -28492,7 +28495,8 @@ nk_chart_begin_colored(struct nk_context *ctx, enum nk_chart_type type, slot->highlight = highlight; slot->min = NK_MIN(min_value, max_value); slot->max = NK_MAX(min_value, max_value); - slot->range = slot->max - slot->min;} + slot->range = slot->max - slot->min; + slot->hide_markers = style->hide_markers;} /* draw chart background */ background = &style->background; @@ -28544,7 +28548,8 @@ nk_chart_add_slot_colored(struct nk_context *ctx, const enum nk_chart_type type, slot->highlight = highlight; slot->min = NK_MIN(min_value, max_value); slot->max = NK_MAX(min_value, max_value); - slot->range = slot->max - slot->min;} + slot->range = slot->max - slot->min; + slot->hide_markers = style->hide_markers;} } NK_API void nk_chart_add_slot(struct nk_context *ctx, const enum nk_chart_type type, @@ -28591,7 +28596,9 @@ nk_chart_push_line(struct nk_context *ctx, struct nk_window *win, i->mouse.buttons[NK_BUTTON_LEFT].clicked) ? NK_CHART_CLICKED: 0; color = g->slots[slot].highlight; } - nk_fill_rect(out, bounds, 0, color); + if (!g->slots[slot].hide_markers) { + nk_fill_rect(out, bounds, 0, color); + } g->slots[slot].index += 1; return ret; } @@ -28615,7 +28622,9 @@ nk_chart_push_line(struct nk_context *ctx, struct nk_window *win, color = g->slots[slot].highlight; } } - nk_fill_rect(out, nk_rect(cur.x - 2, cur.y - 2, 4, 4), 0, color); + if (!g->slots[slot].hide_markers) { + nk_fill_rect(out, nk_rect(cur.x - 2, cur.y - 2, 4, 4), 0, color); + } /* save current data point position */ g->slots[slot].last.x = cur.x; diff --git a/src/nuklear.h b/src/nuklear.h index a7a0243..18f263e 100644 --- a/src/nuklear.h +++ b/src/nuklear.h @@ -4976,6 +4976,7 @@ struct nk_style_chart { struct nk_vec2 padding; float color_factor; float disabled_factor; + nk_bool hide_markers; }; struct nk_style_combo { @@ -5166,6 +5167,7 @@ struct nk_chart_slot { int count; struct nk_vec2 last; int index; + nk_bool hide_markers; }; struct nk_chart { diff --git a/src/nuklear_chart.c b/src/nuklear_chart.c index b71caf2..d177a83 100644 --- a/src/nuklear_chart.c +++ b/src/nuklear_chart.c @@ -52,7 +52,8 @@ nk_chart_begin_colored(struct nk_context *ctx, enum nk_chart_type type, slot->highlight = highlight; slot->min = NK_MIN(min_value, max_value); slot->max = NK_MAX(min_value, max_value); - slot->range = slot->max - slot->min;} + slot->range = slot->max - slot->min; + slot->hide_markers = style->hide_markers;} /* draw chart background */ background = &style->background; @@ -104,7 +105,8 @@ nk_chart_add_slot_colored(struct nk_context *ctx, const enum nk_chart_type type, slot->highlight = highlight; slot->min = NK_MIN(min_value, max_value); slot->max = NK_MAX(min_value, max_value); - slot->range = slot->max - slot->min;} + slot->range = slot->max - slot->min; + slot->hide_markers = style->hide_markers;} } NK_API void nk_chart_add_slot(struct nk_context *ctx, const enum nk_chart_type type, @@ -151,7 +153,9 @@ nk_chart_push_line(struct nk_context *ctx, struct nk_window *win, i->mouse.buttons[NK_BUTTON_LEFT].clicked) ? NK_CHART_CLICKED: 0; color = g->slots[slot].highlight; } - nk_fill_rect(out, bounds, 0, color); + if (!g->slots[slot].hide_markers) { + nk_fill_rect(out, bounds, 0, color); + } g->slots[slot].index += 1; return ret; } @@ -175,7 +179,9 @@ nk_chart_push_line(struct nk_context *ctx, struct nk_window *win, color = g->slots[slot].highlight; } } - nk_fill_rect(out, nk_rect(cur.x - 2, cur.y - 2, 4, 4), 0, color); + if (!g->slots[slot].hide_markers) { + nk_fill_rect(out, nk_rect(cur.x - 2, cur.y - 2, 4, 4), 0, color); + } /* save current data point position */ g->slots[slot].last.x = cur.x; diff --git a/src/nuklear_style.c b/src/nuklear_style.c index 6cf4514..0ddc89b 100644 --- a/src/nuklear_style.c +++ b/src/nuklear_style.c @@ -486,6 +486,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) chart->rounding = 0; chart->color_factor = 1.0f; chart->disabled_factor = NK_WIDGET_DISABLED_FACTOR; + chart->hide_markers = nk_false; /* combo */ combo = &style->combo; From 0f4c3683511f95d8723684d0eb134507214f6eb2 Mon Sep 17 00:00:00 2001 From: Rob Loach Date: Sat, 13 Jan 2024 19:59:24 -0500 Subject: [PATCH 088/106] ci: Fix create-tag --- .github/workflows/create-tag.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/create-tag.yml b/.github/workflows/create-tag.yml index bb5e0dd..1c072dd 100644 --- a/.github/workflows/create-tag.yml +++ b/.github/workflows/create-tag.yml @@ -11,6 +11,7 @@ jobs: steps: - uses: actions/checkout@v4 - uses: butlerlogic/action-autotag@stable - with: + env: GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" + with: root: clib.json From f7fedf091f50d157f6297981c1d2fe5ff16ef56c Mon Sep 17 00:00:00 2001 From: Rob Loach Date: Sat, 13 Jan 2024 20:16:08 -0500 Subject: [PATCH 089/106] ci: Target version 1.1.2 of create-tag --- .github/workflows/create-tag.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/create-tag.yml b/.github/workflows/create-tag.yml index 1c072dd..b1b92e1 100644 --- a/.github/workflows/create-tag.yml +++ b/.github/workflows/create-tag.yml @@ -10,7 +10,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: butlerlogic/action-autotag@stable + - uses: butlerlogic/action-autotag@1.1.2 env: GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" with: From fb474874db084d6ba7009c148fe8a9fcfdd3034e Mon Sep 17 00:00:00 2001 From: b-aaz <85005689+b-aaz@users.noreply.github.com> Date: Sat, 20 Jan 2024 16:16:45 +0330 Subject: [PATCH 090/106] Added required includes to the platform headers . Added missing include decelerations and in one case removed an unnecessary one form the platform headers in the demo/ directory . --- demo/allegro5/nuklear_allegro5.h | 1 + demo/d3d11/nuklear_d3d11.h | 1 + demo/d3d12/nuklear_d3d12.h | 1 + demo/d3d9/nuklear_d3d9.h | 1 + demo/gdi/nuklear_gdi.h | 2 +- demo/gdi_native_nuklear/nuklear_gdi.h | 2 +- demo/glfw_opengl2/nuklear_glfw_gl2.h | 2 ++ demo/glfw_opengl3/nuklear_glfw_gl3.h | 3 +++ demo/glfw_opengl4/nuklear_glfw_gl4.h | 3 +++ demo/glfw_vulkan/nuklear_glfw_vulkan.h | 2 ++ demo/glfw_vulkan/src/nuklear_glfw_vulkan.in.h | 2 ++ demo/sdl2surface_rawfb/sdl2surface_rawfb.h | 4 ++++ demo/sdl_opengl2/nuklear_sdl_gl2.h | 2 ++ demo/sdl_opengl3/nuklear_sdl_gl3.h | 2 ++ demo/sdl_opengles2/nuklear_sdl_gles2.h | 3 ++- demo/sdl_renderer/nuklear_sdl_renderer.h | 4 ++-- demo/sfml_opengl2/nuklear_sfml_gl2.h | 2 ++ demo/sfml_opengl3/nuklear_sfml_gl3.h | 3 ++- demo/wayland_rawfb/nuklear_raw_wayland.h | 4 ++++ demo/x11/nuklear_xlib.h | 3 +++ demo/x11_opengl3/nuklear_xlib_gl3.h | 1 + demo/x11_rawfb/nuklear_rawfb.h | 4 ++++ demo/x11_rawfb/nuklear_xlib.h | 3 +++ demo/x11_xft/nuklear_xlib.h | 3 +++ 24 files changed, 52 insertions(+), 6 deletions(-) diff --git a/demo/allegro5/nuklear_allegro5.h b/demo/allegro5/nuklear_allegro5.h index 0e980c7..0e72f16 100644 --- a/demo/allegro5/nuklear_allegro5.h +++ b/demo/allegro5/nuklear_allegro5.h @@ -46,6 +46,7 @@ NK_API void nk_allegro5_font_set_font(NkAllegro5Font *font); * =============================================================== */ #ifdef NK_ALLEGRO5_IMPLEMENTATION +#include #ifndef NK_ALLEGRO5_TEXT_MAX #define NK_ALLEGRO5_TEXT_MAX 256 diff --git a/demo/d3d11/nuklear_d3d11.h b/demo/d3d11/nuklear_d3d11.h index 27fa2c1..c62be56 100644 --- a/demo/d3d11/nuklear_d3d11.h +++ b/demo/d3d11/nuklear_d3d11.h @@ -41,6 +41,7 @@ NK_API void nk_d3d11_shutdown(void); #define COBJMACROS #include +#include #include #include #include diff --git a/demo/d3d12/nuklear_d3d12.h b/demo/d3d12/nuklear_d3d12.h index 5b86ea1..03560a2 100644 --- a/demo/d3d12/nuklear_d3d12.h +++ b/demo/d3d12/nuklear_d3d12.h @@ -88,6 +88,7 @@ NK_API void nk_d3d12_shutdown(void); #define COBJMACROS #include +#include #include #include #include diff --git a/demo/d3d9/nuklear_d3d9.h b/demo/d3d9/nuklear_d3d9.h index f967678..8af027f 100644 --- a/demo/d3d9/nuklear_d3d9.h +++ b/demo/d3d9/nuklear_d3d9.h @@ -41,6 +41,7 @@ NK_API void nk_d3d9_shutdown(void); #define COBJMACROS #include +#include #include #include diff --git a/demo/gdi/nuklear_gdi.h b/demo/gdi/nuklear_gdi.h index 6bbedb6..ff2ff19 100644 --- a/demo/gdi/nuklear_gdi.h +++ b/demo/gdi/nuklear_gdi.h @@ -38,7 +38,7 @@ NK_API void nk_gdi_set_font(GdiFont *font); * =============================================================== */ #ifdef NK_GDI_IMPLEMENTATION - +#include #include #include diff --git a/demo/gdi_native_nuklear/nuklear_gdi.h b/demo/gdi_native_nuklear/nuklear_gdi.h index 5c2f1f8..aa91740 100644 --- a/demo/gdi_native_nuklear/nuklear_gdi.h +++ b/demo/gdi_native_nuklear/nuklear_gdi.h @@ -50,7 +50,7 @@ NK_API void nk_gdi_set_font(nk_gdi_ctx gdi, GdiFont* font); * =============================================================== */ #ifdef NK_GDI_IMPLEMENTATION - +#include #include #include diff --git a/demo/glfw_opengl2/nuklear_glfw_gl2.h b/demo/glfw_opengl2/nuklear_glfw_gl2.h index fb8b31e..d74b4f2 100644 --- a/demo/glfw_opengl2/nuklear_glfw_gl2.h +++ b/demo/glfw_opengl2/nuklear_glfw_gl2.h @@ -40,6 +40,8 @@ NK_API void nk_gflw3_scroll_callback(GLFWwindow *win, double xof * =============================================================== */ #ifdef NK_GLFW_GL2_IMPLEMENTATION +#include +#include #ifndef NK_GLFW_TEXT_MAX #define NK_GLFW_TEXT_MAX 256 diff --git a/demo/glfw_opengl3/nuklear_glfw_gl3.h b/demo/glfw_opengl3/nuklear_glfw_gl3.h index cef59e5..8ba361c 100644 --- a/demo/glfw_opengl3/nuklear_glfw_gl3.h +++ b/demo/glfw_opengl3/nuklear_glfw_gl3.h @@ -78,6 +78,9 @@ NK_API void nk_glfw3_mouse_button_callback(GLFWwindow *win, int * =============================================================== */ #ifdef NK_GLFW_GL3_IMPLEMENTATION +#include +#include +#include #ifndef NK_GLFW_DOUBLE_CLICK_LO #define NK_GLFW_DOUBLE_CLICK_LO 0.02 diff --git a/demo/glfw_opengl4/nuklear_glfw_gl4.h b/demo/glfw_opengl4/nuklear_glfw_gl4.h index 781bfc3..b4df990 100644 --- a/demo/glfw_opengl4/nuklear_glfw_gl4.h +++ b/demo/glfw_opengl4/nuklear_glfw_gl4.h @@ -50,6 +50,9 @@ NK_API void nk_glfw3_destroy_texture(int tex_index); */ #ifdef NK_GLFW_GL4_IMPLEMENTATION #undef NK_GLFW_GL4_IMPLEMENTATION +#include +#include +#include #ifndef NK_GLFW_TEXT_MAX #define NK_GLFW_TEXT_MAX 256 diff --git a/demo/glfw_vulkan/nuklear_glfw_vulkan.h b/demo/glfw_vulkan/nuklear_glfw_vulkan.h index f411872..3c1e358 100644 --- a/demo/glfw_vulkan/nuklear_glfw_vulkan.h +++ b/demo/glfw_vulkan/nuklear_glfw_vulkan.h @@ -247,6 +247,7 @@ unsigned char nuklearshaders_nuklear_frag_spv[] = { }; unsigned int nuklearshaders_nuklear_frag_spv_len = 860; +#include #include #include #define GLFW_INCLUDE_VULKAN @@ -294,6 +295,7 @@ NK_API void nk_glfw3_mouse_button_callback(GLFWwindow *win, int button, */ #ifdef NK_GLFW_VULKAN_IMPLEMENTATION #undef NK_GLFW_VULKAN_IMPLEMENTATION +#include #ifndef NK_GLFW_TEXT_MAX #define NK_GLFW_TEXT_MAX 256 diff --git a/demo/glfw_vulkan/src/nuklear_glfw_vulkan.in.h b/demo/glfw_vulkan/src/nuklear_glfw_vulkan.in.h index 78a1f6c..ea86e5b 100644 --- a/demo/glfw_vulkan/src/nuklear_glfw_vulkan.in.h +++ b/demo/glfw_vulkan/src/nuklear_glfw_vulkan.in.h @@ -71,6 +71,8 @@ NK_API void nk_glfw3_mouse_button_callback(GLFWwindow *win, int button, */ #ifdef NK_GLFW_VULKAN_IMPLEMENTATION #undef NK_GLFW_VULKAN_IMPLEMENTATION +#include +#include #ifndef NK_GLFW_TEXT_MAX #define NK_GLFW_TEXT_MAX 256 diff --git a/demo/sdl2surface_rawfb/sdl2surface_rawfb.h b/demo/sdl2surface_rawfb/sdl2surface_rawfb.h index 6e2eb59..7b4b1cf 100644 --- a/demo/sdl2surface_rawfb/sdl2surface_rawfb.h +++ b/demo/sdl2surface_rawfb/sdl2surface_rawfb.h @@ -49,6 +49,10 @@ void nk_sdlsurface_shutdown(struct sdlsurface_context *sdlsurfa * =============================================================== */ #ifdef NK_SDLSURFACE_IMPLEMENTATION +#include +#include +#include + struct sdlsurface_context { struct nk_context ctx; struct nk_rect scissors; diff --git a/demo/sdl_opengl2/nuklear_sdl_gl2.h b/demo/sdl_opengl2/nuklear_sdl_gl2.h index 0c6a2fb..819723c 100644 --- a/demo/sdl_opengl2/nuklear_sdl_gl2.h +++ b/demo/sdl_opengl2/nuklear_sdl_gl2.h @@ -30,6 +30,8 @@ NK_API void nk_sdl_shutdown(void); * =============================================================== */ #ifdef NK_SDL_GL2_IMPLEMENTATION +#include +#include struct nk_sdl_device { struct nk_buffer cmds; diff --git a/demo/sdl_opengl3/nuklear_sdl_gl3.h b/demo/sdl_opengl3/nuklear_sdl_gl3.h index cac8629..4e7df6b 100644 --- a/demo/sdl_opengl3/nuklear_sdl_gl3.h +++ b/demo/sdl_opengl3/nuklear_sdl_gl3.h @@ -36,6 +36,8 @@ NK_API void nk_sdl_device_create(void); */ #ifdef NK_SDL_GL3_IMPLEMENTATION +#include +#include #include struct nk_sdl_device { diff --git a/demo/sdl_opengles2/nuklear_sdl_gles2.h b/demo/sdl_opengles2/nuklear_sdl_gles2.h index 595d7a7..39a444d 100644 --- a/demo/sdl_opengles2/nuklear_sdl_gles2.h +++ b/demo/sdl_opengles2/nuklear_sdl_gles2.h @@ -38,7 +38,8 @@ NK_API void nk_sdl_device_create(void); * =============================================================== */ #ifdef NK_SDL_GLES2_IMPLEMENTATION - +#include +#include #include struct nk_sdl_device { diff --git a/demo/sdl_renderer/nuklear_sdl_renderer.h b/demo/sdl_renderer/nuklear_sdl_renderer.h index 672b81b..fbea3cf 100644 --- a/demo/sdl_renderer/nuklear_sdl_renderer.h +++ b/demo/sdl_renderer/nuklear_sdl_renderer.h @@ -39,8 +39,8 @@ NK_API void nk_sdl_shutdown(void); * =============================================================== */ #ifdef NK_SDL_RENDERER_IMPLEMENTATION - -#include +#include +#include struct nk_sdl_device { struct nk_buffer cmds; diff --git a/demo/sfml_opengl2/nuklear_sfml_gl2.h b/demo/sfml_opengl2/nuklear_sfml_gl2.h index f168bab..5677405 100644 --- a/demo/sfml_opengl2/nuklear_sfml_gl2.h +++ b/demo/sfml_opengl2/nuklear_sfml_gl2.h @@ -31,6 +31,8 @@ NK_API void nk_sfml_shutdown(void); * =============================================================== */ #ifdef NK_SFML_GL2_IMPLEMENTATION +#include +#include struct nk_sfml_device { struct nk_buffer cmds; diff --git a/demo/sfml_opengl3/nuklear_sfml_gl3.h b/demo/sfml_opengl3/nuklear_sfml_gl3.h index 286cfc1..c58bde7 100644 --- a/demo/sfml_opengl3/nuklear_sfml_gl3.h +++ b/demo/sfml_opengl3/nuklear_sfml_gl3.h @@ -38,7 +38,8 @@ NK_API void nk_sfml_device_destroy(void); * =============================================================== */ #ifdef NK_SFML_GL3_IMPLEMENTATION - +#include +#include #include struct nk_sfml_device { diff --git a/demo/wayland_rawfb/nuklear_raw_wayland.h b/demo/wayland_rawfb/nuklear_raw_wayland.h index 49082c5..1a465fc 100644 --- a/demo/wayland_rawfb/nuklear_raw_wayland.h +++ b/demo/wayland_rawfb/nuklear_raw_wayland.h @@ -1,6 +1,10 @@ #ifndef NK_RAW_WAYLAND_H_ #define NK_RAW_WAYLAND_H_ +#include +#include +#include + #define WIDTH 800 #define HEIGHT 600 diff --git a/demo/x11/nuklear_xlib.h b/demo/x11/nuklear_xlib.h index 9b3a861..28fb4cc 100644 --- a/demo/x11/nuklear_xlib.h +++ b/demo/x11/nuklear_xlib.h @@ -44,6 +44,9 @@ NK_API void nk_xfont_del(Display *dpy, XFont *font); * =============================================================== */ #ifdef NK_XLIB_IMPLEMENTATION +#include +#include +#include #include #include #include diff --git a/demo/x11_opengl3/nuklear_xlib_gl3.h b/demo/x11_opengl3/nuklear_xlib_gl3.h index 9dd0181..c343bb5 100644 --- a/demo/x11_opengl3/nuklear_xlib_gl3.h +++ b/demo/x11_opengl3/nuklear_xlib_gl3.h @@ -32,6 +32,7 @@ NK_API void nk_x11_device_destroy(void); * =============================================================== */ #ifdef NK_XLIB_GL3_IMPLEMENTATION +#include #include #include #include diff --git a/demo/x11_rawfb/nuklear_rawfb.h b/demo/x11_rawfb/nuklear_rawfb.h index ce84222..6aece67 100644 --- a/demo/x11_rawfb/nuklear_rawfb.h +++ b/demo/x11_rawfb/nuklear_rawfb.h @@ -55,6 +55,10 @@ NK_API void nk_rawfb_resize_fb(struct rawfb_context *rawfb, voi * =============================================================== */ #ifdef NK_RAWFB_IMPLEMENTATION +#include +#include +#include + struct rawfb_image { void *pixels; int w, h, pitch; diff --git a/demo/x11_rawfb/nuklear_xlib.h b/demo/x11_rawfb/nuklear_xlib.h index 0d23135..3174e24 100644 --- a/demo/x11_rawfb/nuklear_xlib.h +++ b/demo/x11_rawfb/nuklear_xlib.h @@ -49,6 +49,9 @@ NK_API void nk_xlib_shutdown(void); * =============================================================== */ #ifdef NK_XLIBSHM_IMPLEMENTATION +#include +#include +#include #include #include #include diff --git a/demo/x11_xft/nuklear_xlib.h b/demo/x11_xft/nuklear_xlib.h index 9526e3e..f0fb074 100644 --- a/demo/x11_xft/nuklear_xlib.h +++ b/demo/x11_xft/nuklear_xlib.h @@ -48,6 +48,9 @@ NK_API void nk_xfont_del(Display *dpy, XFont *font); * =============================================================== */ #ifdef NK_XLIB_IMPLEMENTATION +#include +#include +#include #include #include #include From 6c6260a7c267bcabf4ddf09d71adb492d16db6c7 Mon Sep 17 00:00:00 2001 From: Petr Abdulin Date: Mon, 22 Jan 2024 23:11:50 +0700 Subject: [PATCH 091/106] Suppress MSVC compiler `possible loss of data` warning with explicit cast --- nuklear.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nuklear.h b/nuklear.h index 4abcbc1..25a3e14 100644 --- a/nuklear.h +++ b/nuklear.h @@ -7662,9 +7662,9 @@ nk_rgb_factor(struct nk_color col, const float factor) { if (factor == 1.0f) return col; - col.r *= factor; - col.g *= factor; - col.b *= factor; + col.r = (nk_byte)(col.r * factor); + col.g = (nk_byte)(col.g * factor); + col.b = (nk_byte)(col.b * factor); return col; } NK_API struct nk_color From b3b04fca160765b11e1134a6b77c040c50e23060 Mon Sep 17 00:00:00 2001 From: Petr Abdulin Date: Tue, 23 Jan 2024 09:18:21 +0700 Subject: [PATCH 092/106] Suppress MSVC compiler `possible loss of data` warning with explicit cast --- src/nuklear_color.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/nuklear_color.c b/src/nuklear_color.c index 17969f3..d73da63 100644 --- a/src/nuklear_color.c +++ b/src/nuklear_color.c @@ -27,9 +27,9 @@ nk_rgb_factor(struct nk_color col, const float factor) { if (factor == 1.0f) return col; - col.r *= factor; - col.g *= factor; - col.b *= factor; + col.r = (nk_byte)(col.r * factor); + col.g = (nk_byte)(col.g * factor); + col.b = (nk_byte)(col.b * factor); return col; } NK_API struct nk_color From 8f1ce6f0c11e1486e7f2e119be1c5b5216721e21 Mon Sep 17 00:00:00 2001 From: Rob Loach Date: Fri, 26 Jan 2024 15:14:04 -0500 Subject: [PATCH 093/106] demo: Fix overview's nk_bool type usage The overview demo uses some `nk_bool`s that are typed as `int`s. While things still do function, if you're using `NK_INCLUDE_STANDARD_BOOL`, it breaks compilation. This change fixes the `nk_bool`s to be actual `nk_bool`s. --- demo/common/overview.c | 60 +++++++++++++++++++++--------------------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/demo/common/overview.c b/demo/common/overview.c index 261679c..780c073 100644 --- a/demo/common/overview.c +++ b/demo/common/overview.c @@ -2,13 +2,13 @@ static int overview(struct nk_context *ctx) { /* window flags */ - static int show_menu = nk_true; + static nk_bool show_menu = nk_true; static nk_flags window_flags = NK_WINDOW_TITLE|NK_WINDOW_BORDER|NK_WINDOW_SCALABLE|NK_WINDOW_MOVABLE|NK_WINDOW_MINIMIZABLE; nk_flags actual_window_flags; /* popups */ static enum nk_style_header_align header_align = NK_HEADER_RIGHT; - static int show_app_about = nk_false; + static nk_bool show_app_about = nk_false; ctx->style.window.header.align = header_align; @@ -25,7 +25,7 @@ overview(struct nk_context *ctx) enum menu_states {MENU_DEFAULT, MENU_WINDOWS}; static nk_size mprog = 60; static int mslider = 10; - static int mcheck = nk_true; + static nk_bool mcheck = nk_true; nk_menubar_begin(ctx); /* menu #1 */ @@ -35,7 +35,7 @@ overview(struct nk_context *ctx) { static size_t prog = 40; static int slider = 10; - static int check = nk_true; + static nk_bool check = nk_true; nk_layout_row_dynamic(ctx, 25, 1); if (nk_menu_item_label(ctx, "Hide", NK_TEXT_LEFT)) show_menu = nk_false; @@ -141,10 +141,10 @@ overview(struct nk_context *ctx) if (nk_tree_push(ctx, NK_TREE_TAB, "Widgets", NK_MINIMIZED)) { enum options {A,B,C}; - static int checkbox_left_text_left; - static int checkbox_centered_text_right; - static int checkbox_right_text_right; - static int checkbox_right_text_left; + static nk_bool checkbox_left_text_left; + static nk_bool checkbox_centered_text_right; + static nk_bool checkbox_right_text_right; + static nk_bool checkbox_right_text_left; static int option_left; static int option_right; if (nk_tree_push(ctx, NK_TREE_NODE, "Text", NK_MINIMIZED)) @@ -261,7 +261,7 @@ overview(struct nk_context *ctx) if (nk_tree_push(ctx, NK_TREE_NODE, "Inactive", NK_MINIMIZED)) { - static int inactive = 1; + static nk_bool inactive = 1; nk_layout_row_dynamic(ctx, 30, 1); nk_checkbox_label(ctx, "Inactive", &inactive); @@ -269,7 +269,7 @@ overview(struct nk_context *ctx) if (inactive) { nk_widget_disable_begin(ctx); } - + if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); @@ -282,7 +282,7 @@ overview(struct nk_context *ctx) { if (nk_tree_push(ctx, NK_TREE_NODE, "List", NK_MINIMIZED)) { - static int selected[4] = {nk_false, nk_false, nk_true, nk_false}; + static nk_bool selected[4] = {nk_false, nk_false, nk_true, nk_false}; nk_layout_row_static(ctx, 18, 100, 1); nk_selectable_label(ctx, "Selectable", NK_TEXT_LEFT, &selected[0]); nk_selectable_label(ctx, "Selectable", NK_TEXT_LEFT, &selected[1]); @@ -294,7 +294,7 @@ overview(struct nk_context *ctx) if (nk_tree_push(ctx, NK_TREE_NODE, "Grid", NK_MINIMIZED)) { int i; - static int selected[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1}; + static nk_bool selected[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1}; nk_layout_row_static(ctx, 50, 50, 4); for (i = 0; i < 16; ++i) { if (nk_selectable_label(ctx, "Z", NK_TEXT_CENTERED, &selected[i])) { @@ -341,7 +341,7 @@ overview(struct nk_context *ctx) */ static float chart_selection = 8.0f; static int current_weapon = 0; - static int check_values[5]; + static nk_bool check_values[5]; static float position[3]; static struct nk_color combo_color = {130, 50, 50, 255}; static struct nk_colorf combo_color2 = {0.509f, 0.705f, 0.2f, 1.0f}; @@ -602,7 +602,7 @@ overview(struct nk_context *ctx) } nk_tree_pop(ctx); } - + if (nk_tree_push(ctx, NK_TREE_NODE, "Horizontal Rule", NK_MINIMIZED)) { nk_layout_row_dynamic(ctx, 12, 1); @@ -713,8 +713,8 @@ overview(struct nk_context *ctx) if (nk_tree_push(ctx, NK_TREE_TAB, "Popup", NK_MINIMIZED)) { static struct nk_color color = {255,0,0, 255}; - static int select[4]; - static int popup_active; + static nk_bool select[4]; + static nk_bool popup_active; const struct nk_input *in = &ctx->input; struct nk_rect bounds; @@ -883,9 +883,9 @@ overview(struct nk_context *ctx) if (nk_tree_push(ctx, NK_TREE_NODE, "Group", NK_MINIMIZED)) { - static int group_titlebar = nk_false; - static int group_border = nk_true; - static int group_no_scrollbar = nk_false; + static nk_bool group_titlebar = nk_false; + static nk_bool group_border = nk_true; + static nk_bool group_no_scrollbar = nk_false; static int group_width = 320; static int group_height = 200; @@ -911,7 +911,7 @@ overview(struct nk_context *ctx) nk_layout_row_static(ctx, (float)group_height, group_width, 2); if (nk_group_begin(ctx, "Group", group_flags)) { int i = 0; - static int selected[16]; + static nk_bool selected[16]; nk_layout_row_static(ctx, 18, 100, 1); for (i = 0; i < 16; ++i) nk_selectable_label(ctx, (selected[i]) ? "Selected": "Unselected", NK_TEXT_CENTERED, &selected[i]); @@ -921,11 +921,12 @@ overview(struct nk_context *ctx) } if (nk_tree_push(ctx, NK_TREE_NODE, "Tree", NK_MINIMIZED)) { - static int root_selected = 0; - int sel = root_selected; + static nk_bool root_selected = 0; + nk_bool sel = root_selected; if (nk_tree_element_push(ctx, NK_TREE_NODE, "Root", NK_MINIMIZED, &sel)) { - static int selected[8]; - int i = 0, node_select = selected[0]; + static nk_bool selected[8]; + int i = 0; + nk_bool node_select = selected[0]; if (sel != root_selected) { root_selected = sel; for (i = 0; i < 8; ++i) @@ -933,7 +934,7 @@ overview(struct nk_context *ctx) } if (nk_tree_element_push(ctx, NK_TREE_NODE, "Node", NK_MINIMIZED, &node_select)) { int j = 0; - static int sel_nodes[4]; + static nk_bool sel_nodes[4]; if (node_select != selected[0]) { selected[0] = node_select; for (i = 0; i < 4; ++i) @@ -1061,7 +1062,7 @@ overview(struct nk_context *ctx) nk_layout_space_begin(ctx, NK_STATIC, 500, 64); nk_layout_space_push(ctx, nk_rect(0,0,150,500)); if (nk_group_begin(ctx, "Group_left", NK_WINDOW_BORDER)) { - static int selected[32]; + static nk_bool selected[32]; nk_layout_row_static(ctx, 18, 100, 1); for (i = 0; i < 32; ++i) nk_selectable_label(ctx, (selected[i]) ? "Selected": "Unselected", NK_TEXT_CENTERED, &selected[i]); @@ -1094,7 +1095,7 @@ overview(struct nk_context *ctx) nk_layout_space_push(ctx, nk_rect(320,0,150,150)); if (nk_group_begin(ctx, "Group_right_top", NK_WINDOW_BORDER)) { - static int selected[4]; + static nk_bool selected[4]; nk_layout_row_static(ctx, 18, 100, 1); for (i = 0; i < 4; ++i) nk_selectable_label(ctx, (selected[i]) ? "Selected": "Unselected", NK_TEXT_CENTERED, &selected[i]); @@ -1103,7 +1104,7 @@ overview(struct nk_context *ctx) nk_layout_space_push(ctx, nk_rect(320,160,150,150)); if (nk_group_begin(ctx, "Group_right_center", NK_WINDOW_BORDER)) { - static int selected[4]; + static nk_bool selected[4]; nk_layout_row_static(ctx, 18, 100, 1); for (i = 0; i < 4; ++i) nk_selectable_label(ctx, (selected[i]) ? "Selected": "Unselected", NK_TEXT_CENTERED, &selected[i]); @@ -1112,7 +1113,7 @@ overview(struct nk_context *ctx) nk_layout_space_push(ctx, nk_rect(320,320,150,150)); if (nk_group_begin(ctx, "Group_right_bottom", NK_WINDOW_BORDER)) { - static int selected[4]; + static nk_bool selected[4]; nk_layout_row_static(ctx, 18, 100, 1); for (i = 0; i < 4; ++i) nk_selectable_label(ctx, (selected[i]) ? "Selected": "Unselected", NK_TEXT_CENTERED, &selected[i]); @@ -1307,4 +1308,3 @@ overview(struct nk_context *ctx) nk_end(ctx); return !nk_window_is_closed(ctx, "Overview"); } - From e3b0f24626b4438445560c76e5ec6607c3cc2264 Mon Sep 17 00:00:00 2001 From: paccer Date: Sat, 10 Feb 2024 03:03:16 +0100 Subject: [PATCH 094/106] Fix missed grab state changes in SDL demos Move grab handling out of `nk_sdl_handle_event` to `nk_sdl_handle_grab`, which is now called outside of the event loop. This change makes the logic similar to the GLFW demos and fixes issues with missed grab state changes and mouse cursor disappearing. --- demo/sdl_opengl2/main.c | 1 + demo/sdl_opengl2/nuklear_sdl_gl2.h | 26 ++++++++++++++---------- demo/sdl_opengl3/main.c | 4 +++- demo/sdl_opengl3/nuklear_sdl_gl3.h | 26 ++++++++++++++---------- demo/sdl_opengles2/main.c | 1 + demo/sdl_opengles2/nuklear_sdl_gles2.h | 26 ++++++++++++++---------- demo/sdl_renderer/main.c | 1 + demo/sdl_renderer/nuklear_sdl_renderer.h | 26 ++++++++++++++---------- 8 files changed, 66 insertions(+), 45 deletions(-) diff --git a/demo/sdl_opengl2/main.c b/demo/sdl_opengl2/main.c index 45c51d2..438f2d3 100644 --- a/demo/sdl_opengl2/main.c +++ b/demo/sdl_opengl2/main.c @@ -139,6 +139,7 @@ main(int argc, char *argv[]) if (evt.type == SDL_QUIT) goto cleanup; nk_sdl_handle_event(&evt); } + nk_sdl_handle_grab(); /* optional grabbing behavior */ nk_input_end(ctx); /* GUI */ diff --git a/demo/sdl_opengl2/nuklear_sdl_gl2.h b/demo/sdl_opengl2/nuklear_sdl_gl2.h index 819723c..067962b 100644 --- a/demo/sdl_opengl2/nuklear_sdl_gl2.h +++ b/demo/sdl_opengl2/nuklear_sdl_gl2.h @@ -233,22 +233,26 @@ nk_sdl_font_stash_end(void) nk_style_set_font(&sdl.ctx, &sdl.atlas.default_font->handle); } +NK_API void +nk_sdl_handle_grab(void) +{ + struct nk_context *ctx = &sdl.ctx; + if (ctx->input.mouse.grab) { + SDL_SetRelativeMouseMode(SDL_TRUE); + } else if (ctx->input.mouse.ungrab) { + SDL_WarpMouseInWindow(sdl.win, (int)ctx->input.mouse.prev.x, (int)ctx->input.mouse.prev.y); + SDL_SetRelativeMouseMode(SDL_FALSE); + } else if (ctx->input.mouse.grabbed) { + ctx->input.mouse.pos.x = ctx->input.mouse.prev.x; + ctx->input.mouse.pos.y = ctx->input.mouse.prev.y; + } +} + NK_API int nk_sdl_handle_event(SDL_Event *evt) { struct nk_context *ctx = &sdl.ctx; - /* optional grabbing behavior */ - if (ctx->input.mouse.grab) { - SDL_SetRelativeMouseMode(SDL_TRUE); - ctx->input.mouse.grab = 0; - } else if (ctx->input.mouse.ungrab) { - int x = (int)ctx->input.mouse.prev.x, y = (int)ctx->input.mouse.prev.y; - SDL_SetRelativeMouseMode(SDL_FALSE); - SDL_WarpMouseInWindow(sdl.win, x, y); - ctx->input.mouse.ungrab = 0; - } - switch(evt->type) { case SDL_KEYUP: /* KEYUP & KEYDOWN share same routine */ diff --git a/demo/sdl_opengl3/main.c b/demo/sdl_opengl3/main.c index e039a2f..44c8c74 100644 --- a/demo/sdl_opengl3/main.c +++ b/demo/sdl_opengl3/main.c @@ -149,7 +149,9 @@ int main(int argc, char *argv[]) while (SDL_PollEvent(&evt)) { if (evt.type == SDL_QUIT) goto cleanup; nk_sdl_handle_event(&evt); - } nk_input_end(ctx); + } + nk_sdl_handle_grab(); /* optional grabbing behavior */ + nk_input_end(ctx); /* GUI */ if (nk_begin(ctx, "Demo", nk_rect(50, 50, 230, 250), diff --git a/demo/sdl_opengl3/nuklear_sdl_gl3.h b/demo/sdl_opengl3/nuklear_sdl_gl3.h index 4e7df6b..4b05003 100644 --- a/demo/sdl_opengl3/nuklear_sdl_gl3.h +++ b/demo/sdl_opengl3/nuklear_sdl_gl3.h @@ -342,22 +342,26 @@ nk_sdl_font_stash_end(void) } +NK_API void +nk_sdl_handle_grab(void) +{ + struct nk_context *ctx = &sdl.ctx; + if (ctx->input.mouse.grab) { + SDL_SetRelativeMouseMode(SDL_TRUE); + } else if (ctx->input.mouse.ungrab) { + SDL_WarpMouseInWindow(sdl.win, (int)ctx->input.mouse.prev.x, (int)ctx->input.mouse.prev.y); + SDL_SetRelativeMouseMode(SDL_FALSE); + } else if (ctx->input.mouse.grabbed) { + ctx->input.mouse.pos.x = ctx->input.mouse.prev.x; + ctx->input.mouse.pos.y = ctx->input.mouse.prev.y; + } +} + NK_API int nk_sdl_handle_event(SDL_Event *evt) { struct nk_context *ctx = &sdl.ctx; - /* optional grabbing behavior */ - if (ctx->input.mouse.grab) { - SDL_SetRelativeMouseMode(SDL_TRUE); - ctx->input.mouse.grab = 0; - } else if (ctx->input.mouse.ungrab) { - int x = (int)ctx->input.mouse.prev.x, y = (int)ctx->input.mouse.prev.y; - SDL_SetRelativeMouseMode(SDL_FALSE); - SDL_WarpMouseInWindow(sdl.win, x, y); - ctx->input.mouse.ungrab = 0; - } - switch(evt->type) { case SDL_KEYUP: /* KEYUP & KEYDOWN share same routine */ diff --git a/demo/sdl_opengles2/main.c b/demo/sdl_opengles2/main.c index b114159..9ef90a7 100644 --- a/demo/sdl_opengles2/main.c +++ b/demo/sdl_opengles2/main.c @@ -92,6 +92,7 @@ MainLoop(void* loopArg){ if (evt.type == SDL_QUIT) running = nk_false; nk_sdl_handle_event(&evt); } + nk_sdl_handle_grab(); /* optional grabbing behavior */ nk_input_end(ctx); diff --git a/demo/sdl_opengles2/nuklear_sdl_gles2.h b/demo/sdl_opengles2/nuklear_sdl_gles2.h index 39a444d..4e97fba 100644 --- a/demo/sdl_opengles2/nuklear_sdl_gles2.h +++ b/demo/sdl_opengles2/nuklear_sdl_gles2.h @@ -342,22 +342,26 @@ nk_sdl_font_stash_end(void) } +NK_API void +nk_sdl_handle_grab(void) +{ + struct nk_context *ctx = &sdl.ctx; + if (ctx->input.mouse.grab) { + SDL_SetRelativeMouseMode(SDL_TRUE); + } else if (ctx->input.mouse.ungrab) { + SDL_WarpMouseInWindow(sdl.win, (int)ctx->input.mouse.prev.x, (int)ctx->input.mouse.prev.y); + SDL_SetRelativeMouseMode(SDL_FALSE); + } else if (ctx->input.mouse.grabbed) { + ctx->input.mouse.pos.x = ctx->input.mouse.prev.x; + ctx->input.mouse.pos.y = ctx->input.mouse.prev.y; + } +} + NK_API int nk_sdl_handle_event(SDL_Event *evt) { struct nk_context *ctx = &sdl.ctx; - /* optional grabbing behavior */ - if (ctx->input.mouse.grab) { - SDL_SetRelativeMouseMode(SDL_TRUE); - ctx->input.mouse.grab = 0; - } else if (ctx->input.mouse.ungrab) { - int x = (int)ctx->input.mouse.prev.x, y = (int)ctx->input.mouse.prev.y; - SDL_SetRelativeMouseMode(SDL_FALSE); - SDL_WarpMouseInWindow(sdl.win, x, y); - ctx->input.mouse.ungrab = 0; - } - switch(evt->type) { case SDL_KEYUP: /* KEYUP & KEYDOWN share same routine */ diff --git a/demo/sdl_renderer/main.c b/demo/sdl_renderer/main.c index 940ea84..a4a0f28 100644 --- a/demo/sdl_renderer/main.c +++ b/demo/sdl_renderer/main.c @@ -177,6 +177,7 @@ main(int argc, char *argv[]) if (evt.type == SDL_QUIT) goto cleanup; nk_sdl_handle_event(&evt); } + nk_sdl_handle_grab(); /* optional grabbing behavior */ nk_input_end(ctx); /* GUI */ diff --git a/demo/sdl_renderer/nuklear_sdl_renderer.h b/demo/sdl_renderer/nuklear_sdl_renderer.h index fbea3cf..e6dc24b 100644 --- a/demo/sdl_renderer/nuklear_sdl_renderer.h +++ b/demo/sdl_renderer/nuklear_sdl_renderer.h @@ -264,22 +264,26 @@ nk_sdl_font_stash_end(void) nk_style_set_font(&sdl.ctx, &sdl.atlas.default_font->handle); } +NK_API void +nk_sdl_handle_grab(void) +{ + struct nk_context *ctx = &sdl.ctx; + if (ctx->input.mouse.grab) { + SDL_SetRelativeMouseMode(SDL_TRUE); + } else if (ctx->input.mouse.ungrab) { + SDL_WarpMouseInWindow(sdl.win, (int)ctx->input.mouse.prev.x, (int)ctx->input.mouse.prev.y); + SDL_SetRelativeMouseMode(SDL_FALSE); + } else if (ctx->input.mouse.grabbed) { + ctx->input.mouse.pos.x = ctx->input.mouse.prev.x; + ctx->input.mouse.pos.y = ctx->input.mouse.prev.y; + } +} + NK_API int nk_sdl_handle_event(SDL_Event *evt) { struct nk_context *ctx = &sdl.ctx; - /* optional grabbing behavior */ - if (ctx->input.mouse.grab) { - SDL_SetRelativeMouseMode(SDL_TRUE); - ctx->input.mouse.grab = 0; - } else if (ctx->input.mouse.ungrab) { - int x = (int)ctx->input.mouse.prev.x, y = (int)ctx->input.mouse.prev.y; - SDL_SetRelativeMouseMode(SDL_FALSE); - SDL_WarpMouseInWindow(sdl.win, x, y); - ctx->input.mouse.ungrab = 0; - } - switch(evt->type) { case SDL_KEYUP: /* KEYUP & KEYDOWN share same routine */ From a10eb1351acfe23cf93cfbf5b021f93ca57a4eee Mon Sep 17 00:00:00 2001 From: paccer Date: Sat, 10 Feb 2024 17:21:32 +0100 Subject: [PATCH 095/106] Fix cursor warping to center on older SDL versions Reverted the order of the SDL_WarpMouseInWindow and SDL_GetMouseState to its original sequence. This avoids cursor warping to the center of screen on older SDL versions It causes an additional SDL_MOUSEMOTION event when ungrabbing, but does not cause any issues. --- demo/sdl_opengl2/nuklear_sdl_gl2.h | 2 +- demo/sdl_opengl3/nuklear_sdl_gl3.h | 2 +- demo/sdl_opengles2/nuklear_sdl_gles2.h | 2 +- demo/sdl_renderer/nuklear_sdl_renderer.h | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/demo/sdl_opengl2/nuklear_sdl_gl2.h b/demo/sdl_opengl2/nuklear_sdl_gl2.h index 067962b..2a885b5 100644 --- a/demo/sdl_opengl2/nuklear_sdl_gl2.h +++ b/demo/sdl_opengl2/nuklear_sdl_gl2.h @@ -240,8 +240,8 @@ nk_sdl_handle_grab(void) if (ctx->input.mouse.grab) { SDL_SetRelativeMouseMode(SDL_TRUE); } else if (ctx->input.mouse.ungrab) { - SDL_WarpMouseInWindow(sdl.win, (int)ctx->input.mouse.prev.x, (int)ctx->input.mouse.prev.y); SDL_SetRelativeMouseMode(SDL_FALSE); + SDL_WarpMouseInWindow(sdl.win, (int)ctx->input.mouse.prev.x, (int)ctx->input.mouse.prev.y); } else if (ctx->input.mouse.grabbed) { ctx->input.mouse.pos.x = ctx->input.mouse.prev.x; ctx->input.mouse.pos.y = ctx->input.mouse.prev.y; diff --git a/demo/sdl_opengl3/nuklear_sdl_gl3.h b/demo/sdl_opengl3/nuklear_sdl_gl3.h index 4b05003..7c847b1 100644 --- a/demo/sdl_opengl3/nuklear_sdl_gl3.h +++ b/demo/sdl_opengl3/nuklear_sdl_gl3.h @@ -349,8 +349,8 @@ nk_sdl_handle_grab(void) if (ctx->input.mouse.grab) { SDL_SetRelativeMouseMode(SDL_TRUE); } else if (ctx->input.mouse.ungrab) { - SDL_WarpMouseInWindow(sdl.win, (int)ctx->input.mouse.prev.x, (int)ctx->input.mouse.prev.y); SDL_SetRelativeMouseMode(SDL_FALSE); + SDL_WarpMouseInWindow(sdl.win, (int)ctx->input.mouse.prev.x, (int)ctx->input.mouse.prev.y); } else if (ctx->input.mouse.grabbed) { ctx->input.mouse.pos.x = ctx->input.mouse.prev.x; ctx->input.mouse.pos.y = ctx->input.mouse.prev.y; diff --git a/demo/sdl_opengles2/nuklear_sdl_gles2.h b/demo/sdl_opengles2/nuklear_sdl_gles2.h index 4e97fba..e3f4afb 100644 --- a/demo/sdl_opengles2/nuklear_sdl_gles2.h +++ b/demo/sdl_opengles2/nuklear_sdl_gles2.h @@ -349,8 +349,8 @@ nk_sdl_handle_grab(void) if (ctx->input.mouse.grab) { SDL_SetRelativeMouseMode(SDL_TRUE); } else if (ctx->input.mouse.ungrab) { - SDL_WarpMouseInWindow(sdl.win, (int)ctx->input.mouse.prev.x, (int)ctx->input.mouse.prev.y); SDL_SetRelativeMouseMode(SDL_FALSE); + SDL_WarpMouseInWindow(sdl.win, (int)ctx->input.mouse.prev.x, (int)ctx->input.mouse.prev.y); } else if (ctx->input.mouse.grabbed) { ctx->input.mouse.pos.x = ctx->input.mouse.prev.x; ctx->input.mouse.pos.y = ctx->input.mouse.prev.y; diff --git a/demo/sdl_renderer/nuklear_sdl_renderer.h b/demo/sdl_renderer/nuklear_sdl_renderer.h index e6dc24b..f2670bb 100644 --- a/demo/sdl_renderer/nuklear_sdl_renderer.h +++ b/demo/sdl_renderer/nuklear_sdl_renderer.h @@ -271,8 +271,8 @@ nk_sdl_handle_grab(void) if (ctx->input.mouse.grab) { SDL_SetRelativeMouseMode(SDL_TRUE); } else if (ctx->input.mouse.ungrab) { - SDL_WarpMouseInWindow(sdl.win, (int)ctx->input.mouse.prev.x, (int)ctx->input.mouse.prev.y); SDL_SetRelativeMouseMode(SDL_FALSE); + SDL_WarpMouseInWindow(sdl.win, (int)ctx->input.mouse.prev.x, (int)ctx->input.mouse.prev.y); } else if (ctx->input.mouse.grabbed) { ctx->input.mouse.pos.x = ctx->input.mouse.prev.x; ctx->input.mouse.pos.y = ctx->input.mouse.prev.y; From 56ab9d96eac8af467cfdd02523497ca6a15715d8 Mon Sep 17 00:00:00 2001 From: paccer Date: Fri, 23 Feb 2024 20:39:08 +0100 Subject: [PATCH 096/106] Added comment to nk_sdl_handle_grab in SDL demos Explains call order of SDL_SetRelativeMouseMode and SDL_SetWindowGrab --- demo/sdl_opengl2/nuklear_sdl_gl2.h | 1 + demo/sdl_opengl3/nuklear_sdl_gl3.h | 1 + demo/sdl_opengles2/nuklear_sdl_gles2.h | 1 + demo/sdl_renderer/nuklear_sdl_renderer.h | 1 + 4 files changed, 4 insertions(+) diff --git a/demo/sdl_opengl2/nuklear_sdl_gl2.h b/demo/sdl_opengl2/nuklear_sdl_gl2.h index 2a885b5..fbc7ec7 100644 --- a/demo/sdl_opengl2/nuklear_sdl_gl2.h +++ b/demo/sdl_opengl2/nuklear_sdl_gl2.h @@ -240,6 +240,7 @@ nk_sdl_handle_grab(void) if (ctx->input.mouse.grab) { SDL_SetRelativeMouseMode(SDL_TRUE); } else if (ctx->input.mouse.ungrab) { + /* better support for older SDL by setting mode first; causes an extra mouse motion event */ SDL_SetRelativeMouseMode(SDL_FALSE); SDL_WarpMouseInWindow(sdl.win, (int)ctx->input.mouse.prev.x, (int)ctx->input.mouse.prev.y); } else if (ctx->input.mouse.grabbed) { diff --git a/demo/sdl_opengl3/nuklear_sdl_gl3.h b/demo/sdl_opengl3/nuklear_sdl_gl3.h index 7c847b1..6c9d4b1 100644 --- a/demo/sdl_opengl3/nuklear_sdl_gl3.h +++ b/demo/sdl_opengl3/nuklear_sdl_gl3.h @@ -349,6 +349,7 @@ nk_sdl_handle_grab(void) if (ctx->input.mouse.grab) { SDL_SetRelativeMouseMode(SDL_TRUE); } else if (ctx->input.mouse.ungrab) { + /* better support for older SDL by setting mode first; causes an extra mouse motion event */ SDL_SetRelativeMouseMode(SDL_FALSE); SDL_WarpMouseInWindow(sdl.win, (int)ctx->input.mouse.prev.x, (int)ctx->input.mouse.prev.y); } else if (ctx->input.mouse.grabbed) { diff --git a/demo/sdl_opengles2/nuklear_sdl_gles2.h b/demo/sdl_opengles2/nuklear_sdl_gles2.h index e3f4afb..6f46d52 100644 --- a/demo/sdl_opengles2/nuklear_sdl_gles2.h +++ b/demo/sdl_opengles2/nuklear_sdl_gles2.h @@ -349,6 +349,7 @@ nk_sdl_handle_grab(void) if (ctx->input.mouse.grab) { SDL_SetRelativeMouseMode(SDL_TRUE); } else if (ctx->input.mouse.ungrab) { + /* better support for older SDL by setting mode first; causes an extra mouse motion event */ SDL_SetRelativeMouseMode(SDL_FALSE); SDL_WarpMouseInWindow(sdl.win, (int)ctx->input.mouse.prev.x, (int)ctx->input.mouse.prev.y); } else if (ctx->input.mouse.grabbed) { diff --git a/demo/sdl_renderer/nuklear_sdl_renderer.h b/demo/sdl_renderer/nuklear_sdl_renderer.h index f2670bb..fb8596f 100644 --- a/demo/sdl_renderer/nuklear_sdl_renderer.h +++ b/demo/sdl_renderer/nuklear_sdl_renderer.h @@ -271,6 +271,7 @@ nk_sdl_handle_grab(void) if (ctx->input.mouse.grab) { SDL_SetRelativeMouseMode(SDL_TRUE); } else if (ctx->input.mouse.ungrab) { + /* better support for older SDL by setting mode first; causes an extra mouse motion event */ SDL_SetRelativeMouseMode(SDL_FALSE); SDL_WarpMouseInWindow(sdl.win, (int)ctx->input.mouse.prev.x, (int)ctx->input.mouse.prev.y); } else if (ctx->input.mouse.grabbed) { From 254dfc212096cb04524a7a2a8ffcc2d91ed29d26 Mon Sep 17 00:00:00 2001 From: Brian Watling Date: Mon, 26 Feb 2024 22:58:44 -0500 Subject: [PATCH 097/106] s/hide_markers/show_markers/ --- demo/common/overview.c | 6 +++--- nuklear.h | 14 +++++++------- src/nuklear.h | 4 ++-- src/nuklear_chart.c | 8 ++++---- src/nuklear_style.c | 2 +- 5 files changed, 17 insertions(+), 17 deletions(-) diff --git a/demo/common/overview.c b/demo/common/overview.c index a006e2e..cd56864 100644 --- a/demo/common/overview.c +++ b/demo/common/overview.c @@ -621,7 +621,7 @@ overview(struct nk_context *ctx) float id = 0; static int col_index = -1; static int line_index = -1; - static int hide_markers = nk_false; + static int show_markers = nk_true; float step = (2*3.141592654f) / 32; int i; @@ -631,9 +631,9 @@ overview(struct nk_context *ctx) id = 0; index = -1; nk_layout_row_dynamic(ctx, 15, 1); - nk_checkbox_label(ctx, "Hide markers", &hide_markers); + nk_checkbox_label(ctx, "Show markers", &show_markers); nk_layout_row_dynamic(ctx, 100, 1); - ctx->style.chart.hide_markers = hide_markers; + ctx->style.chart.show_markers = show_markers; if (nk_chart_begin(ctx, NK_CHART_LINES, 32, -1.0f, 1.0f)) { for (i = 0; i < 32; ++i) { nk_flags res = nk_chart_push(ctx, (float)cos(id)); diff --git a/nuklear.h b/nuklear.h index 8cf381e..b534598 100644 --- a/nuklear.h +++ b/nuklear.h @@ -5198,7 +5198,7 @@ struct nk_style_chart { struct nk_vec2 padding; float color_factor; float disabled_factor; - nk_bool hide_markers; + nk_bool show_markers; }; struct nk_style_combo { @@ -5389,7 +5389,7 @@ struct nk_chart_slot { int count; struct nk_vec2 last; int index; - nk_bool hide_markers; + nk_bool show_markers; }; struct nk_chart { @@ -18658,7 +18658,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) chart->rounding = 0; chart->color_factor = 1.0f; chart->disabled_factor = NK_WIDGET_DISABLED_FACTOR; - chart->hide_markers = nk_false; + chart->show_markers = nk_true; /* combo */ combo = &style->combo; @@ -28496,7 +28496,7 @@ nk_chart_begin_colored(struct nk_context *ctx, enum nk_chart_type type, slot->min = NK_MIN(min_value, max_value); slot->max = NK_MAX(min_value, max_value); slot->range = slot->max - slot->min; - slot->hide_markers = style->hide_markers;} + slot->show_markers = style->show_markers;} /* draw chart background */ background = &style->background; @@ -28549,7 +28549,7 @@ nk_chart_add_slot_colored(struct nk_context *ctx, const enum nk_chart_type type, slot->min = NK_MIN(min_value, max_value); slot->max = NK_MAX(min_value, max_value); slot->range = slot->max - slot->min; - slot->hide_markers = style->hide_markers;} + slot->show_markers = style->show_markers;} } NK_API void nk_chart_add_slot(struct nk_context *ctx, const enum nk_chart_type type, @@ -28596,7 +28596,7 @@ nk_chart_push_line(struct nk_context *ctx, struct nk_window *win, i->mouse.buttons[NK_BUTTON_LEFT].clicked) ? NK_CHART_CLICKED: 0; color = g->slots[slot].highlight; } - if (!g->slots[slot].hide_markers) { + if (g->slots[slot].show_markers) { nk_fill_rect(out, bounds, 0, color); } g->slots[slot].index += 1; @@ -28622,7 +28622,7 @@ nk_chart_push_line(struct nk_context *ctx, struct nk_window *win, color = g->slots[slot].highlight; } } - if (!g->slots[slot].hide_markers) { + if (g->slots[slot].show_markers) { nk_fill_rect(out, nk_rect(cur.x - 2, cur.y - 2, 4, 4), 0, color); } diff --git a/src/nuklear.h b/src/nuklear.h index 18f263e..9348bf3 100644 --- a/src/nuklear.h +++ b/src/nuklear.h @@ -4976,7 +4976,7 @@ struct nk_style_chart { struct nk_vec2 padding; float color_factor; float disabled_factor; - nk_bool hide_markers; + nk_bool show_markers; }; struct nk_style_combo { @@ -5167,7 +5167,7 @@ struct nk_chart_slot { int count; struct nk_vec2 last; int index; - nk_bool hide_markers; + nk_bool show_markers; }; struct nk_chart { diff --git a/src/nuklear_chart.c b/src/nuklear_chart.c index d177a83..87301fa 100644 --- a/src/nuklear_chart.c +++ b/src/nuklear_chart.c @@ -53,7 +53,7 @@ nk_chart_begin_colored(struct nk_context *ctx, enum nk_chart_type type, slot->min = NK_MIN(min_value, max_value); slot->max = NK_MAX(min_value, max_value); slot->range = slot->max - slot->min; - slot->hide_markers = style->hide_markers;} + slot->show_markers = style->show_markers;} /* draw chart background */ background = &style->background; @@ -106,7 +106,7 @@ nk_chart_add_slot_colored(struct nk_context *ctx, const enum nk_chart_type type, slot->min = NK_MIN(min_value, max_value); slot->max = NK_MAX(min_value, max_value); slot->range = slot->max - slot->min; - slot->hide_markers = style->hide_markers;} + slot->show_markers = style->show_markers;} } NK_API void nk_chart_add_slot(struct nk_context *ctx, const enum nk_chart_type type, @@ -153,7 +153,7 @@ nk_chart_push_line(struct nk_context *ctx, struct nk_window *win, i->mouse.buttons[NK_BUTTON_LEFT].clicked) ? NK_CHART_CLICKED: 0; color = g->slots[slot].highlight; } - if (!g->slots[slot].hide_markers) { + if (g->slots[slot].show_markers) { nk_fill_rect(out, bounds, 0, color); } g->slots[slot].index += 1; @@ -179,7 +179,7 @@ nk_chart_push_line(struct nk_context *ctx, struct nk_window *win, color = g->slots[slot].highlight; } } - if (!g->slots[slot].hide_markers) { + if (g->slots[slot].show_markers) { nk_fill_rect(out, nk_rect(cur.x - 2, cur.y - 2, 4, 4), 0, color); } diff --git a/src/nuklear_style.c b/src/nuklear_style.c index 0ddc89b..709fe68 100644 --- a/src/nuklear_style.c +++ b/src/nuklear_style.c @@ -486,7 +486,7 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) chart->rounding = 0; chart->color_factor = 1.0f; chart->disabled_factor = NK_WIDGET_DISABLED_FACTOR; - chart->hide_markers = nk_false; + chart->show_markers = nk_true; /* combo */ combo = &style->combo; From 1edb78e4d0d55e69eb59606e7ba5ef11b6fe2646 Mon Sep 17 00:00:00 2001 From: Lautriva Date: Thu, 7 Mar 2024 13:27:33 +0100 Subject: [PATCH 098/106] Fix bitwise operations warnings in C++20 --- nuklear.h | 16 ++++++++-------- src/CHANGELOG | 1 + src/nuklear_contextual.c | 2 +- src/nuklear_panel.c | 4 ++-- src/nuklear_popup.c | 6 +++--- src/nuklear_property.c | 2 +- src/nuklear_tooltip.c | 2 +- 7 files changed, 17 insertions(+), 16 deletions(-) diff --git a/nuklear.h b/nuklear.h index bcb220e..f1628cd 100644 --- a/nuklear.h +++ b/nuklear.h @@ -19667,12 +19667,12 @@ nk_panel_get_border_color(const struct nk_style *style, enum nk_panel_type type) NK_LIB nk_bool nk_panel_is_sub(enum nk_panel_type type) { - return (type & NK_PANEL_SET_SUB)?1:0; + return ((int)type & (int)NK_PANEL_SET_SUB)?1:0; } NK_LIB nk_bool nk_panel_is_nonblock(enum nk_panel_type type) { - return (type & NK_PANEL_SET_NONBLOCK)?1:0; + return ((int)type & (int)NK_PANEL_SET_NONBLOCK)?1:0; } NK_LIB nk_bool nk_panel_begin(struct nk_context *ctx, const char *title, enum nk_panel_type panel_type) @@ -20922,7 +20922,7 @@ nk_popup_begin(struct nk_context *ctx, enum nk_popup_type type, win = ctx->current; panel = win->layout; - NK_ASSERT(!(panel->type & NK_PANEL_SET_POPUP) && "popups are not allowed to have popups"); + NK_ASSERT(!((int)panel->type & (int)NK_PANEL_SET_POPUP) && "popups are not allowed to have popups"); (void)panel; title_len = (int)nk_strlen(title); title_hash = nk_murmur_hash(title, (int)title_len, NK_PANEL_POPUP); @@ -21016,7 +21016,7 @@ nk_nonblock_begin(struct nk_context *ctx, /* popups cannot have popups */ win = ctx->current; panel = win->layout; - NK_ASSERT(!(panel->type & NK_PANEL_SET_POPUP)); + NK_ASSERT(!((int)panel->type & (int)NK_PANEL_SET_POPUP)); (void)panel; popup = win->popup.win; if (!popup) { @@ -21089,7 +21089,7 @@ nk_popup_close(struct nk_context *ctx) popup = ctx->current; NK_ASSERT(popup->parent); - NK_ASSERT(popup->layout->type & NK_PANEL_SET_POPUP); + NK_ASSERT((int)popup->layout->type & (int)NK_PANEL_SET_POPUP); popup->flags |= NK_WINDOW_HIDDEN; } NK_API void @@ -21357,7 +21357,7 @@ nk_contextual_end(struct nk_context *ctx) popup = ctx->current; panel = popup->layout; NK_ASSERT(popup->parent); - NK_ASSERT(panel->type & NK_PANEL_SET_POPUP); + NK_ASSERT((int)panel->type & (int)NK_PANEL_SET_POPUP); if (panel->flags & NK_WINDOW_DYNAMIC) { /* Close behavior This is a bit of a hack solution since we do not know before we end our popup @@ -28322,7 +28322,7 @@ nk_do_property(nk_flags *ws, text_edit->string.buffer.memory.ptr = dst; text_edit->string.buffer.size = NK_MAX_NUMBER_BUFFER; text_edit->mode = NK_TEXT_EDIT_MODE_INSERT; - nk_do_edit(ws, out, edit, NK_EDIT_FIELD|NK_EDIT_AUTO_SELECT, + nk_do_edit(ws, out, edit, (int)NK_EDIT_FIELD|(int)NK_EDIT_AUTO_SELECT, filters[filter], text_edit, &style->edit, (*state == NK_PROPERTY_EDIT) ? in: 0, font); *length = text_edit->string.len; @@ -29982,7 +29982,7 @@ nk_tooltip_begin(struct nk_context *ctx, float width) /* make sure that no nonblocking popup is currently active */ win = ctx->current; in = &ctx->input; - if (win->popup.win && (win->popup.type & NK_PANEL_SET_NONBLOCK)) + if (win->popup.win && ((int)win->popup.type & (int)NK_PANEL_SET_NONBLOCK)) return 0; w = nk_iceilf(width); diff --git a/src/CHANGELOG b/src/CHANGELOG index 8bd34dc..7cd702e 100644 --- a/src/CHANGELOG +++ b/src/CHANGELOG @@ -7,6 +7,7 @@ /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// +/// - 2024/07/03 (4.12.1) - Fix bitwise operations warnings in C++20 /// - 2023/11/26 (4.12.0) - Added an alignment option to checkboxes and radio buttons. /// - 2023/10/11 (4.11.0) - Added nk_widget_disable_begin() and nk_widget_disable_end() /// - 2022/12/23 (4.10.6) - Fix incorrect glyph index in nk_font_bake() diff --git a/src/nuklear_contextual.c b/src/nuklear_contextual.c index f3e7db0..da66854 100644 --- a/src/nuklear_contextual.c +++ b/src/nuklear_contextual.c @@ -198,7 +198,7 @@ nk_contextual_end(struct nk_context *ctx) popup = ctx->current; panel = popup->layout; NK_ASSERT(popup->parent); - NK_ASSERT(panel->type & NK_PANEL_SET_POPUP); + NK_ASSERT((int)panel->type & (int)NK_PANEL_SET_POPUP); if (panel->flags & NK_WINDOW_DYNAMIC) { /* Close behavior This is a bit of a hack solution since we do not know before we end our popup diff --git a/src/nuklear_panel.c b/src/nuklear_panel.c index f170d7c..792d774 100644 --- a/src/nuklear_panel.c +++ b/src/nuklear_panel.c @@ -76,12 +76,12 @@ nk_panel_get_border_color(const struct nk_style *style, enum nk_panel_type type) NK_LIB nk_bool nk_panel_is_sub(enum nk_panel_type type) { - return (type & NK_PANEL_SET_SUB)?1:0; + return ((int)type & (int)NK_PANEL_SET_SUB)?1:0; } NK_LIB nk_bool nk_panel_is_nonblock(enum nk_panel_type type) { - return (type & NK_PANEL_SET_NONBLOCK)?1:0; + return ((int)type & (int)NK_PANEL_SET_NONBLOCK)?1:0; } NK_LIB nk_bool nk_panel_begin(struct nk_context *ctx, const char *title, enum nk_panel_type panel_type) diff --git a/src/nuklear_popup.c b/src/nuklear_popup.c index e0c64dc..ee3a578 100644 --- a/src/nuklear_popup.c +++ b/src/nuklear_popup.c @@ -27,7 +27,7 @@ nk_popup_begin(struct nk_context *ctx, enum nk_popup_type type, win = ctx->current; panel = win->layout; - NK_ASSERT(!(panel->type & NK_PANEL_SET_POPUP) && "popups are not allowed to have popups"); + NK_ASSERT(!((int)panel->type & (int)NK_PANEL_SET_POPUP) && "popups are not allowed to have popups"); (void)panel; title_len = (int)nk_strlen(title); title_hash = nk_murmur_hash(title, (int)title_len, NK_PANEL_POPUP); @@ -121,7 +121,7 @@ nk_nonblock_begin(struct nk_context *ctx, /* popups cannot have popups */ win = ctx->current; panel = win->layout; - NK_ASSERT(!(panel->type & NK_PANEL_SET_POPUP)); + NK_ASSERT(!((int)panel->type & (int)NK_PANEL_SET_POPUP)); (void)panel; popup = win->popup.win; if (!popup) { @@ -194,7 +194,7 @@ nk_popup_close(struct nk_context *ctx) popup = ctx->current; NK_ASSERT(popup->parent); - NK_ASSERT(popup->layout->type & NK_PANEL_SET_POPUP); + NK_ASSERT((int)popup->layout->type & (int)NK_PANEL_SET_POPUP); popup->flags |= NK_WINDOW_HIDDEN; } NK_API void diff --git a/src/nuklear_property.c b/src/nuklear_property.c index 2a34eb7..fb76d67 100644 --- a/src/nuklear_property.c +++ b/src/nuklear_property.c @@ -251,7 +251,7 @@ nk_do_property(nk_flags *ws, text_edit->string.buffer.memory.ptr = dst; text_edit->string.buffer.size = NK_MAX_NUMBER_BUFFER; text_edit->mode = NK_TEXT_EDIT_MODE_INSERT; - nk_do_edit(ws, out, edit, NK_EDIT_FIELD|NK_EDIT_AUTO_SELECT, + nk_do_edit(ws, out, edit, (int)NK_EDIT_FIELD|(int)NK_EDIT_AUTO_SELECT, filters[filter], text_edit, &style->edit, (*state == NK_PROPERTY_EDIT) ? in: 0, font); *length = text_edit->string.len; diff --git a/src/nuklear_tooltip.c b/src/nuklear_tooltip.c index 38d8696..f4d78c6 100644 --- a/src/nuklear_tooltip.c +++ b/src/nuklear_tooltip.c @@ -24,7 +24,7 @@ nk_tooltip_begin(struct nk_context *ctx, float width) /* make sure that no nonblocking popup is currently active */ win = ctx->current; in = &ctx->input; - if (win->popup.win && (win->popup.type & NK_PANEL_SET_NONBLOCK)) + if (win->popup.win && ((int)win->popup.type & (int)NK_PANEL_SET_NONBLOCK)) return 0; w = nk_iceilf(width); From d40d95471e509d7a51bcd860495b31a155c9f796 Mon Sep 17 00:00:00 2001 From: Lautriva Date: Thu, 7 Mar 2024 13:39:12 +0100 Subject: [PATCH 099/106] Add Changelog in nuklear.h for 4.12.1 --- nuklear.h | 1 + 1 file changed, 1 insertion(+) diff --git a/nuklear.h b/nuklear.h index f1628cd..d0ea41b 100644 --- a/nuklear.h +++ b/nuklear.h @@ -30123,6 +30123,7 @@ nk_tooltipfv(struct nk_context *ctx, const char *fmt, va_list args) /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// +/// - 2024/07/03 (4.12.1) - Fix bitwise operations warnings in C++20 /// - 2023/11/26 (4.12.0) - Added an alignment option to checkboxes and radio buttons. /// - 2023/10/11 (4.11.0) - Added nk_widget_disable_begin() and nk_widget_disable_end() /// - 2022/12/23 (4.10.6) - Fix incorrect glyph index in nk_font_bake() From 5f2e2af7378ea4d2ea015701bf875cba6efe451a Mon Sep 17 00:00:00 2001 From: Lautriva Date: Thu, 7 Mar 2024 13:40:31 +0100 Subject: [PATCH 100/106] Add Changelog in nuklear.h for 4.12.1 --- nuklear.h | 2 +- src/CHANGELOG | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nuklear.h b/nuklear.h index d0ea41b..3f2b2f8 100644 --- a/nuklear.h +++ b/nuklear.h @@ -30123,7 +30123,7 @@ nk_tooltipfv(struct nk_context *ctx, const char *fmt, va_list args) /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// -/// - 2024/07/03 (4.12.1) - Fix bitwise operations warnings in C++20 +/// - 2024/03/07 (4.12.1) - Fix bitwise operations warnings in C++20 /// - 2023/11/26 (4.12.0) - Added an alignment option to checkboxes and radio buttons. /// - 2023/10/11 (4.11.0) - Added nk_widget_disable_begin() and nk_widget_disable_end() /// - 2022/12/23 (4.10.6) - Fix incorrect glyph index in nk_font_bake() diff --git a/src/CHANGELOG b/src/CHANGELOG index 7cd702e..c301e31 100644 --- a/src/CHANGELOG +++ b/src/CHANGELOG @@ -7,7 +7,7 @@ /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// -/// - 2024/07/03 (4.12.1) - Fix bitwise operations warnings in C++20 +/// - 2024/03/07 (4.12.1) - Fix bitwise operations warnings in C++20 /// - 2023/11/26 (4.12.0) - Added an alignment option to checkboxes and radio buttons. /// - 2023/10/11 (4.11.0) - Added nk_widget_disable_begin() and nk_widget_disable_end() /// - 2022/12/23 (4.10.6) - Fix incorrect glyph index in nk_font_bake() From 40a172bdaa8ec6de61af92c655e592f305cdc66d Mon Sep 17 00:00:00 2001 From: Jonathan Bradley Date: Fri, 8 Mar 2024 11:40:43 -0500 Subject: [PATCH 101/106] demo: don't error-out on VK_SUBOPTIMAL_KHR --- demo/glfw_vulkan/main.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demo/glfw_vulkan/main.c b/demo/glfw_vulkan/main.c index 555a5aa..a77f2da 100644 --- a/demo/glfw_vulkan/main.c +++ b/demo/glfw_vulkan/main.c @@ -2219,7 +2219,7 @@ int main(void) { if (result == VK_ERROR_OUT_OF_DATE_KHR) { continue; } - if (result != VK_SUCCESS) { + if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) { fprintf(stderr, "vkAcquireNextImageKHR failed: %d\n", result); return false; } From 03aa3086a0c1a7401b60098b4719300f7107e016 Mon Sep 17 00:00:00 2001 From: Jonathan Bradley Date: Fri, 8 Mar 2024 15:01:13 -0500 Subject: [PATCH 102/106] demo: don't error-out on image count difference The Vulkan spec states that create_info.minImageCount determines the minimum number of images to create, not the exact count. The count retrieved via vkGetSwapchainImagesKHR can (and in my case does) differ - without penalty to the rest of the demo. --- demo/glfw_vulkan/main.c | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/demo/glfw_vulkan/main.c b/demo/glfw_vulkan/main.c index a77f2da..071ec31 100644 --- a/demo/glfw_vulkan/main.c +++ b/demo/glfw_vulkan/main.c @@ -758,7 +758,6 @@ bool create_swap_chain(struct vulkan_demo *demo) { VkResult result; VkSwapchainCreateInfoKHR create_info; uint32_t queue_family_indices[2]; - uint32_t old_swap_chain_images_len; bool ret = false; queue_family_indices[0] = (uint32_t)demo->indices.graphics; @@ -815,22 +814,12 @@ bool create_swap_chain(struct vulkan_demo *demo) { goto cleanup; } - old_swap_chain_images_len = demo->swap_chain_images_len; result = vkGetSwapchainImagesKHR(demo->device, demo->swap_chain, &demo->swap_chain_images_len, NULL); if (result != VK_SUCCESS) { fprintf(stderr, "vkGetSwapchainImagesKHR failed: %d\n", result); goto cleanup; } - if (old_swap_chain_images_len > 0 && - old_swap_chain_images_len != demo->swap_chain_images_len) { - fprintf(stderr, - "number of assigned swap chain images changed between " - "runs. old: %u, new: %u\n", - (unsigned)old_swap_chain_images_len, - (unsigned)demo->swap_chain_images_len); - goto cleanup; - } if (demo->swap_chain_images == NULL) { demo->swap_chain_images = malloc(demo->swap_chain_images_len * sizeof(VkImage)); From c8e91e571cc2450da917ffc284deb5dc4ddf773c Mon Sep 17 00:00:00 2001 From: Victor Chernyakin Date: Thu, 4 Apr 2024 10:13:08 -0700 Subject: [PATCH 103/106] Fix `strncpy()` call to use nuklear API (#595) --- example/file_browser.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/example/file_browser.c b/example/file_browser.c index 6bf23c2..30f2a46 100644 --- a/example/file_browser.c +++ b/example/file_browser.c @@ -345,7 +345,8 @@ media_init(struct media *media) static void file_browser_reload_directory_content(struct file_browser *browser, const char *path) { - strncpy(browser->directory, path, MAX_PATH_LEN); + const size_t path_len = nk_strlen(path) + 1; + NK_MEMCPY(browser->directory, path, MIN(path_len, MAX_PATH_LEN)); browser->directory[MAX_PATH_LEN - 1] = 0; dir_free_list(browser->files, browser->file_count); dir_free_list(browser->directories, browser->dir_count); From a46521c099276bb066d0a972f3b7dd7edcefccdc Mon Sep 17 00:00:00 2001 From: Rob Loach Date: Thu, 4 Apr 2024 13:25:45 -0400 Subject: [PATCH 104/106] Fix overview mixed declarations --- demo/common/overview.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/demo/common/overview.c b/demo/common/overview.c index becdade..f5572f8 100644 --- a/demo/common/overview.c +++ b/demo/common/overview.c @@ -6,14 +6,15 @@ overview(struct nk_context *ctx) static nk_flags window_flags = NK_WINDOW_TITLE|NK_WINDOW_BORDER|NK_WINDOW_SCALABLE|NK_WINDOW_MOVABLE|NK_WINDOW_MINIMIZABLE; nk_flags actual_window_flags; + /* widget flags */ + static nk_bool disable_widgets = nk_false; + /* popups */ static enum nk_style_header_align header_align = NK_HEADER_RIGHT; static nk_bool show_app_about = nk_false; ctx->style.window.header.align = header_align; - static nk_bool disable_widgets = nk_false; - actual_window_flags = window_flags; if (!(actual_window_flags & NK_WINDOW_TITLE)) actual_window_flags &= ~(NK_WINDOW_MINIMIZABLE|NK_WINDOW_CLOSABLE); From 5fb51369a1a8b3a930468a0c31c588009ef7f537 Mon Sep 17 00:00:00 2001 From: Rob Loach Date: Sat, 6 Apr 2024 01:27:07 -0400 Subject: [PATCH 105/106] Update rawfb demos to use similar code (#629) This change unifies the rawfb code, by @ccawley2011. --- .github/workflows/ccpp.yml | 10 +- demo/{x11_rawfb => rawfb}/nuklear_rawfb.h | 182 ++-- .../{sdl2surface_rawfb => rawfb/sdl}/Makefile | 2 +- demo/{sdl2surface_rawfb => rawfb/sdl}/main.c | 24 +- .../sdl/nuklear_sdl_rawfb.h} | 457 ++++----- .../wayland}/.gitignore | 0 .../{wayland_rawfb => rawfb/wayland}/Makefile | 0 demo/{wayland_rawfb => rawfb/wayland}/main.c | 236 +++-- demo/{x11_rawfb => rawfb/x11}/Makefile | 0 demo/{x11_rawfb => rawfb/x11}/main.c | 14 +- demo/{x11_rawfb => rawfb/x11}/nuklear_xlib.h | 0 demo/wayland_rawfb/nuklear_raw_wayland.h | 869 ------------------ 12 files changed, 457 insertions(+), 1337 deletions(-) rename demo/{x11_rawfb => rawfb}/nuklear_rawfb.h (89%) rename demo/{sdl2surface_rawfb => rawfb/sdl}/Makefile (87%) rename demo/{sdl2surface_rawfb => rawfb/sdl}/main.c (93%) rename demo/{sdl2surface_rawfb/sdl2surface_rawfb.h => rawfb/sdl/nuklear_sdl_rawfb.h} (61%) rename demo/{wayland_rawfb => rawfb/wayland}/.gitignore (100%) rename demo/{wayland_rawfb => rawfb/wayland}/Makefile (100%) rename demo/{wayland_rawfb => rawfb/wayland}/main.c (75%) rename demo/{x11_rawfb => rawfb/x11}/Makefile (100%) rename demo/{x11_rawfb => rawfb/x11}/main.c (96%) rename demo/{x11_rawfb => rawfb/x11}/nuklear_xlib.h (100%) delete mode 100644 demo/wayland_rawfb/nuklear_raw_wayland.h diff --git a/.github/workflows/ccpp.yml b/.github/workflows/ccpp.yml index f495a78..be1e542 100644 --- a/.github/workflows/ccpp.yml +++ b/.github/workflows/ccpp.yml @@ -6,7 +6,7 @@ jobs: build: runs-on: ubuntu-latest - + steps: - uses: actions/checkout@v4 - name: apt-update @@ -31,10 +31,10 @@ jobs: run: make -C demo/sdl_opengles2 - name: build sdl_renderer run: make -C demo/sdl_renderer - - name: build sdl2surface_rawfb - run: make -C demo/sdl2surface_rawfb + - name: build sdl_rawfb + run: make -C demo/rawfb/sdl - name: build wayland_rawfb - run: make -C demo/wayland_rawfb + run: make -C demo/rawfb/wayland - name: build x11 run: make -C demo/x11 - name: build x11_opengl2 @@ -42,7 +42,7 @@ jobs: - name: build x11_opengl3 run: make -C demo/x11_opengl3 - name: build x11_rawfb - run: make -C demo/x11_rawfb + run: make -C demo/rawfb/x11 - name: build x11_xft run: make -C demo/x11_xft - name: build example diff --git a/demo/x11_rawfb/nuklear_rawfb.h b/demo/rawfb/nuklear_rawfb.h similarity index 89% rename from demo/x11_rawfb/nuklear_rawfb.h rename to demo/rawfb/nuklear_rawfb.h index 6aece67..42cc638 100644 --- a/demo/x11_rawfb/nuklear_rawfb.h +++ b/demo/rawfb/nuklear_rawfb.h @@ -87,21 +87,21 @@ nk_rawfb_color2int(const struct nk_color c, rawfb_pl pl) switch (pl) { case PIXEL_LAYOUT_RGBX_8888: - res |= c.r << 24; - res |= c.g << 16; - res |= c.b << 8; - res |= c.a; - break; + res |= c.r << 24; + res |= c.g << 16; + res |= c.b << 8; + res |= c.a; + break; case PIXEL_LAYOUT_XRGB_8888: - res |= c.a << 24; - res |= c.r << 16; - res |= c.g << 8; - res |= c.b; - break; + res |= c.a << 24; + res |= c.r << 16; + res |= c.g << 8; + res |= c.b; + break; default: - perror("nk_rawfb_color2int(): Unsupported pixel layout.\n"); - break; + perror("nk_rawfb_color2int(): Unsupported pixel layout.\n"); + break; } return (res); } @@ -113,21 +113,21 @@ nk_rawfb_int2color(const unsigned int i, rawfb_pl pl) switch (pl) { case PIXEL_LAYOUT_RGBX_8888: - col.r = (i >> 24) & 0xff; - col.g = (i >> 16) & 0xff; - col.b = (i >> 8) & 0xff; - col.a = i & 0xff; - break; + col.r = (i >> 24) & 0xff; + col.g = (i >> 16) & 0xff; + col.b = (i >> 8) & 0xff; + col.a = i & 0xff; + break; case PIXEL_LAYOUT_XRGB_8888: - col.a = (i >> 24) & 0xff; - col.r = (i >> 16) & 0xff; - col.g = (i >> 8) & 0xff; - col.b = i & 0xff; - break; + col.a = (i >> 24) & 0xff; + col.r = (i >> 16) & 0xff; + col.g = (i >> 8) & 0xff; + col.b = i & 0xff; + break; default: - perror("nk_rawfb_int2color(): Unsupported pixel layout.\n"); - break; + perror("nk_rawfb_int2color(): Unsupported pixel layout.\n"); + break; } return col; } @@ -184,12 +184,12 @@ nk_rawfb_img_setpixel(const struct rawfb_image *img, NK_ASSERT(img); if (y0 < img->h && y0 >= 0 && x0 >= 0 && x0 < img->w) { ptr = (unsigned char *)img->pixels + (img->pitch * y0); - pixel = (unsigned int *)ptr; + pixel = (unsigned int *)ptr; if (img->format == NK_FONT_ATLAS_ALPHA8) { ptr[x0] = col.a; } else { - pixel[x0] = c; + pixel[x0] = c; } } } @@ -208,8 +208,8 @@ nk_rawfb_img_getpixel(const struct rawfb_image *img, const int x0, const int y0) col.a = ptr[x0]; col.b = col.g = col.r = 0xff; } else { - pixel = ((unsigned int *)ptr)[x0]; - col = nk_rawfb_int2color(pixel, img->pl); + pixel = ((unsigned int *)ptr)[x0]; + col = nk_rawfb_int2color(pixel, img->pl); } } return col; } @@ -598,7 +598,7 @@ nk_rawfb_draw_rect_multi_color(const struct rawfb_context *rawfb, edge_buf = malloc(((2*w) + (2*h)) * sizeof(struct nk_color)); if (edge_buf == NULL) - return; + return; edge_t = edge_buf; edge_b = edge_buf + w; @@ -608,51 +608,51 @@ nk_rawfb_draw_rect_multi_color(const struct rawfb_context *rawfb, /* Top and bottom edge gradients */ for (i=0; ifb, x+j, y+i, edge_t[j]); - } else if (i==h-1) { - nk_rawfb_img_blendpixel(&rawfb->fb, x+j, y+i, edge_b[j]); - } else { - if (j==0) { - nk_rawfb_img_blendpixel(&rawfb->fb, x+j, y+i, edge_l[i]); - } else if (j==w-1) { - nk_rawfb_img_blendpixel(&rawfb->fb, x+j, y+i, edge_r[i]); - } else { - pixel.r = (((((float)edge_r[i].r - edge_l[i].r)/(w-1))*j) + 0.5) + edge_l[i].r; - pixel.g = (((((float)edge_r[i].g - edge_l[i].g)/(w-1))*j) + 0.5) + edge_l[i].g; - pixel.b = (((((float)edge_r[i].b - edge_l[i].b)/(w-1))*j) + 0.5) + edge_l[i].b; - pixel.a = (((((float)edge_r[i].a - edge_l[i].a)/(w-1))*j) + 0.5) + edge_l[i].a; - nk_rawfb_img_blendpixel(&rawfb->fb, x+j, y+i, pixel); - } - } - } + for (j=0; jfb, x+j, y+i, edge_t[j]); + } else if (i==h-1) { + nk_rawfb_img_blendpixel(&rawfb->fb, x+j, y+i, edge_b[j]); + } else { + if (j==0) { + nk_rawfb_img_blendpixel(&rawfb->fb, x+j, y+i, edge_l[i]); + } else if (j==w-1) { + nk_rawfb_img_blendpixel(&rawfb->fb, x+j, y+i, edge_r[i]); + } else { + pixel.r = (((((float)edge_r[i].r - edge_l[i].r)/(w-1))*j) + 0.5) + edge_l[i].r; + pixel.g = (((((float)edge_r[i].g - edge_l[i].g)/(w-1))*j) + 0.5) + edge_l[i].g; + pixel.b = (((((float)edge_r[i].b - edge_l[i].b)/(w-1))*j) + 0.5) + edge_l[i].b; + pixel.a = (((((float)edge_r[i].a - edge_l[i].a)/(w-1))*j) + 0.5) + edge_l[i].a; + nk_rawfb_img_blendpixel(&rawfb->fb, x+j, y+i, pixel); + } + } + } } free(edge_buf); @@ -837,31 +837,30 @@ nk_rawfb_init(void *fb, void *tex_mem, const unsigned int w, const unsigned int rawfb->font_tex.w = rawfb->font_tex.h = 0; rawfb->fb.pixels = fb; - rawfb->fb.w= w; + rawfb->fb.w = w; rawfb->fb.h = h; rawfb->fb.pl = pl; if (pl == PIXEL_LAYOUT_RGBX_8888 || pl == PIXEL_LAYOUT_XRGB_8888) { - rawfb->fb.format = NK_FONT_ATLAS_RGBA32; - rawfb->fb.pitch = pitch; - } - else { - perror("nk_rawfb_init(): Unsupported pixel layout.\n"); - free(rawfb); - return NULL; + rawfb->fb.format = NK_FONT_ATLAS_RGBA32; + rawfb->fb.pitch = pitch; + } else { + perror("nk_rawfb_init(): Unsupported pixel layout.\n"); + free(rawfb); + return NULL; } if (0 == nk_init_default(&rawfb->ctx, 0)) { - free(rawfb); - return NULL; + free(rawfb); + return NULL; } nk_font_atlas_init_default(&rawfb->atlas); nk_font_atlas_begin(&rawfb->atlas); tex = nk_font_atlas_bake(&rawfb->atlas, &rawfb->font_tex.w, &rawfb->font_tex.h, rawfb->font_tex.format); if (!tex) { - free(rawfb); - return NULL; + free(rawfb); + return NULL; } switch(rawfb->font_tex.format) { @@ -879,6 +878,7 @@ nk_rawfb_init(void *fb, void *tex_mem, const unsigned int w, const unsigned int nk_style_set_font(&rawfb->ctx, &rawfb->atlas.default_font->handle); nk_style_load_all_cursors(&rawfb->ctx, rawfb->atlas.cursors); nk_rawfb_scissor(rawfb, 0, 0, rawfb->fb.w, rawfb->fb.h); + return rawfb; } @@ -905,12 +905,12 @@ nk_rawfb_stretch_image(const struct rawfb_image *dst, continue; } col = nk_rawfb_img_getpixel(src, (int)xoff, (int) yoff); - if (col.r || col.g || col.b) - { - col.r = fg->r; - col.g = fg->g; - col.b = fg->b; - } + if (col.r || col.g || col.b) + { + col.r = fg->r; + col.g = fg->g; + col.b = fg->b; + } nk_rawfb_img_blendpixel(dst, i + (int)(dst_rect->x + 0.5f), j + (int)(dst_rect->y + 0.5f), col); xoff += xinc; } @@ -986,8 +986,8 @@ nk_rawfb_draw_text(const struct rawfb_context *rawfb, dst_rect.x = x + g.offset.x + rect.x; dst_rect.y = g.offset.y + rect.y; - dst_rect.w = ceilf(g.width); - dst_rect.h = ceilf(g.height); + dst_rect.w = ceil(g.width); + dst_rect.h = ceil(g.height); /* Use software rescaling to blit glyph from font_text to framebuffer */ nk_rawfb_stretch_image(&rawfb->fb, &rawfb->font_tex, &dst_rect, &src_rect, &rawfb->scissors, &fg); @@ -1024,9 +1024,9 @@ NK_API void nk_rawfb_shutdown(struct rawfb_context *rawfb) { if (rawfb) { - nk_free(&rawfb->ctx); - memset(rawfb, 0, sizeof(struct rawfb_context)); - free(rawfb); + nk_free(&rawfb->ctx); + memset(rawfb, 0, sizeof(struct rawfb_context)); + free(rawfb); } } @@ -1036,7 +1036,7 @@ nk_rawfb_resize_fb(struct rawfb_context *rawfb, const unsigned int w, const unsigned int h, const unsigned int pitch, - const rawfb_pl pl) + const rawfb_pl pl) { rawfb->fb.w = w; rawfb->fb.h = h; @@ -1117,9 +1117,9 @@ nk_rawfb_render(const struct rawfb_context *rawfb, q->end, 22, q->line_thickness, q->color); } break; case NK_COMMAND_RECT_MULTI_COLOR: { - const struct nk_command_rect_multi_color *q = (const struct nk_command_rect_multi_color *)cmd; - nk_rawfb_draw_rect_multi_color(rawfb, q->x, q->y, q->w, q->h, q->left, q->top, q->right, q->bottom); - } break; + const struct nk_command_rect_multi_color *q = (const struct nk_command_rect_multi_color *)cmd; + nk_rawfb_draw_rect_multi_color(rawfb, q->x, q->y, q->w, q->h, q->left, q->top, q->right, q->bottom); + } break; case NK_COMMAND_IMAGE: { const struct nk_command_image *q = (const struct nk_command_image *)cmd; nk_rawfb_drawimage(rawfb, q->x, q->y, q->w, q->h, &q->img, &q->col); diff --git a/demo/sdl2surface_rawfb/Makefile b/demo/rawfb/sdl/Makefile similarity index 87% rename from demo/sdl2surface_rawfb/Makefile rename to demo/rawfb/sdl/Makefile index 4fabb13..94dd4eb 100644 --- a/demo/sdl2surface_rawfb/Makefile +++ b/demo/rawfb/sdl/Makefile @@ -2,7 +2,7 @@ CFLAGS=`sdl2-config --cflags --libs` -std=c89 -Wall -Wextra -pedantic -Wno-unu .PHONY: clean -demo: main.c sdl2surface_rawfb.h +demo: main.c nuklear_sdl_rawfb.h $(CC) -o demo *.c $(CFLAGS) -lrt -lm clean: diff --git a/demo/sdl2surface_rawfb/main.c b/demo/rawfb/sdl/main.c similarity index 93% rename from demo/sdl2surface_rawfb/main.c rename to demo/rawfb/sdl/main.c index a8b661a..e7ba432 100644 --- a/demo/sdl2surface_rawfb/main.c +++ b/demo/rawfb/sdl/main.c @@ -18,9 +18,9 @@ #define NK_INCLUDE_FONT_BAKING #define NK_INCLUDE_DEFAULT_FONT #define NK_INCLUDE_SOFTWARE_FONT -#include "../../nuklear.h" -#define NK_SDLSURFACE_IMPLEMENTATION -#include "sdl2surface_rawfb.h" +#include "../../../nuklear.h" +#define NK_RAWFB_IMPLEMENTATION +#include "nuklear_sdl_rawfb.h" /* =============================================================== * @@ -45,19 +45,19 @@ #endif #ifdef INCLUDE_STYLE - #include "../../demo/common/style.c" + #include "../../common/style.c" #endif #ifdef INCLUDE_CALCULATOR - #include "../../demo/common/calculator.c" + #include "../../common/calculator.c" #endif #ifdef INCLUDE_CANVAS - #include "../../demo/common/canvas.c" + #include "../../common/canvas.c" #endif #ifdef INCLUDE_OVERVIEW - #include "../../demo/common/overview.c" + #include "../../common/overview.c" #endif #ifdef INCLUDE_NODE_EDITOR - #include "../../demo/common/node_editor.c" + #include "../../common/node_editor.c" #endif static int translate_sdl_key(struct SDL_Keysym const *k) @@ -131,7 +131,7 @@ int main(int argc, char **argv) struct nk_color clear = {0,100,0,255}; struct nk_vec2 vec; struct nk_rect bounds = {40,40,0,0}; - struct sdlsurface_context *context; + struct rawfb_context *context; SDL_DisplayMode dm; SDL_Window *window; @@ -165,7 +165,7 @@ int main(int argc, char **argv) surface = SDL_CreateRGBSurfaceWithFormat(0, dm.w-200, dm.h-200, 32, SDL_PIXELFORMAT_ARGB8888); - context = nk_sdlsurface_init(surface, 13.0f); + context = nk_rawfb_init(surface, 13.0f); while(1) @@ -240,7 +240,7 @@ int main(int argc, char **argv) #endif /* ----------------------------------------- */ - nk_sdlsurface_render(context, clear, 1); + nk_rawfb_render(context, clear, 1); @@ -252,7 +252,7 @@ int main(int argc, char **argv) } - nk_sdlsurface_shutdown(context); + nk_rawfb_shutdown(context); SDL_FreeSurface(surface); SDL_DestroyRenderer(renderer); diff --git a/demo/sdl2surface_rawfb/sdl2surface_rawfb.h b/demo/rawfb/sdl/nuklear_sdl_rawfb.h similarity index 61% rename from demo/sdl2surface_rawfb/sdl2surface_rawfb.h rename to demo/rawfb/sdl/nuklear_sdl_rawfb.h index 7b4b1cf..8dd9268 100644 --- a/demo/sdl2surface_rawfb/sdl2surface_rawfb.h +++ b/demo/rawfb/sdl/nuklear_sdl_rawfb.h @@ -30,15 +30,19 @@ */ /* Adapted from nulear_rawfb.h for use with SDL_Surface by Martijn Versteegh*/ -#ifndef NK_SDLSURFACE_H_ -#define NK_SDLSURFACE_H_ + +#ifndef NK_RAWFB_H_ +#define NK_RAWFB_H_ #include #include -struct sdlsurface_context *nk_sdlsurface_init(SDL_Surface *fb, float fontSize); -void nk_sdlsurface_render(const struct sdlsurface_context *sdlsurface, const struct nk_color clear, const unsigned char enable_clear); -void nk_sdlsurface_shutdown(struct sdlsurface_context *sdlsurface); +struct rawfb_context; + +/* All functions are thread-safe */ +NK_API struct rawfb_context *nk_rawfb_init(SDL_Surface *fb, float fontSize); +NK_API void nk_rawfb_render(const struct rawfb_context *rawfb, const struct nk_color clear, const unsigned char enable_clear); +NK_API void nk_rawfb_shutdown(struct rawfb_context *rawfb); #endif /* @@ -48,16 +52,20 @@ void nk_sdlsurface_shutdown(struct sdlsurface_context *sdlsurfa * * =============================================================== */ -#ifdef NK_SDLSURFACE_IMPLEMENTATION +#ifdef NK_RAWFB_IMPLEMENTATION #include #include #include -struct sdlsurface_context { +struct rawfb_image { + SDL_Surface *surf; + int w, h; +}; +struct rawfb_context { struct nk_context ctx; struct nk_rect scissors; - struct SDL_Surface *fb; - struct SDL_Surface *font_tex; + struct rawfb_image fb; + struct rawfb_image font_tex; struct nk_font_atlas atlas; }; @@ -69,13 +77,13 @@ struct sdlsurface_context { #endif static unsigned int -nk_sdlsurface_color2int(const struct nk_color c, const SDL_PixelFormat *format) +nk_rawfb_color2int(const struct nk_color c, const SDL_PixelFormat *format) { return SDL_MapRGBA(format, c.r, c.g, c.b, c.a); } static struct nk_color -nk_sdlsurface_int2color(const unsigned int i, const SDL_PixelFormat *format) +nk_rawfb_int2color(const unsigned int i, const SDL_PixelFormat *format) { struct nk_color col = {0,0,0,0}; @@ -85,20 +93,20 @@ nk_sdlsurface_int2color(const unsigned int i, const SDL_PixelFormat *format) } static void -nk_sdlsurface_ctx_setpixel(const struct sdlsurface_context *sdlsurface, +nk_rawfb_ctx_setpixel(const struct rawfb_context *rawfb, const short x0, const short y0, const struct nk_color col) { - unsigned int c = nk_sdlsurface_color2int(col, sdlsurface->fb->format); - unsigned char *pixels = sdlsurface->fb->pixels; + unsigned int c = nk_rawfb_color2int(col, rawfb->fb.surf->format); + unsigned char *pixels = rawfb->fb.surf->pixels; - pixels += y0 * sdlsurface->fb->pitch; + pixels += y0 * rawfb->fb.surf->pitch; - if (y0 < sdlsurface->scissors.h && y0 >= sdlsurface->scissors.y && - x0 >= sdlsurface->scissors.x && x0 < sdlsurface->scissors.w) { + if (y0 < rawfb->scissors.h && y0 >= rawfb->scissors.y && + x0 >= rawfb->scissors.x && x0 < rawfb->scissors.w) { - if (sdlsurface->fb->format->BytesPerPixel == 4) { + if (rawfb->fb.surf->format->BytesPerPixel == 4) { *((Uint32 *)pixels + x0) = c; - } else if (sdlsurface->fb->format->BytesPerPixel == 2) { + } else if (rawfb->fb.surf->format->BytesPerPixel == 2) { *((Uint16 *)pixels + x0) = c; } else { *((Uint8 *)pixels + x0) = c; @@ -107,7 +115,7 @@ nk_sdlsurface_ctx_setpixel(const struct sdlsurface_context *sdlsurface, } static void -nk_sdlsurface_line_horizontal(const struct sdlsurface_context *sdlsurface, +nk_rawfb_line_horizontal(const struct rawfb_context *rawfb, const short x0, const short y, const short x1, const struct nk_color col) { /* This function is called the most. Try to optimize it a bit... @@ -115,21 +123,21 @@ nk_sdlsurface_line_horizontal(const struct sdlsurface_context *sdlsurface, * The caller has to make sure it does no exceed bounds. */ unsigned int i, n; unsigned char c[16 * 4]; - unsigned char *pixels = sdlsurface->fb->pixels; - unsigned int bpp = sdlsurface->fb->format->BytesPerPixel; + unsigned char *pixels = rawfb->fb.surf->pixels; + unsigned int bpp = rawfb->fb.surf->format->BytesPerPixel; - pixels += (y * sdlsurface->fb->pitch) + (x0 * bpp); + pixels += (y * rawfb->fb.surf->pitch) + (x0 * bpp); n = (x1 - x0) * bpp; if (bpp == 4) { for (i = 0; i < sizeof(c) / bpp; i++) - ((Uint32 *)c)[i] = nk_sdlsurface_color2int(col, sdlsurface->fb->format); + ((Uint32 *)c)[i] = nk_rawfb_color2int(col, rawfb->fb.surf->format); } else if (bpp == 2) { for (i = 0; i < sizeof(c) / bpp; i++) - ((Uint16 *)c)[i] = nk_sdlsurface_color2int(col, sdlsurface->fb->format); + ((Uint16 *)c)[i] = nk_rawfb_color2int(col, rawfb->fb.surf->format); } else { for (i = 0; i < sizeof(c) / bpp; i++) - ((Uint8 *)c)[i] = nk_sdlsurface_color2int(col, sdlsurface->fb->format); + ((Uint8 *)c)[i] = nk_rawfb_color2int(col, rawfb->fb.surf->format); } while (n > sizeof(c)) { @@ -140,20 +148,20 @@ nk_sdlsurface_line_horizontal(const struct sdlsurface_context *sdlsurface, } static void -nk_sdlsurface_img_setpixel(const struct SDL_Surface *img, +nk_rawfb_img_setpixel(const struct rawfb_image *img, const int x0, const int y0, const struct nk_color col) { - unsigned int c = nk_sdlsurface_color2int(col, img->format); + unsigned int c = nk_rawfb_color2int(col, img->surf->format); unsigned char *ptr; NK_ASSERT(img); if (y0 < img->h && y0 >= 0 && x0 >= 0 && x0 < img->w) { - ptr = (unsigned char *)img->pixels + (img->pitch * y0); + ptr = (unsigned char *)img->surf->pixels + (img->surf->pitch * y0); - if (img->format == NK_FONT_ATLAS_ALPHA8) { + if (img->surf->format == NK_FONT_ATLAS_ALPHA8) { ptr[x0] = col.a; - } else if (img->format->BytesPerPixel == 4) { + } else if (img->surf->format->BytesPerPixel == 4) { ((Uint32 *)ptr)[x0] = c; - } else if (img->format->BytesPerPixel == 2) { + } else if (img->surf->format->BytesPerPixel == 2) { ((Uint16 *)ptr)[x0] = c; } else { ((Uint8 *)ptr)[x0] = c; @@ -162,32 +170,32 @@ nk_sdlsurface_img_setpixel(const struct SDL_Surface *img, } static struct nk_color -nk_sdlsurface_img_getpixel(const struct SDL_Surface *img, const int x0, const int y0) +nk_rawfb_img_getpixel(const struct rawfb_image *img, const int x0, const int y0) { struct nk_color col = {0, 0, 0, 0}; unsigned char *ptr; unsigned int pixel; NK_ASSERT(img); if (y0 < img->h && y0 >= 0 && x0 >= 0 && x0 < img->w) { - ptr = (unsigned char *)img->pixels + (img->pitch * y0); + ptr = (unsigned char *)img->surf->pixels + (img->surf->pitch * y0); - if (img->format == NK_FONT_ATLAS_ALPHA8) { + if (img->surf->format == NK_FONT_ATLAS_ALPHA8) { col.a = ptr[x0]; col.b = col.g = col.r = 0xff; - } else if (img->format->BytesPerPixel == 4) { + } else if (img->surf->format->BytesPerPixel == 4) { pixel = ((Uint32 *)ptr)[x0]; - col = nk_sdlsurface_int2color(pixel, img->format); - } else if (img->format->BytesPerPixel == 2) { + col = nk_rawfb_int2color(pixel, img->surf->format); + } else if (img->surf->format->BytesPerPixel == 2) { pixel = ((Uint16 *)ptr)[x0]; - col = nk_sdlsurface_int2color(pixel, img->format); + col = nk_rawfb_int2color(pixel, img->surf->format); } else { pixel = ((Uint8 *)ptr)[x0]; - col = nk_sdlsurface_int2color(pixel, img->format); + col = nk_rawfb_int2color(pixel, img->surf->format); } } return col; } static void -nk_sdlsurface_img_blendpixel(const struct SDL_Surface *img, +nk_rawfb_img_blendpixel(const struct rawfb_image *img, const int x0, const int y0, struct nk_color col) { struct nk_color col2; @@ -196,28 +204,28 @@ nk_sdlsurface_img_blendpixel(const struct SDL_Surface *img, return; inv_a = 0xff - col.a; - col2 = nk_sdlsurface_img_getpixel(img, x0, y0); + col2 = nk_rawfb_img_getpixel(img, x0, y0); col.r = (col.r * col.a + col2.r * inv_a) >> 8; col.g = (col.g * col.a + col2.g * inv_a) >> 8; col.b = (col.b * col.a + col2.b * inv_a) >> 8; - nk_sdlsurface_img_setpixel(img, x0, y0, col); + nk_rawfb_img_setpixel(img, x0, y0, col); } static void -nk_sdlsurface_scissor(struct sdlsurface_context *sdlsurface, +nk_rawfb_scissor(struct rawfb_context *rawfb, const float x, const float y, const float w, const float h) { - sdlsurface->scissors.x = MIN(MAX(x, 0), sdlsurface->fb->w); - sdlsurface->scissors.y = MIN(MAX(y, 0), sdlsurface->fb->h); - sdlsurface->scissors.w = MIN(MAX(w + x, 0), sdlsurface->fb->w); - sdlsurface->scissors.h = MIN(MAX(h + y, 0), sdlsurface->fb->h); + rawfb->scissors.x = MIN(MAX(x, 0), rawfb->fb.w); + rawfb->scissors.y = MIN(MAX(y, 0), rawfb->fb.h); + rawfb->scissors.w = MIN(MAX(w + x, 0), rawfb->fb.w); + rawfb->scissors.h = MIN(MAX(h + y, 0), rawfb->fb.h); } static void -nk_sdlsurface_stroke_line(const struct sdlsurface_context *sdlsurface, +nk_rawfb_stroke_line(const struct rawfb_context *rawfb, short x0, short y0, short x1, short y1, const unsigned int line_thickness, const struct nk_color col) { @@ -231,7 +239,7 @@ nk_sdlsurface_stroke_line(const struct sdlsurface_context *sdlsurface, /* fast path */ if (dy == 0) { - if (dx == 0 || y0 >= sdlsurface->scissors.h || y0 < sdlsurface->scissors.y) + if (dx == 0 || y0 >= rawfb->scissors.h || y0 < rawfb->scissors.y) return; if (dx < 0) { @@ -240,11 +248,11 @@ nk_sdlsurface_stroke_line(const struct sdlsurface_context *sdlsurface, x1 = x0; x0 = tmp; } - x1 = MIN(sdlsurface->scissors.w, x1); - x0 = MIN(sdlsurface->scissors.w, x0); - x1 = MAX(sdlsurface->scissors.x, x1); - x0 = MAX(sdlsurface->scissors.x, x0); - nk_sdlsurface_line_horizontal(sdlsurface, x0, y0, x1, col); + x1 = MIN(rawfb->scissors.w, x1); + x0 = MIN(rawfb->scissors.w, x0); + x1 = MAX(rawfb->scissors.x, x1); + x0 = MAX(rawfb->scissors.x, x0); + nk_rawfb_line_horizontal(rawfb, x0, y0, x1, col); return; } if (dy < 0) { @@ -260,7 +268,7 @@ nk_sdlsurface_stroke_line(const struct sdlsurface_context *sdlsurface, dy <<= 1; dx <<= 1; - nk_sdlsurface_ctx_setpixel(sdlsurface, x0, y0, col); + nk_rawfb_ctx_setpixel(rawfb, x0, y0, col); if (dx > dy) { int fraction = dy - (dx >> 1); while (x0 != x1) { @@ -270,7 +278,7 @@ nk_sdlsurface_stroke_line(const struct sdlsurface_context *sdlsurface, } x0 += stepx; fraction += dy; - nk_sdlsurface_ctx_setpixel(sdlsurface, x0, y0, col); + nk_rawfb_ctx_setpixel(rawfb, x0, y0, col); } } else { int fraction = dx - (dy >> 1); @@ -281,13 +289,13 @@ nk_sdlsurface_stroke_line(const struct sdlsurface_context *sdlsurface, } y0 += stepy; fraction += dx; - nk_sdlsurface_ctx_setpixel(sdlsurface, x0, y0, col); + nk_rawfb_ctx_setpixel(rawfb, x0, y0, col); } } } static void -nk_sdlsurface_fill_polygon(const struct sdlsurface_context *sdlsurface, +nk_rawfb_fill_polygon(const struct rawfb_context *rawfb, const struct nk_vec2i *pnts, int count, const struct nk_color col) { int i = 0; @@ -342,7 +350,7 @@ nk_sdlsurface_fill_polygon(const struct sdlsurface_context *sdlsurface, if (nodeX[i+0] < left) nodeX[i+0] = left ; if (nodeX[i+1] > right) nodeX[i+1] = right; for (pixelX = nodeX[i]; pixelX < nodeX[i + 1]; pixelX++) - nk_sdlsurface_ctx_setpixel(sdlsurface, pixelX, pixelY, col); + nk_rawfb_ctx_setpixel(rawfb, pixelX, pixelY, col); } } } @@ -350,7 +358,7 @@ nk_sdlsurface_fill_polygon(const struct sdlsurface_context *sdlsurface, } static void -nk_sdlsurface_stroke_arc(const struct sdlsurface_context *sdlsurface, +nk_rawfb_stroke_arc(const struct rawfb_context *rawfb, short x0, short y0, short w, short h, const short s, const short line_thickness, const struct nk_color col) { @@ -373,13 +381,13 @@ nk_sdlsurface_stroke_arc(const struct sdlsurface_context *sdlsurface, /* First half */ for (x = 0, y = h, sigma = 2*b2+a2*(1-2*h); b2*x <= a2*y; x++) { if (s == 180) - nk_sdlsurface_ctx_setpixel(sdlsurface, x0 + x, y0 + y, col); + nk_rawfb_ctx_setpixel(rawfb, x0 + x, y0 + y, col); else if (s == 270) - nk_sdlsurface_ctx_setpixel(sdlsurface, x0 - x, y0 + y, col); + nk_rawfb_ctx_setpixel(rawfb, x0 - x, y0 + y, col); else if (s == 0) - nk_sdlsurface_ctx_setpixel(sdlsurface, x0 + x, y0 - y, col); + nk_rawfb_ctx_setpixel(rawfb, x0 + x, y0 - y, col); else if (s == 90) - nk_sdlsurface_ctx_setpixel(sdlsurface, x0 - x, y0 - y, col); + nk_rawfb_ctx_setpixel(rawfb, x0 - x, y0 - y, col); if (sigma >= 0) { sigma += fa2 * (1 - y); y--; @@ -389,13 +397,13 @@ nk_sdlsurface_stroke_arc(const struct sdlsurface_context *sdlsurface, /* Second half */ for (x = w, y = 0, sigma = 2*a2+b2*(1-2*w); a2*y <= b2*x; y++) { if (s == 180) - nk_sdlsurface_ctx_setpixel(sdlsurface, x0 + x, y0 + y, col); + nk_rawfb_ctx_setpixel(rawfb, x0 + x, y0 + y, col); else if (s == 270) - nk_sdlsurface_ctx_setpixel(sdlsurface, x0 - x, y0 + y, col); + nk_rawfb_ctx_setpixel(rawfb, x0 - x, y0 + y, col); else if (s == 0) - nk_sdlsurface_ctx_setpixel(sdlsurface, x0 + x, y0 - y, col); + nk_rawfb_ctx_setpixel(rawfb, x0 + x, y0 - y, col); else if (s == 90) - nk_sdlsurface_ctx_setpixel(sdlsurface, x0 - x, y0 - y, col); + nk_rawfb_ctx_setpixel(rawfb, x0 - x, y0 - y, col); if (sigma >= 0) { sigma += fb2 * (1 - x); x--; @@ -404,7 +412,7 @@ nk_sdlsurface_stroke_arc(const struct sdlsurface_context *sdlsurface, } static void -nk_sdlsurface_fill_arc(const struct sdlsurface_context *sdlsurface, short x0, short y0, +nk_rawfb_fill_arc(const struct rawfb_context *rawfb, short x0, short y0, short w, short h, const short s, const struct nk_color col) { /* Bresenham's ellipses - modified to fill one quarter */ @@ -439,7 +447,7 @@ nk_sdlsurface_fill_arc(const struct sdlsurface_context *sdlsurface, short x0, sh } else if (s == 90) { pnts[1].x = x0 - x; pnts[1].y = y0 - y; } - nk_sdlsurface_fill_polygon(sdlsurface, pnts, 3, col); + nk_rawfb_fill_polygon(rawfb, pnts, 3, col); pnts[2] = pnts[1]; if (sigma >= 0) { sigma += fa2 * (1 - y); @@ -458,7 +466,7 @@ nk_sdlsurface_fill_arc(const struct sdlsurface_context *sdlsurface, short x0, sh } else if (s == 90) { pnts[1].x = x0 - x; pnts[1].y = y0 - y; } - nk_sdlsurface_fill_polygon(sdlsurface, pnts, 3, col); + nk_rawfb_fill_polygon(rawfb, pnts, 3, col); pnts[2] = pnts[1]; if (sigma >= 0) { sigma += fb2 * (1 - x); @@ -468,46 +476,46 @@ nk_sdlsurface_fill_arc(const struct sdlsurface_context *sdlsurface, short x0, sh } static void -nk_sdlsurface_stroke_rect(const struct sdlsurface_context *sdlsurface, +nk_rawfb_stroke_rect(const struct rawfb_context *rawfb, const short x, const short y, const short w, const short h, const short r, const short line_thickness, const struct nk_color col) { if (r == 0) { - nk_sdlsurface_stroke_line(sdlsurface, x, y, x + w, y, line_thickness, col); - nk_sdlsurface_stroke_line(sdlsurface, x, y + h, x + w, y + h, line_thickness, col); - nk_sdlsurface_stroke_line(sdlsurface, x, y, x, y + h, line_thickness, col); - nk_sdlsurface_stroke_line(sdlsurface, x + w, y, x + w, y + h, line_thickness, col); + nk_rawfb_stroke_line(rawfb, x, y, x + w, y, line_thickness, col); + nk_rawfb_stroke_line(rawfb, x, y + h, x + w, y + h, line_thickness, col); + nk_rawfb_stroke_line(rawfb, x, y, x, y + h, line_thickness, col); + nk_rawfb_stroke_line(rawfb, x + w, y, x + w, y + h, line_thickness, col); } else { const short xc = x + r; const short yc = y + r; const short wc = (short)(w - 2 * r); const short hc = (short)(h - 2 * r); - nk_sdlsurface_stroke_line(sdlsurface, xc, y, xc + wc, y, line_thickness, col); - nk_sdlsurface_stroke_line(sdlsurface, x + w, yc, x + w, yc + hc, line_thickness, col); - nk_sdlsurface_stroke_line(sdlsurface, xc, y + h, xc + wc, y + h, line_thickness, col); - nk_sdlsurface_stroke_line(sdlsurface, x, yc, x, yc + hc, line_thickness, col); + nk_rawfb_stroke_line(rawfb, xc, y, xc + wc, y, line_thickness, col); + nk_rawfb_stroke_line(rawfb, x + w, yc, x + w, yc + hc, line_thickness, col); + nk_rawfb_stroke_line(rawfb, xc, y + h, xc + wc, y + h, line_thickness, col); + nk_rawfb_stroke_line(rawfb, x, yc, x, yc + hc, line_thickness, col); - nk_sdlsurface_stroke_arc(sdlsurface, xc + wc - r, y, + nk_rawfb_stroke_arc(rawfb, xc + wc - r, y, (unsigned)r*2, (unsigned)r*2, 0 , line_thickness, col); - nk_sdlsurface_stroke_arc(sdlsurface, x, y, + nk_rawfb_stroke_arc(rawfb, x, y, (unsigned)r*2, (unsigned)r*2, 90 , line_thickness, col); - nk_sdlsurface_stroke_arc(sdlsurface, x, yc + hc - r, + nk_rawfb_stroke_arc(rawfb, x, yc + hc - r, (unsigned)r*2, (unsigned)r*2, 270 , line_thickness, col); - nk_sdlsurface_stroke_arc(sdlsurface, xc + wc - r, yc + hc - r, + nk_rawfb_stroke_arc(rawfb, xc + wc - r, yc + hc - r, (unsigned)r*2, (unsigned)r*2, 180 , line_thickness, col); } } static void -nk_sdlsurface_fill_rect(const struct sdlsurface_context *sdlsurface, +nk_rawfb_fill_rect(const struct rawfb_context *rawfb, const short x, const short y, const short w, const short h, const short r, const struct nk_color col) { int i; if (r == 0) { for (i = 0; i < h; i++) - nk_sdlsurface_stroke_line(sdlsurface, x, y + i, x + w, y + i, 1, col); + nk_rawfb_stroke_line(rawfb, x, y + i, x + w, y + i, 1, col); } else { const short xc = x + r; const short yc = y + r; @@ -543,21 +551,21 @@ nk_sdlsurface_fill_rect(const struct sdlsurface_context *sdlsurface, pnts[11].x = x; pnts[11].y = yc + hc; - nk_sdlsurface_fill_polygon(sdlsurface, pnts, 12, col); + nk_rawfb_fill_polygon(rawfb, pnts, 12, col); - nk_sdlsurface_fill_arc(sdlsurface, xc + wc - r, y, + nk_rawfb_fill_arc(rawfb, xc + wc - r, y, (unsigned)r*2, (unsigned)r*2, 0 , col); - nk_sdlsurface_fill_arc(sdlsurface, x, y, + nk_rawfb_fill_arc(rawfb, x, y, (unsigned)r*2, (unsigned)r*2, 90 , col); - nk_sdlsurface_fill_arc(sdlsurface, x, yc + hc - r, + nk_rawfb_fill_arc(rawfb, x, yc + hc - r, (unsigned)r*2, (unsigned)r*2, 270 , col); - nk_sdlsurface_fill_arc(sdlsurface, xc + wc - r, yc + hc - r, + nk_rawfb_fill_arc(rawfb, xc + wc - r, yc + hc - r, (unsigned)r*2, (unsigned)r*2, 180 , col); } } NK_API void -nk_sdlsurface_draw_rect_multi_color(const struct sdlsurface_context *sdlsurface, +nk_rawfb_draw_rect_multi_color(const struct rawfb_context *rawfb, const short x, const short y, const short w, const short h, struct nk_color tl, struct nk_color tr, struct nk_color br, struct nk_color bl) { @@ -571,7 +579,7 @@ nk_sdlsurface_draw_rect_multi_color(const struct sdlsurface_context *sdlsurface, edge_buf = malloc(((2*w) + (2*h)) * sizeof(struct nk_color)); if (edge_buf == NULL) - return; + return; edge_t = edge_buf; edge_b = edge_buf + w; @@ -581,58 +589,58 @@ nk_sdlsurface_draw_rect_multi_color(const struct sdlsurface_context *sdlsurface, /* Top and bottom edge gradients */ for (i=0; ifb, x+j, y+i, edge_t[j]); - } else if (i==h-1) { - nk_sdlsurface_img_blendpixel(sdlsurface->fb, x+j, y+i, edge_b[j]); - } else { - if (j==0) { - nk_sdlsurface_img_blendpixel(sdlsurface->fb, x+j, y+i, edge_l[i]); - } else if (j==w-1) { - nk_sdlsurface_img_blendpixel(sdlsurface->fb, x+j, y+i, edge_r[i]); - } else { - pixel.r = (((((float)edge_r[i].r - edge_l[i].r)/(w-1))*j) + 0.5) + edge_l[i].r; - pixel.g = (((((float)edge_r[i].g - edge_l[i].g)/(w-1))*j) + 0.5) + edge_l[i].g; - pixel.b = (((((float)edge_r[i].b - edge_l[i].b)/(w-1))*j) + 0.5) + edge_l[i].b; - pixel.a = (((((float)edge_r[i].a - edge_l[i].a)/(w-1))*j) + 0.5) + edge_l[i].a; - nk_sdlsurface_img_blendpixel(sdlsurface->fb, x+j, y+i, pixel); + for (j=0; jfb, x+j, y+i, edge_t[j]); + } else if (i==h-1) { + nk_rawfb_img_blendpixel(&rawfb->fb, x+j, y+i, edge_b[j]); + } else { + if (j==0) { + nk_rawfb_img_blendpixel(&rawfb->fb, x+j, y+i, edge_l[i]); + } else if (j==w-1) { + nk_rawfb_img_blendpixel(&rawfb->fb, x+j, y+i, edge_r[i]); + } else { + pixel.r = (((((float)edge_r[i].r - edge_l[i].r)/(w-1))*j) + 0.5) + edge_l[i].r; + pixel.g = (((((float)edge_r[i].g - edge_l[i].g)/(w-1))*j) + 0.5) + edge_l[i].g; + pixel.b = (((((float)edge_r[i].b - edge_l[i].b)/(w-1))*j) + 0.5) + edge_l[i].b; + pixel.a = (((((float)edge_r[i].a - edge_l[i].a)/(w-1))*j) + 0.5) + edge_l[i].a; + nk_rawfb_img_blendpixel(&rawfb->fb, x+j, y+i, pixel); + } + } } - } - } } free(edge_buf); } static void -nk_sdlsurface_fill_triangle(const struct sdlsurface_context *sdlsurface, +nk_rawfb_fill_triangle(const struct rawfb_context *rawfb, const short x0, const short y0, const short x1, const short y1, const short x2, const short y2, const struct nk_color col) { @@ -643,46 +651,46 @@ nk_sdlsurface_fill_triangle(const struct sdlsurface_context *sdlsurface, pnts[1].y = y1; pnts[2].x = x2; pnts[2].y = y2; - nk_sdlsurface_fill_polygon(sdlsurface, pnts, 3, col); + nk_rawfb_fill_polygon(rawfb, pnts, 3, col); } static void -nk_sdlsurface_stroke_triangle(const struct sdlsurface_context *sdlsurface, +nk_rawfb_stroke_triangle(const struct rawfb_context *rawfb, const short x0, const short y0, const short x1, const short y1, const short x2, const short y2, const unsigned short line_thickness, const struct nk_color col) { - nk_sdlsurface_stroke_line(sdlsurface, x0, y0, x1, y1, line_thickness, col); - nk_sdlsurface_stroke_line(sdlsurface, x1, y1, x2, y2, line_thickness, col); - nk_sdlsurface_stroke_line(sdlsurface, x2, y2, x0, y0, line_thickness, col); + nk_rawfb_stroke_line(rawfb, x0, y0, x1, y1, line_thickness, col); + nk_rawfb_stroke_line(rawfb, x1, y1, x2, y2, line_thickness, col); + nk_rawfb_stroke_line(rawfb, x2, y2, x0, y0, line_thickness, col); } static void -nk_sdlsurface_stroke_polygon(const struct sdlsurface_context *sdlsurface, +nk_rawfb_stroke_polygon(const struct rawfb_context *rawfb, const struct nk_vec2i *pnts, const int count, const unsigned short line_thickness, const struct nk_color col) { int i; for (i = 1; i < count; ++i) - nk_sdlsurface_stroke_line(sdlsurface, pnts[i-1].x, pnts[i-1].y, pnts[i].x, + nk_rawfb_stroke_line(rawfb, pnts[i-1].x, pnts[i-1].y, pnts[i].x, pnts[i].y, line_thickness, col); - nk_sdlsurface_stroke_line(sdlsurface, pnts[count-1].x, pnts[count-1].y, + nk_rawfb_stroke_line(rawfb, pnts[count-1].x, pnts[count-1].y, pnts[0].x, pnts[0].y, line_thickness, col); } static void -nk_sdlsurface_stroke_polyline(const struct sdlsurface_context *sdlsurface, +nk_rawfb_stroke_polyline(const struct rawfb_context *rawfb, const struct nk_vec2i *pnts, const int count, const unsigned short line_thickness, const struct nk_color col) { int i; for (i = 0; i < count-1; ++i) - nk_sdlsurface_stroke_line(sdlsurface, pnts[i].x, pnts[i].y, + nk_rawfb_stroke_line(rawfb, pnts[i].x, pnts[i].y, pnts[i+1].x, pnts[i+1].y, line_thickness, col); } static void -nk_sdlsurface_fill_circle(const struct sdlsurface_context *sdlsurface, +nk_rawfb_fill_circle(const struct rawfb_context *rawfb, short x0, short y0, short w, short h, const struct nk_color col) { /* Bresenham's ellipses */ @@ -699,8 +707,8 @@ nk_sdlsurface_fill_circle(const struct sdlsurface_context *sdlsurface, /* First half */ for (x = 0, y = h, sigma = 2*b2+a2*(1-2*h); b2*x <= a2*y; x++) { - nk_sdlsurface_stroke_line(sdlsurface, x0 - x, y0 + y, x0 + x, y0 + y, 1, col); - nk_sdlsurface_stroke_line(sdlsurface, x0 - x, y0 - y, x0 + x, y0 - y, 1, col); + nk_rawfb_stroke_line(rawfb, x0 - x, y0 + y, x0 + x, y0 + y, 1, col); + nk_rawfb_stroke_line(rawfb, x0 - x, y0 - y, x0 + x, y0 - y, 1, col); if (sigma >= 0) { sigma += fa2 * (1 - y); y--; @@ -708,8 +716,8 @@ nk_sdlsurface_fill_circle(const struct sdlsurface_context *sdlsurface, } /* Second half */ for (x = w, y = 0, sigma = 2*a2+b2*(1-2*w); a2*y <= b2*x; y++) { - nk_sdlsurface_stroke_line(sdlsurface, x0 - x, y0 + y, x0 + x, y0 + y, 1, col); - nk_sdlsurface_stroke_line(sdlsurface, x0 - x, y0 - y, x0 + x, y0 - y, 1, col); + nk_rawfb_stroke_line(rawfb, x0 - x, y0 + y, x0 + x, y0 + y, 1, col); + nk_rawfb_stroke_line(rawfb, x0 - x, y0 - y, x0 + x, y0 - y, 1, col); if (sigma >= 0) { sigma += fb2 * (1 - x); x--; @@ -718,7 +726,7 @@ nk_sdlsurface_fill_circle(const struct sdlsurface_context *sdlsurface, } static void -nk_sdlsurface_stroke_circle(const struct sdlsurface_context *sdlsurface, +nk_rawfb_stroke_circle(const struct rawfb_context *rawfb, short x0, short y0, short w, short h, const short line_thickness, const struct nk_color col) { @@ -738,10 +746,10 @@ nk_sdlsurface_stroke_circle(const struct sdlsurface_context *sdlsurface, /* First half */ for (x = 0, y = h, sigma = 2*b2+a2*(1-2*h); b2*x <= a2*y; x++) { - nk_sdlsurface_ctx_setpixel(sdlsurface, x0 + x, y0 + y, col); - nk_sdlsurface_ctx_setpixel(sdlsurface, x0 - x, y0 + y, col); - nk_sdlsurface_ctx_setpixel(sdlsurface, x0 + x, y0 - y, col); - nk_sdlsurface_ctx_setpixel(sdlsurface, x0 - x, y0 - y, col); + nk_rawfb_ctx_setpixel(rawfb, x0 + x, y0 + y, col); + nk_rawfb_ctx_setpixel(rawfb, x0 - x, y0 + y, col); + nk_rawfb_ctx_setpixel(rawfb, x0 + x, y0 - y, col); + nk_rawfb_ctx_setpixel(rawfb, x0 - x, y0 - y, col); if (sigma >= 0) { sigma += fa2 * (1 - y); y--; @@ -749,10 +757,10 @@ nk_sdlsurface_stroke_circle(const struct sdlsurface_context *sdlsurface, } /* Second half */ for (x = w, y = 0, sigma = 2*a2+b2*(1-2*w); a2*y <= b2*x; y++) { - nk_sdlsurface_ctx_setpixel(sdlsurface, x0 + x, y0 + y, col); - nk_sdlsurface_ctx_setpixel(sdlsurface, x0 - x, y0 + y, col); - nk_sdlsurface_ctx_setpixel(sdlsurface, x0 + x, y0 - y, col); - nk_sdlsurface_ctx_setpixel(sdlsurface, x0 - x, y0 - y, col); + nk_rawfb_ctx_setpixel(rawfb, x0 + x, y0 + y, col); + nk_rawfb_ctx_setpixel(rawfb, x0 - x, y0 + y, col); + nk_rawfb_ctx_setpixel(rawfb, x0 + x, y0 - y, col); + nk_rawfb_ctx_setpixel(rawfb, x0 - x, y0 - y, col); if (sigma >= 0) { sigma += fb2 * (1 - x); x--; @@ -761,7 +769,7 @@ nk_sdlsurface_stroke_circle(const struct sdlsurface_context *sdlsurface, } static void -nk_sdlsurface_stroke_curve(const struct sdlsurface_context *sdlsurface, +nk_rawfb_stroke_curve(const struct rawfb_context *rawfb, const struct nk_vec2i p1, const struct nk_vec2i p2, const struct nk_vec2i p3, const struct nk_vec2i p4, const unsigned int num_segments, const unsigned short line_thickness, @@ -782,66 +790,66 @@ nk_sdlsurface_stroke_curve(const struct sdlsurface_context *sdlsurface, float w4 = t * t *t; float x = w1 * p1.x + w2 * p2.x + w3 * p3.x + w4 * p4.x; float y = w1 * p1.y + w2 * p2.y + w3 * p3.y + w4 * p4.y; - nk_sdlsurface_stroke_line(sdlsurface, last.x, last.y, + nk_rawfb_stroke_line(rawfb, last.x, last.y, (short)x, (short)y, line_thickness,col); last.x = (short)x; last.y = (short)y; } } static void -nk_sdlsurface_clear(const struct sdlsurface_context *sdlsurface, const struct nk_color col) +nk_rawfb_clear(const struct rawfb_context *rawfb, const struct nk_color col) { - nk_sdlsurface_fill_rect(sdlsurface, 0, 0, sdlsurface->fb->w, sdlsurface->fb->h, 0, col); + nk_rawfb_fill_rect(rawfb, 0, 0, rawfb->fb.w, rawfb->fb.h, 0, col); } -struct sdlsurface_context* -nk_sdlsurface_init(SDL_Surface *fb, float fontSize) +NK_API struct rawfb_context* +nk_rawfb_init(SDL_Surface *fb, float fontSize) { const void *tex; - int texh, texw; - struct sdlsurface_context *sdlsurface; + struct rawfb_context *rawfb; assert((fb->format->format == SDL_PIXELFORMAT_ARGB8888) || (fb->format->format == SDL_PIXELFORMAT_RGBA8888)); - sdlsurface = malloc(sizeof(struct sdlsurface_context)); - if (!sdlsurface) + rawfb = malloc(sizeof(struct rawfb_context)); + if (!rawfb) return NULL; - memset(sdlsurface, 0, sizeof(struct sdlsurface_context)); + memset(rawfb, 0, sizeof(struct rawfb_context)); - sdlsurface->fb = fb; + rawfb->fb.surf = fb; + rawfb->fb.w = fb->w; + rawfb->fb.h = fb->h; - if (0 == nk_init_default(&sdlsurface->ctx, 0)) { - free(sdlsurface); - return NULL; + if (0 == nk_init_default(&rawfb->ctx, 0)) { + free(rawfb); + return NULL; } - nk_font_atlas_init_default(&sdlsurface->atlas); - nk_font_atlas_begin(&sdlsurface->atlas); - sdlsurface->atlas.default_font = nk_font_atlas_add_default(&sdlsurface->atlas, fontSize, 0); - tex = nk_font_atlas_bake(&sdlsurface->atlas, &texw, &texh, NK_FONT_ATLAS_RGBA32); + nk_font_atlas_init_default(&rawfb->atlas); + nk_font_atlas_begin(&rawfb->atlas); + rawfb->atlas.default_font = nk_font_atlas_add_default(&rawfb->atlas, fontSize, 0); + tex = nk_font_atlas_bake(&rawfb->atlas, &rawfb->font_tex.w, &rawfb->font_tex.h, NK_FONT_ATLAS_RGBA32); if (!tex) { - free(sdlsurface); - return NULL; + free(rawfb); + return NULL; } - sdlsurface->font_tex = SDL_CreateRGBSurface(0, texw, texh, 32, 0xff, 0xff00, 0xff0000, 0xff000000); + rawfb->font_tex.surf = SDL_CreateRGBSurface(0, rawfb->font_tex.w, rawfb->font_tex.h, 32, 0xff, 0xff00, 0xff0000, 0xff000000); - memcpy(sdlsurface->font_tex->pixels, tex, texw * texh * 4); + memcpy(rawfb->font_tex.surf->pixels, tex, rawfb->font_tex.w * rawfb->font_tex.h * 4); + nk_font_atlas_end(&rawfb->atlas, nk_handle_ptr(NULL), NULL); + if (rawfb->atlas.default_font) + nk_style_set_font(&rawfb->ctx, &rawfb->atlas.default_font->handle); + nk_style_load_all_cursors(&rawfb->ctx, rawfb->atlas.cursors); + nk_rawfb_scissor(rawfb, 0, 0, rawfb->fb.w, rawfb->fb.h); - nk_font_atlas_end(&sdlsurface->atlas, nk_handle_ptr(NULL), NULL); - if (sdlsurface->atlas.default_font) - nk_style_set_font(&sdlsurface->ctx, &sdlsurface->atlas.default_font->handle); - nk_style_load_all_cursors(&sdlsurface->ctx, sdlsurface->atlas.cursors); - nk_sdlsurface_scissor(sdlsurface, 0, 0, sdlsurface->fb->w, sdlsurface->fb->h); - - return sdlsurface; + return rawfb; } static void -nk_sdlsurface_stretch_image(const struct SDL_Surface *dst, - const struct SDL_Surface *src, const struct nk_rect *dst_rect, +nk_rawfb_stretch_image(const struct rawfb_image *dst, + const struct rawfb_image *src, const struct nk_rect *dst_rect, const struct nk_rect *src_rect, const struct nk_rect *dst_scissors, const struct nk_color *fg) { @@ -861,14 +869,14 @@ nk_sdlsurface_stretch_image(const struct SDL_Surface *dst, if (j + (int)(dst_rect->y + 0.5f) < dst_scissors->y || j + (int)(dst_rect->y + 0.5f) >= dst_scissors->h) continue; } - col = nk_sdlsurface_img_getpixel(src, (int)xoff, (int) yoff); + col = nk_rawfb_img_getpixel(src, (int)xoff, (int) yoff); if (col.r || col.g || col.b) { col.r = fg->r; col.g = fg->g; col.b = fg->b; } - nk_sdlsurface_img_blendpixel(dst, i + (int)(dst_rect->x + 0.5f), j + (int)(dst_rect->y + 0.5f), col); + nk_rawfb_img_blendpixel(dst, i + (int)(dst_rect->x + 0.5f), j + (int)(dst_rect->y + 0.5f), col); xoff += xinc; } xoff = src_rect->x; @@ -877,7 +885,7 @@ nk_sdlsurface_stretch_image(const struct SDL_Surface *dst, } static void -nk_sdlsurface_font_query_font_glyph(nk_handle handle, const float height, +nk_rawfb_font_query_font_glyph(nk_handle handle, const float height, struct nk_user_font_glyph *glyph, const nk_rune codepoint, const nk_rune next_codepoint) { @@ -904,7 +912,7 @@ nk_sdlsurface_font_query_font_glyph(nk_handle handle, const float height, } NK_API void -nk_sdlsurface_draw_text(const struct sdlsurface_context *sdlsurface, +nk_rawfb_draw_text(const struct rawfb_context *rawfb, const struct nk_user_font *font, const struct nk_rect rect, const char *text, const int len, const float font_height, const struct nk_color fg) @@ -931,15 +939,15 @@ nk_sdlsurface_draw_text(const struct sdlsurface_context *sdlsurface, /* query currently drawn glyph information */ next_glyph_len = nk_utf_decode(text + text_len + glyph_len, &next, (int)len - text_len); - nk_sdlsurface_font_query_font_glyph(font->userdata, font_height, &g, unicode, + nk_rawfb_font_query_font_glyph(font->userdata, font_height, &g, unicode, (next == NK_UTF_INVALID) ? '\0' : next); /* calculate and draw glyph drawing rectangle and image */ char_width = g.xadvance; - src_rect.x = g.uv[0].x * sdlsurface->font_tex->w; - src_rect.y = g.uv[0].y * sdlsurface->font_tex->h; - src_rect.w = g.uv[1].x * sdlsurface->font_tex->w - g.uv[0].x * sdlsurface->font_tex->w; - src_rect.h = g.uv[1].y * sdlsurface->font_tex->h - g.uv[0].y * sdlsurface->font_tex->h; + src_rect.x = g.uv[0].x * rawfb->font_tex.w; + src_rect.y = g.uv[0].y * rawfb->font_tex.h; + src_rect.w = g.uv[1].x * rawfb->font_tex.w - g.uv[0].x * rawfb->font_tex.w; + src_rect.h = g.uv[1].y * rawfb->font_tex.h - g.uv[0].y * rawfb->font_tex.h; dst_rect.x = x + g.offset.x + rect.x; dst_rect.y = g.offset.y + rect.y; @@ -947,7 +955,7 @@ nk_sdlsurface_draw_text(const struct sdlsurface_context *sdlsurface, dst_rect.h = ceil(g.height); /* Use software rescaling to blit glyph from font_text to framebuffer */ - nk_sdlsurface_stretch_image(sdlsurface->fb, sdlsurface->font_tex, &dst_rect, &src_rect, &sdlsurface->scissors, &fg); + nk_rawfb_stretch_image(&rawfb->fb, &rawfb->font_tex, &dst_rect, &src_rect, &rawfb->scissors, &fg); /* offset next glyph */ text_len += glyph_len; @@ -958,7 +966,7 @@ nk_sdlsurface_draw_text(const struct sdlsurface_context *sdlsurface, } NK_API void -nk_sdlsurface_drawimage(const struct sdlsurface_context *sdlsurface, +nk_rawfb_drawimage(const struct rawfb_context *rawfb, const int x, const int y, const int w, const int h, const struct nk_image *img, const struct nk_color *col) { @@ -974,99 +982,99 @@ nk_sdlsurface_drawimage(const struct sdlsurface_context *sdlsurface, dst_rect.y = y; dst_rect.w = w; dst_rect.h = h; - nk_sdlsurface_stretch_image(sdlsurface->fb, sdlsurface->font_tex, &dst_rect, &src_rect, &sdlsurface->scissors, col); + nk_rawfb_stretch_image(&rawfb->fb, &rawfb->font_tex, &dst_rect, &src_rect, &rawfb->scissors, col); } NK_API void -nk_sdlsurface_shutdown(struct sdlsurface_context *sdlsurface) +nk_rawfb_shutdown(struct rawfb_context *rawfb) { - if (sdlsurface) { - SDL_FreeSurface(sdlsurface->font_tex); - nk_free(&sdlsurface->ctx); - memset(sdlsurface, 0, sizeof(struct sdlsurface_context)); - free(sdlsurface); + if (rawfb) { + SDL_FreeSurface(rawfb->font_tex.surf); + nk_free(&rawfb->ctx); + memset(rawfb, 0, sizeof(struct rawfb_context)); + free(rawfb); } } NK_API void -nk_sdlsurface_render(const struct sdlsurface_context *sdlsurface, +nk_rawfb_render(const struct rawfb_context *rawfb, const struct nk_color clear, const unsigned char enable_clear) { const struct nk_command *cmd; if (enable_clear) - nk_sdlsurface_clear(sdlsurface, clear); + nk_rawfb_clear(rawfb, clear); - nk_foreach(cmd, (struct nk_context*)&sdlsurface->ctx) { + nk_foreach(cmd, (struct nk_context*)&rawfb->ctx) { switch (cmd->type) { case NK_COMMAND_NOP: break; case NK_COMMAND_SCISSOR: { const struct nk_command_scissor *s =(const struct nk_command_scissor*)cmd; - nk_sdlsurface_scissor((struct sdlsurface_context *)sdlsurface, s->x, s->y, s->w, s->h); + nk_rawfb_scissor((struct rawfb_context *)rawfb, s->x, s->y, s->w, s->h); } break; case NK_COMMAND_LINE: { const struct nk_command_line *l = (const struct nk_command_line *)cmd; - nk_sdlsurface_stroke_line(sdlsurface, l->begin.x, l->begin.y, l->end.x, + nk_rawfb_stroke_line(rawfb, l->begin.x, l->begin.y, l->end.x, l->end.y, l->line_thickness, l->color); } break; case NK_COMMAND_RECT: { const struct nk_command_rect *r = (const struct nk_command_rect *)cmd; - nk_sdlsurface_stroke_rect(sdlsurface, r->x, r->y, r->w, r->h, + nk_rawfb_stroke_rect(rawfb, r->x, r->y, r->w, r->h, (unsigned short)r->rounding, r->line_thickness, r->color); } break; case NK_COMMAND_RECT_FILLED: { const struct nk_command_rect_filled *r = (const struct nk_command_rect_filled *)cmd; - nk_sdlsurface_fill_rect(sdlsurface, r->x, r->y, r->w, r->h, + nk_rawfb_fill_rect(rawfb, r->x, r->y, r->w, r->h, (unsigned short)r->rounding, r->color); } break; case NK_COMMAND_CIRCLE: { const struct nk_command_circle *c = (const struct nk_command_circle *)cmd; - nk_sdlsurface_stroke_circle(sdlsurface, c->x, c->y, c->w, c->h, c->line_thickness, c->color); + nk_rawfb_stroke_circle(rawfb, c->x, c->y, c->w, c->h, c->line_thickness, c->color); } break; case NK_COMMAND_CIRCLE_FILLED: { const struct nk_command_circle_filled *c = (const struct nk_command_circle_filled *)cmd; - nk_sdlsurface_fill_circle(sdlsurface, c->x, c->y, c->w, c->h, c->color); + nk_rawfb_fill_circle(rawfb, c->x, c->y, c->w, c->h, c->color); } break; case NK_COMMAND_TRIANGLE: { const struct nk_command_triangle*t = (const struct nk_command_triangle*)cmd; - nk_sdlsurface_stroke_triangle(sdlsurface, t->a.x, t->a.y, t->b.x, t->b.y, + nk_rawfb_stroke_triangle(rawfb, t->a.x, t->a.y, t->b.x, t->b.y, t->c.x, t->c.y, t->line_thickness, t->color); } break; case NK_COMMAND_TRIANGLE_FILLED: { const struct nk_command_triangle_filled *t = (const struct nk_command_triangle_filled *)cmd; - nk_sdlsurface_fill_triangle(sdlsurface, t->a.x, t->a.y, t->b.x, t->b.y, + nk_rawfb_fill_triangle(rawfb, t->a.x, t->a.y, t->b.x, t->b.y, t->c.x, t->c.y, t->color); } break; case NK_COMMAND_POLYGON: { const struct nk_command_polygon *p =(const struct nk_command_polygon*)cmd; - nk_sdlsurface_stroke_polygon(sdlsurface, p->points, p->point_count, p->line_thickness,p->color); + nk_rawfb_stroke_polygon(rawfb, p->points, p->point_count, p->line_thickness,p->color); } break; case NK_COMMAND_POLYGON_FILLED: { const struct nk_command_polygon_filled *p = (const struct nk_command_polygon_filled *)cmd; - nk_sdlsurface_fill_polygon(sdlsurface, p->points, p->point_count, p->color); + nk_rawfb_fill_polygon(rawfb, p->points, p->point_count, p->color); } break; case NK_COMMAND_POLYLINE: { const struct nk_command_polyline *p = (const struct nk_command_polyline *)cmd; - nk_sdlsurface_stroke_polyline(sdlsurface, p->points, p->point_count, p->line_thickness, p->color); + nk_rawfb_stroke_polyline(rawfb, p->points, p->point_count, p->line_thickness, p->color); } break; case NK_COMMAND_TEXT: { const struct nk_command_text *t = (const struct nk_command_text*)cmd; - nk_sdlsurface_draw_text(sdlsurface, t->font, nk_rect(t->x, t->y, t->w, t->h), + nk_rawfb_draw_text(rawfb, t->font, nk_rect(t->x, t->y, t->w, t->h), t->string, t->length, t->height, t->foreground); } break; case NK_COMMAND_CURVE: { const struct nk_command_curve *q = (const struct nk_command_curve *)cmd; - nk_sdlsurface_stroke_curve(sdlsurface, q->begin, q->ctrl[0], q->ctrl[1], + nk_rawfb_stroke_curve(rawfb, q->begin, q->ctrl[0], q->ctrl[1], q->end, 22, q->line_thickness, q->color); } break; case NK_COMMAND_RECT_MULTI_COLOR: { - const struct nk_command_rect_multi_color *q = (const struct nk_command_rect_multi_color *)cmd; - nk_sdlsurface_draw_rect_multi_color(sdlsurface, q->x, q->y, q->w, q->h, q->left, q->top, q->right, q->bottom); - } break; + const struct nk_command_rect_multi_color *q = (const struct nk_command_rect_multi_color *)cmd; + nk_rawfb_draw_rect_multi_color(rawfb, q->x, q->y, q->w, q->h, q->left, q->top, q->right, q->bottom); + } break; case NK_COMMAND_IMAGE: { const struct nk_command_image *q = (const struct nk_command_image *)cmd; - nk_sdlsurface_drawimage(sdlsurface, q->x, q->y, q->w, q->h, &q->img, &q->col); + nk_rawfb_drawimage(rawfb, q->x, q->y, q->w, q->h, &q->img, &q->col); } break; case NK_COMMAND_ARC: { assert(0 && "NK_COMMAND_ARC not implemented\n"); @@ -1076,8 +1084,7 @@ nk_sdlsurface_render(const struct sdlsurface_context *sdlsurface, } break; default: break; } - } - nk_clear((struct nk_context*)&sdlsurface->ctx); + } nk_clear((struct nk_context*)&rawfb->ctx); } #endif diff --git a/demo/wayland_rawfb/.gitignore b/demo/rawfb/wayland/.gitignore similarity index 100% rename from demo/wayland_rawfb/.gitignore rename to demo/rawfb/wayland/.gitignore diff --git a/demo/wayland_rawfb/Makefile b/demo/rawfb/wayland/Makefile similarity index 100% rename from demo/wayland_rawfb/Makefile rename to demo/rawfb/wayland/Makefile diff --git a/demo/wayland_rawfb/main.c b/demo/rawfb/wayland/main.c similarity index 75% rename from demo/wayland_rawfb/main.c rename to demo/rawfb/wayland/main.c index cf60eed..7241422 100644 --- a/demo/wayland_rawfb/main.c +++ b/demo/rawfb/wayland/main.c @@ -4,11 +4,11 @@ #define NK_INCLUDE_STANDARD_VARARGS #define NK_INCLUDE_DEFAULT_ALLOCATOR #define NK_IMPLEMENTATION +#define NK_RAWFB_IMPLEMENTATION #define NK_INCLUDE_FONT_BAKING #define NK_INCLUDE_DEFAULT_FONT #define NK_INCLUDE_SOFTWARE_FONT - #include #include #include @@ -20,11 +20,34 @@ #include #include -#include "../../nuklear.h" +#include "../../../nuklear.h" #include "xdg-shell.h" -#include "nuklear_raw_wayland.h" +#include "../nuklear_rawfb.h" +struct nk_wayland { + /*wayland vars*/ + struct wl_display *display; + struct wl_compositor *compositor; + struct xdg_wm_base *xdg_wm_base; + struct wl_shm *wl_shm; + struct wl_seat* seat; + struct wl_callback *frame_callback; + struct wl_surface *surface; + struct xdg_surface *xdg_surface; + struct xdg_toplevel *xdg_toplevel; + struct wl_buffer *front_buffer; + + int32_t *data; + int mouse_pointer_x; + int mouse_pointer_y; + uint8_t tex_scratch[512 * 512]; + + struct rawfb_context *rawfb; +}; + +#define WIDTH 800 +#define HEIGHT 600 #define DTIME 20 @@ -51,19 +74,19 @@ #endif #ifdef INCLUDE_STYLE - #include "../../demo/common/style.c" + #include "../../common/style.c" #endif #ifdef INCLUDE_CALCULATOR - #include "../../demo/common/calculator.c" + #include "../../common/calculator.c" #endif #ifdef INCLUDE_CANVAS - #include "../../demo/common/canvas.c" + #include "../../common/canvas.c" #endif #ifdef INCLUDE_OVERVIEW - #include "../../demo/common/overview.c" + #include "../../common/overview.c" #endif #ifdef INCLUDE_NODE_EDITOR - #include "../../demo/common/node_editor.c" + #include "../../common/node_editor.c" #endif @@ -113,7 +136,7 @@ static const struct wl_output_listener nk_wayland_output_listener = //-------------------------------------------------------------------- endof WAYLAND OUTPUT INTERFACE //WAYLAND POINTER INTERFACE (mouse/touchpad) -static void nk_wayland_pointer_enter (void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t surface_x, wl_fixed_t surface_y) +static void nk_wayland_pointer_enter (void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t surface_x, wl_fixed_t surface_y) { NK_UNUSED(data); NK_UNUSED(pointer); @@ -123,7 +146,7 @@ static void nk_wayland_pointer_enter (void *data, struct wl_pointer *pointer, ui NK_UNUSED(surface_y); } -static void nk_wayland_pointer_leave (void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) +static void nk_wayland_pointer_leave (void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) { NK_UNUSED(data); NK_UNUSED(pointer); @@ -131,7 +154,7 @@ static void nk_wayland_pointer_leave (void *data, struct wl_pointer *pointer, ui NK_UNUSED(surface); } -static void nk_wayland_pointer_motion (void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t x, wl_fixed_t y) +static void nk_wayland_pointer_motion (void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t x, wl_fixed_t y) { struct nk_wayland* win = (struct nk_wayland*)data; @@ -140,11 +163,11 @@ static void nk_wayland_pointer_motion (void *data, struct wl_pointer *pointer, u win->mouse_pointer_x = wl_fixed_to_int(x); win->mouse_pointer_y = wl_fixed_to_int(y); - - nk_input_motion(&(win->ctx), win->mouse_pointer_x, win->mouse_pointer_y); + + nk_input_motion(&(win->rawfb->ctx), win->mouse_pointer_x, win->mouse_pointer_y); } -static void nk_wayland_pointer_button (void *data, struct wl_pointer *pointer, uint32_t serial, uint32_t time, uint32_t button, uint32_t state) +static void nk_wayland_pointer_button (void *data, struct wl_pointer *pointer, uint32_t serial, uint32_t time, uint32_t button, uint32_t state) { struct nk_wayland* win = (struct nk_wayland*)data; @@ -155,15 +178,15 @@ static void nk_wayland_pointer_button (void *data, struct wl_pointer *pointer, u if (button == 272){ //left mouse button if (state == WL_POINTER_BUTTON_STATE_PRESSED) { // printf("nk_input_button x=%d, y=%d press: 1 \n", win->mouse_pointer_x, win->mouse_pointer_y); - nk_input_button(&(win->ctx), NK_BUTTON_LEFT, win->mouse_pointer_x, win->mouse_pointer_y, 1); - + nk_input_button(&(win->rawfb->ctx), NK_BUTTON_LEFT, win->mouse_pointer_x, win->mouse_pointer_y, 1); + } else if (state == WL_POINTER_BUTTON_STATE_RELEASED) { - nk_input_button(&(win->ctx), NK_BUTTON_LEFT, win->mouse_pointer_x, win->mouse_pointer_y, 0); + nk_input_button(&(win->rawfb->ctx), NK_BUTTON_LEFT, win->mouse_pointer_x, win->mouse_pointer_y, 0); } } } -static void nk_wayland_pointer_axis (void *data, struct wl_pointer *pointer, uint32_t time, uint32_t axis, wl_fixed_t value) +static void nk_wayland_pointer_axis (void *data, struct wl_pointer *pointer, uint32_t time, uint32_t axis, wl_fixed_t value) { NK_UNUSED(data); NK_UNUSED(pointer); @@ -172,12 +195,12 @@ static void nk_wayland_pointer_axis (void *data, struct wl_pointer *pointer, uin NK_UNUSED(value); } -static struct wl_pointer_listener nk_wayland_pointer_listener = +static struct wl_pointer_listener nk_wayland_pointer_listener = { - &nk_wayland_pointer_enter, - &nk_wayland_pointer_leave, - &nk_wayland_pointer_motion, - &nk_wayland_pointer_button, + &nk_wayland_pointer_enter, + &nk_wayland_pointer_leave, + &nk_wayland_pointer_motion, + &nk_wayland_pointer_button, &nk_wayland_pointer_axis, NULL, NULL, @@ -187,7 +210,7 @@ static struct wl_pointer_listener nk_wayland_pointer_listener = //-------------------------------------------------------------------- endof WAYLAND POINTER INTERFACE //WAYLAND KEYBOARD INTERFACE -static void nk_wayland_keyboard_keymap (void *data, struct wl_keyboard *keyboard, uint32_t format, int32_t fd, uint32_t size) +static void nk_wayland_keyboard_keymap (void *data, struct wl_keyboard *keyboard, uint32_t format, int32_t fd, uint32_t size) { NK_UNUSED(data); NK_UNUSED(keyboard); @@ -196,7 +219,7 @@ static void nk_wayland_keyboard_keymap (void *data, struct wl_keyboard *keyboard NK_UNUSED(size); } -static void nk_wayland_keyboard_enter (void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface, struct wl_array *keys) +static void nk_wayland_keyboard_enter (void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface, struct wl_array *keys) { NK_UNUSED(data); NK_UNUSED(keyboard); @@ -205,7 +228,7 @@ static void nk_wayland_keyboard_enter (void *data, struct wl_keyboard *keyboard, NK_UNUSED(keys); } -static void nk_wayland_keyboard_leave (void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) +static void nk_wayland_keyboard_leave (void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) { NK_UNUSED(data); NK_UNUSED(keyboard); @@ -213,7 +236,7 @@ static void nk_wayland_keyboard_leave (void *data, struct wl_keyboard *keyboard, NK_UNUSED(surface); } -static void nk_wayland_keyboard_key (void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key, uint32_t state) +static void nk_wayland_keyboard_key (void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key, uint32_t state) { NK_UNUSED(data); NK_UNUSED(keyboard); @@ -234,22 +257,22 @@ static void nk_wayland_keyboard_modifiers (void *data, struct wl_keyboard *keybo NK_UNUSED(group); } -static struct wl_keyboard_listener nk_wayland_keyboard_listener = +static struct wl_keyboard_listener nk_wayland_keyboard_listener = { - &nk_wayland_keyboard_keymap, - &nk_wayland_keyboard_enter, - &nk_wayland_keyboard_leave, - &nk_wayland_keyboard_key, + &nk_wayland_keyboard_keymap, + &nk_wayland_keyboard_enter, + &nk_wayland_keyboard_leave, + &nk_wayland_keyboard_key, &nk_wayland_keyboard_modifiers, NULL }; //-------------------------------------------------------------------- endof WAYLAND KEYBOARD INTERFACE //WAYLAND SEAT INTERFACE -static void seat_capabilities (void *data, struct wl_seat *seat, uint32_t capabilities) +static void seat_capabilities (void *data, struct wl_seat *seat, uint32_t capabilities) { struct nk_wayland* win = (struct nk_wayland*)data; - + if (capabilities & WL_SEAT_CAPABILITY_POINTER) { struct wl_pointer *pointer = wl_seat_get_pointer (seat); wl_pointer_add_listener (pointer, &nk_wayland_pointer_listener, win); @@ -314,7 +337,7 @@ static struct xdg_toplevel_listener nk_wayland_xdg_toplevel_listener = // WAYLAND REGISTRY INTERFACE -static void nk_wayland_registry_add_object (void *data, struct wl_registry *registry, uint32_t name, const char *interface, uint32_t version) +static void nk_wayland_registry_add_object (void *data, struct wl_registry *registry, uint32_t name, const char *interface, uint32_t version) { struct nk_wayland* win = (struct nk_wayland*)data; @@ -323,76 +346,38 @@ static void nk_wayland_registry_add_object (void *data, struct wl_registry *regi //printf("looking for %s interface \n", interface); if (!strcmp(interface,"wl_compositor")) { win->compositor = wl_registry_bind (registry, name, &wl_compositor_interface, 1); - + } else if (!strcmp(interface,"xdg_wm_base")) { win->xdg_wm_base = wl_registry_bind (registry, name, &xdg_wm_base_interface, 1); xdg_wm_base_add_listener (win->xdg_wm_base, &nk_wayland_xdg_wm_base_listener, win); } else if (!strcmp(interface,"wl_shm")) { win->wl_shm = wl_registry_bind (registry, name, &wl_shm_interface, 1); - + } else if (!strcmp(interface,"wl_seat")) { win->seat = wl_registry_bind (registry, name, &wl_seat_interface, 1); wl_seat_add_listener (win->seat, &seat_listener, win); - + } else if (!strcmp(interface, "wl_output")) { struct wl_output *wl_output = wl_registry_bind(registry, name, &wl_output_interface, 1); wl_output_add_listener(wl_output, &nk_wayland_output_listener, NULL); } } -static void nk_wayland_registry_remove_object (void *data, struct wl_registry *registry, uint32_t name) +static void nk_wayland_registry_remove_object (void *data, struct wl_registry *registry, uint32_t name) { NK_UNUSED(data); NK_UNUSED(registry); NK_UNUSED(name); } -static struct wl_registry_listener nk_wayland_registry_listener = +static struct wl_registry_listener nk_wayland_registry_listener = { - &nk_wayland_registry_add_object, + &nk_wayland_registry_add_object, &nk_wayland_registry_remove_object }; //------------------------------------------------------------------------------------------------ endof WAYLAND REGISTRY INTERFACE - -static void nk_wayland_init(struct nk_wayland* win) -{ - const void *tex; - - win->font_tex.pixels = win->tex_scratch; - win->font_tex.format = NK_FONT_ATLAS_ALPHA8; - win->font_tex.w = win->font_tex.h = 0; - - if (0 == nk_init_default(&(win->ctx), 0)) { - return; - } - - nk_font_atlas_init_default(&(win->atlas)); - nk_font_atlas_begin(&(win->atlas)); - tex = nk_font_atlas_bake(&(win->atlas), &(win->font_tex.w), &(win->font_tex.h), win->font_tex.format); - if (!tex) { - return; - } - - switch(win->font_tex.format) { - case NK_FONT_ATLAS_ALPHA8: - win->font_tex.pitch = win->font_tex.w * 1; - break; - case NK_FONT_ATLAS_RGBA32: - win->font_tex.pitch = win->font_tex.w * 4; - break; - }; - /* Store the font texture in tex scratch memory */ - memcpy(win->font_tex.pixels, tex, win->font_tex.pitch * win->font_tex.h); - nk_font_atlas_end(&(win->atlas), nk_handle_ptr(NULL), NULL); - if (win->atlas.default_font) - nk_style_set_font(&(win->ctx), &(win->atlas.default_font->handle)); - nk_style_load_all_cursors(&(win->ctx), win->atlas.cursors); - nk_wayland_scissor(win, 0, 0, win->width, win->height); - -} - -static void nk_wayland_deinit(struct nk_wayland *win) +static void nk_wayland_deinit(struct nk_wayland *win) { xdg_toplevel_destroy (win->xdg_toplevel); xdg_surface_destroy (win->xdg_surface); @@ -421,16 +406,16 @@ static void nk_wayland_surf_clear(struct nk_wayland* win) { int x, y; int pix_idx; - - for (y = 0; y < win->height; y++){ - for (x = 0; x < win->width; x++){ - pix_idx = y * win->width + x; + + for (y = 0; y < HEIGHT; y++){ + for (x = 0; x < WIDTH; x++){ + pix_idx = y * WIDTH + x; win->data[pix_idx] = 0xFF000000; } } } -//This causes the screen to refresh +//This causes the screen to refresh static const struct wl_callback_listener frame_listener; static void redraw(void *data, struct wl_callback *callback, uint32_t time) @@ -442,15 +427,15 @@ static void redraw(void *data, struct wl_callback *callback, uint32_t time) NK_UNUSED(time); wl_callback_destroy(win->frame_callback); - wl_surface_damage(win->surface, 0, 0, WIDTH, HEIGHT); - + wl_surface_damage(win->surface, 0, 0, WIDTH, HEIGHT); + win->frame_callback = wl_surface_frame(win->surface); wl_surface_attach(win->surface, win->front_buffer, 0, 0); wl_callback_add_listener(win->frame_callback, &frame_listener, win); wl_surface_commit(win->surface); - + } @@ -458,30 +443,27 @@ static const struct wl_callback_listener frame_listener = { redraw }; -int main () +int main () { long dt; long started; struct nk_wayland nk_wayland_ctx; struct wl_registry *registry; int running = 1; - + //1. Initialize display nk_wayland_ctx.display = wl_display_connect (NULL); if (nk_wayland_ctx.display == NULL) { printf("no wayland display found. do you have wayland composer running? \n"); return -1; } - + registry = wl_display_get_registry (nk_wayland_ctx.display); wl_registry_add_listener (registry, &nk_wayland_registry_listener, &nk_wayland_ctx); wl_display_roundtrip (nk_wayland_ctx.display); - - - //2. Create Window - nk_wayland_ctx.width = WIDTH; - nk_wayland_ctx.height = HEIGHT; + + //2. Create Window nk_wayland_ctx.surface = wl_compositor_create_surface (nk_wayland_ctx.compositor); nk_wayland_ctx.xdg_surface = xdg_wm_base_get_xdg_surface(nk_wayland_ctx.xdg_wm_base, nk_wayland_ctx.surface); @@ -508,70 +490,70 @@ int main () wl_display_roundtrip (nk_wayland_ctx.display); - //3. Clear window and start rendering loop + //3. Clear window and start rendering loop nk_wayland_surf_clear(&nk_wayland_ctx); wl_surface_attach (nk_wayland_ctx.surface, nk_wayland_ctx.front_buffer, 0, 0); wl_surface_commit (nk_wayland_ctx.surface); - nk_wayland_init(&nk_wayland_ctx); - - + nk_rawfb_init(nk_wayland_ctx.data, nk_wayland_ctx.tex_scratch, WIDTH, HEIGHT, WIDTH*4, PIXEL_LAYOUT_XRGB_8888); + + //4. rendering UI while (running) { - started = timestamp(); - - // GUI - if (nk_begin(&(nk_wayland_ctx.ctx), "Demo", nk_rect(50, 50, 200, 200), + started = timestamp(); + + // GUI + if (nk_begin(&(nk_wayland_ctx.rawfb->ctx), "Demo", nk_rect(50, 50, 200, 200), NK_WINDOW_BORDER|NK_WINDOW_MOVABLE| NK_WINDOW_CLOSABLE|NK_WINDOW_MINIMIZABLE|NK_WINDOW_TITLE)) { enum {EASY, HARD}; static int op = EASY; static int property = 20; - nk_layout_row_static(&(nk_wayland_ctx.ctx), 30, 80, 1); - if (nk_button_label(&(nk_wayland_ctx.ctx), "button")){ + nk_layout_row_static(&(nk_wayland_ctx.rawfb->ctx), 30, 80, 1); + if (nk_button_label(&(nk_wayland_ctx.rawfb->ctx), "button")){ printf("button pressed\n"); } - nk_layout_row_dynamic(&(nk_wayland_ctx.ctx), 30, 2); - if (nk_option_label(&(nk_wayland_ctx.ctx), "easy", op == EASY)) op = EASY; - if (nk_option_label(&(nk_wayland_ctx.ctx), "hard", op == HARD)) op = HARD; - nk_layout_row_dynamic(&(nk_wayland_ctx.ctx), 25, 1); - nk_property_int(&(nk_wayland_ctx.ctx), "Compression:", 0, &property, 100, 10, 1); + nk_layout_row_dynamic(&(nk_wayland_ctx.rawfb->ctx), 30, 2); + if (nk_option_label(&(nk_wayland_ctx.rawfb->ctx), "easy", op == EASY)) op = EASY; + if (nk_option_label(&(nk_wayland_ctx.rawfb->ctx), "hard", op == HARD)) op = HARD; + nk_layout_row_dynamic(&(nk_wayland_ctx.rawfb->ctx), 25, 1); + nk_property_int(&(nk_wayland_ctx.rawfb->ctx), "Compression:", 0, &property, 100, 10, 1); } - nk_end(&(nk_wayland_ctx.ctx)); - - if (nk_window_is_closed(&(nk_wayland_ctx.ctx), "Demo")) break; + nk_end(&(nk_wayland_ctx.rawfb->ctx)); + + if (nk_window_is_closed(&(nk_wayland_ctx.rawfb->ctx), "Demo")) break; /* -------------- EXAMPLES ---------------- */ #ifdef INCLUDE_CALCULATOR - calculator(&(nk_wayland_ctx.ctx)); + calculator(&(nk_wayland_ctx.rawfb->ctx)); #endif #ifdef INCLUDE_CANVAS - canvas(&(nk_wayland_ctx.ctx)); + canvas(&(nk_wayland_ctx.rawfb->ctx)); #endif #ifdef INCLUDE_OVERVIEW - overview(&(nk_wayland_ctx.ctx)); + overview(&(nk_wayland_ctx.rawfb->ctx)); #endif #ifdef INCLUDE_NODE_EDITOR - node_editor(&(nk_wayland_ctx.ctx)); + node_editor(&(nk_wayland_ctx.rawfb->ctx)); #endif /* ----------------------------------------- */ - // Draw framebuffer - nk_wayland_render(&nk_wayland_ctx, nk_rgb(30,30,30), 1); - - + // Draw framebuffer + nk_rawfb_render(nk_wayland_ctx.rawfb, nk_rgb(30,30,30), 1); + + //handle wayland stuff (send display to FB & get inputs) - nk_input_begin(&(nk_wayland_ctx.ctx)); + nk_input_begin(&(nk_wayland_ctx.rawfb->ctx)); wl_display_dispatch(nk_wayland_ctx.display); - nk_input_end(&(nk_wayland_ctx.ctx)); - - // Timing + nk_input_end(&(nk_wayland_ctx.rawfb->ctx)); + + // Timing dt = timestamp() - started; if (dt < DTIME) sleep_for(DTIME - dt); } - + nk_wayland_deinit (&nk_wayland_ctx); wl_display_disconnect (nk_wayland_ctx.display); return 0; diff --git a/demo/x11_rawfb/Makefile b/demo/rawfb/x11/Makefile similarity index 100% rename from demo/x11_rawfb/Makefile rename to demo/rawfb/x11/Makefile diff --git a/demo/x11_rawfb/main.c b/demo/rawfb/x11/main.c similarity index 96% rename from demo/x11_rawfb/main.c rename to demo/rawfb/x11/main.c index 52a1c93..1f61230 100644 --- a/demo/x11_rawfb/main.c +++ b/demo/rawfb/x11/main.c @@ -46,8 +46,8 @@ #define NK_INCLUDE_DEFAULT_FONT #define NK_INCLUDE_SOFTWARE_FONT -#include "../../nuklear.h" -#include "nuklear_rawfb.h" +#include "../../../nuklear.h" +#include "../nuklear_rawfb.h" #include "nuklear_xlib.h" #define DTIME 20 @@ -126,19 +126,19 @@ sleep_for(long t) #endif #ifdef INCLUDE_STYLE - #include "../../demo/common/style.c" + #include "../../common/style.c" #endif #ifdef INCLUDE_CALCULATOR - #include "../../demo/common/calculator.c" + #include "../../common/calculator.c" #endif #ifdef INCLUDE_CANVAS - #include "../../demo/common/canvas.c" + #include "../../common/canvas.c" #endif #ifdef INCLUDE_OVERVIEW - #include "../../demo/common/overview.c" + #include "../../common/overview.c" #endif #ifdef INCLUDE_NODE_EDITOR - #include "../../demo/common/node_editor.c" + #include "../../common/node_editor.c" #endif /* =============================================================== diff --git a/demo/x11_rawfb/nuklear_xlib.h b/demo/rawfb/x11/nuklear_xlib.h similarity index 100% rename from demo/x11_rawfb/nuklear_xlib.h rename to demo/rawfb/x11/nuklear_xlib.h diff --git a/demo/wayland_rawfb/nuklear_raw_wayland.h b/demo/wayland_rawfb/nuklear_raw_wayland.h deleted file mode 100644 index 1a465fc..0000000 --- a/demo/wayland_rawfb/nuklear_raw_wayland.h +++ /dev/null @@ -1,869 +0,0 @@ -#ifndef NK_RAW_WAYLAND_H_ -#define NK_RAW_WAYLAND_H_ - -#include -#include -#include - -#define WIDTH 800 -#define HEIGHT 600 - -#ifndef MIN -#define MIN(a,b) ((a) < (b) ? (a) : (b)) -#endif -#ifndef MAX -#define MAX(a,b) ((a) < (b) ? (b) : (a)) -#endif - -typedef enum wayland_pixel_layout { - PIXEL_LAYOUT_XRGB_8888, - PIXEL_LAYOUT_RGBX_8888, -} wayland_pl; - -struct wayland_img { - void *pixels; - int w, h, pitch; - wayland_pl pl; - enum nk_font_atlas_format format; -}; - -struct nk_wayland{ - /*wayland vars*/ - struct wl_display *display; - struct wl_compositor *compositor; - struct xdg_wm_base *xdg_wm_base; - struct wl_shm *wl_shm; - struct wl_seat* seat; - struct wl_callback *frame_callback; - struct wl_surface *surface; - struct xdg_surface *xdg_surface; - struct xdg_toplevel *xdg_toplevel; - struct wl_buffer *front_buffer; - - - /*nuklear vars*/ - struct nk_context ctx; - struct nk_rect scissors; - struct nk_font_atlas atlas; - struct wayland_img font_tex; - int32_t width, height; - int32_t *data; - int mouse_pointer_x; - int mouse_pointer_y; - uint8_t tex_scratch[512 * 512]; - -}; - -static uint32_t nk_color_to_xrgb8888(struct nk_color col) -{ - return (col.a << 24) + (col.r << 16) + (col.g << 8) + col.b; -} - -static struct nk_color nk_wayland_int2color(const unsigned int i, wayland_pl pl) -{ - struct nk_color col = {0,0,0,0}; - - switch (pl) { - case PIXEL_LAYOUT_RGBX_8888: - col.r = (i >> 24) & 0xff; - col.g = (i >> 16) & 0xff; - col.b = (i >> 8) & 0xff; - col.a = i & 0xff; - break; - case PIXEL_LAYOUT_XRGB_8888: - col.a = (i >> 24) & 0xff; - col.r = (i >> 16) & 0xff; - col.g = (i >> 8) & 0xff; - col.b = i & 0xff; - break; - - default: - perror("nk_rawfb_int2color(): Unsupported pixel layout.\n"); - break; - } - return col; -} - -static unsigned int nk_wayland_color2int(const struct nk_color c, wayland_pl pl) -{ - unsigned int res = 0; - - switch (pl) { - case PIXEL_LAYOUT_RGBX_8888: - res |= c.r << 24; - res |= c.g << 16; - res |= c.b << 8; - res |= c.a; - break; - - case PIXEL_LAYOUT_XRGB_8888: - res |= c.a << 24; - res |= c.r << 16; - res |= c.g << 8; - res |= c.b; - break; - - default: - perror("nk_rawfb_color2int(): Unsupported pixel layout.\n"); - break; - } - return (res); -} - -static void nk_wayland_ctx_setpixel(const struct nk_wayland* win, - const short x0, const short y0, const struct nk_color col) -{ - uint32_t c = nk_color_to_xrgb8888(col); - uint32_t *pixels = (uint32_t *)win->data; - unsigned int *ptr; - - pixels += (y0 * win->width); - ptr = (unsigned int *)pixels + x0; - - if (y0 < win->scissors.h && y0 >= win->scissors.y && x0 >= win->scissors.x && x0 < win->scissors.w){ - *ptr = c; - }else { - printf("out of bound! \n"); - } -} - -static void nk_wayland_fill_polygon(const struct nk_wayland* win, const struct nk_vec2i *pnts, int count, const struct nk_color col) -{ - int i = 0; - //#define MAX_POINTS 64 - int left = 10000, top = 10000, bottom = 0, right = 0; - int nodes, nodeX[1024], pixelX, pixelY, j, swap ; - - if (count == 0) return; - if (count > 1024) - count = 1024; - - /* Get polygon dimensions */ - for (i = 0; i < count; i++) { - if (left > pnts[i].x) - left = pnts[i].x; - if (right < pnts[i].x) - right = pnts[i].x; - if (top > pnts[i].y) - top = pnts[i].y; - if (bottom < pnts[i].y) - bottom = pnts[i].y; - } bottom++; right++; - - /* Polygon scanline algorithm released under public-domain by Darel Rex Finley, 2007 */ - /* Loop through the rows of the image. */ - for (pixelY = top; pixelY < bottom; pixelY ++) { - nodes = 0; /* Build a list of nodes. */ - j = count - 1; - for (i = 0; i < count; i++) { - if (((pnts[i].y < pixelY) && (pnts[j].y >= pixelY)) || - ((pnts[j].y < pixelY) && (pnts[i].y >= pixelY))) { - nodeX[nodes++]= (int)((float)pnts[i].x - + ((float)pixelY - (float)pnts[i].y) / ((float)pnts[j].y - (float)pnts[i].y) - * ((float)pnts[j].x - (float)pnts[i].x)); - } j = i; - } - - /* Sort the nodes, via a simple “Bubble” sort. */ - i = 0; - while (i < nodes - 1) { - if (nodeX[i] > nodeX[i+1]) { - swap = nodeX[i]; - nodeX[i] = nodeX[i+1]; - nodeX[i+1] = swap; - if (i) i--; - } else i++; - } - /* Fill the pixels between node pairs. */ - for (i = 0; i < nodes; i += 2) { - if (nodeX[i+0] >= right) break; - if (nodeX[i+1] > left) { - if (nodeX[i+0] < left) nodeX[i+0] = left ; - if (nodeX[i+1] > right) nodeX[i+1] = right; - for (pixelX = nodeX[i]; pixelX < nodeX[i + 1]; pixelX++) - nk_wayland_ctx_setpixel(win, pixelX, pixelY, col); - } - } - } -} - -static void nk_wayland_fill_arc(const struct nk_wayland* win, short x0, short y0, short w, short h, const short s, const struct nk_color col) -{ - /* Bresenham's ellipses - modified to fill one quarter */ - const int a2 = (w * w) / 4; - const int b2 = (h * h) / 4; - const int fa2 = 4 * a2, fb2 = 4 * b2; - int x, y, sigma; - struct nk_vec2i pnts[3]; - if (w < 1 || h < 1) return; - if (s != 0 && s != 90 && s != 180 && s != 270) - return; - - /* Convert upper left to center */ - h = (h + 1) / 2; - w = (w + 1) / 2; - x0 += w; - y0 += h; - - pnts[0].x = x0; - pnts[0].y = y0; - pnts[2].x = x0; - pnts[2].y = y0; - - /* First half */ - for (x = 0, y = h, sigma = 2*b2+a2*(1-2*h); b2*x <= a2*y; x++) { - if (s == 180) { - pnts[1].x = x0 + x; pnts[1].y = y0 + y; - } else if (s == 270) { - pnts[1].x = x0 - x; pnts[1].y = y0 + y; - } else if (s == 0) { - pnts[1].x = x0 + x; pnts[1].y = y0 - y; - } else if (s == 90) { - pnts[1].x = x0 - x; pnts[1].y = y0 - y; - } - nk_wayland_fill_polygon(win, pnts, 3, col); - pnts[2] = pnts[1]; - if (sigma >= 0) { - sigma += fa2 * (1 - y); - y--; - } sigma += b2 * ((4 * x) + 6); - } - - /* Second half */ - for (x = w, y = 0, sigma = 2*a2+b2*(1-2*w); a2*y <= b2*x; y++) { - if (s == 180) { - pnts[1].x = x0 + x; pnts[1].y = y0 + y; - } else if (s == 270) { - pnts[1].x = x0 - x; pnts[1].y = y0 + y; - } else if (s == 0) { - pnts[1].x = x0 + x; pnts[1].y = y0 - y; - } else if (s == 90) { - pnts[1].x = x0 - x; pnts[1].y = y0 - y; - } - nk_wayland_fill_polygon(win, pnts, 3, col); - pnts[2] = pnts[1]; - if (sigma >= 0) { - sigma += fb2 * (1 - x); - x--; - } sigma += a2 * ((4 * y) + 6); - } -} - -static void nk_wayland_img_setpixel(const struct wayland_img *img, const int x0, const int y0, const struct nk_color col) -{ - unsigned int c = nk_wayland_color2int(col, img->pl); - unsigned char *ptr; - unsigned int *pixel; - NK_ASSERT(img); - if (y0 < img->h && y0 >= 0 && x0 >= 0 && x0 < img->w) { - ptr = (unsigned char *)img->pixels + (img->pitch * y0); - pixel = (unsigned int *)ptr; - - if (img->format == NK_FONT_ATLAS_ALPHA8) { - ptr[x0] = col.a; - } else { - pixel[x0] = c; - } - } -} - -static struct nk_color nk_wayland_getpixel(const struct nk_wayland* win, const int x0, const int y0) -{ - struct nk_color col = {0, 0, 0, 0}; - uint32_t *ptr; - - if (y0 < win->height && y0 >= 0 && x0 >= 0 && x0 < win->width) { - ptr = (uint32_t *)win->data + (y0 * win->width); - - col = nk_wayland_int2color(*ptr, PIXEL_LAYOUT_XRGB_8888); - } - - return col; -} - -static struct nk_color nk_wayland_img_getpixel(const struct wayland_img *img, const int x0, const int y0) -{ - struct nk_color col = {0, 0, 0, 0}; - unsigned char *ptr; - unsigned int pixel; - NK_ASSERT(img); - if (y0 < img->h && y0 >= 0 && x0 >= 0 && x0 < img->w) { - ptr = (unsigned char *)img->pixels + (img->pitch * y0); - - if (img->format == NK_FONT_ATLAS_ALPHA8) { - col.a = ptr[x0]; - col.b = col.g = col.r = 0xff; - } else { - pixel = ((unsigned int *)ptr)[x0]; - col = nk_wayland_int2color(pixel, img->pl); - } - } return col; -} - -static void nk_wayland_blendpixel(const struct nk_wayland* win, const int x0, const int y0, struct nk_color col) -{ - struct nk_color col2; - unsigned char inv_a; - if (col.a == 0) - return; - - inv_a = 0xff - col.a; - col2 = nk_wayland_getpixel(win, x0, y0); - col.r = (col.r * col.a + col2.r * inv_a) >> 8; - col.g = (col.g * col.a + col2.g * inv_a) >> 8; - col.b = (col.b * col.a + col2.b * inv_a) >> 8; - nk_wayland_ctx_setpixel(win, x0, y0, col); -} - -static void nk_wayland_img_blendpixel(const struct wayland_img *img, const int x0, const int y0, struct nk_color col) -{ - struct nk_color col2; - unsigned char inv_a; - if (col.a == 0) - return; - - inv_a = 0xff - col.a; - col2 = nk_wayland_img_getpixel(img, x0, y0); - col.r = (col.r * col.a + col2.r * inv_a) >> 8; - col.g = (col.g * col.a + col2.g * inv_a) >> 8; - col.b = (col.b * col.a + col2.b * inv_a) >> 8; - nk_wayland_img_setpixel(img, x0, y0, col); -} - -static void nk_wayland_line_horizontal(const struct nk_wayland* win, const short x0, const short y, const short x1, const struct nk_color col) -{ - /* This function is called the most. Try to optimize it a bit... - * It does not check for scissors or image borders. - * The caller has to make sure it does no exceed bounds. */ - unsigned int i, n; - unsigned int c[16]; - unsigned char *pixels = (uint8_t*)win->data; - unsigned int *ptr; - - pixels += (y * (win->width * 4)); - ptr = (unsigned int *)pixels + x0; - - n = x1 - x0; - for (i = 0; i < sizeof(c) / sizeof(c[0]); i++) - c[i] = nk_color_to_xrgb8888(col); - - while (n > 16) { - memcpy((void *)ptr, c, sizeof(c)); - n -= 16; ptr += 16; - } for (i = 0; i < n; i++) - ptr[i] = c[i]; -} - - -static void nk_wayland_scissor(struct nk_wayland* win, const float x, const float y, const float w, const float h) -{ - win->scissors.x = MIN(MAX(x, 0), WIDTH); - win->scissors.y = MIN(MAX(y, 0), HEIGHT); - win->scissors.w = MIN(MAX(w + x, 0), WIDTH); - win->scissors.h = MIN(MAX(h + y, 0), HEIGHT); -} - -static void nk_wayland_stroke_line(const struct nk_wayland* win, short x0, short y0, short x1, short y1, const unsigned int line_thickness, const struct nk_color col) -{ - short tmp; - int dy, dx, stepx, stepy; - - NK_UNUSED(line_thickness); - - dy = y1 - y0; - dx = x1 - x0; - - //printf("\n\n\n\n"); - // fast path - if (dy == 0) { - if (dx == 0 || y0 >= win->scissors.h || y0 < win->scissors.y){ - return; - } - - if (dx < 0) { - // swap x0 and x1 - tmp = x1; - x1 = x0; - x0 = tmp; - } - x1 = MIN(win->scissors.w, x1); - x0 = MIN(win->scissors.w, x0); - x1 = MAX(win->scissors.x, x1); - x0 = MAX(win->scissors.x, x0); - nk_wayland_line_horizontal(win, x0, y0, x1, col); - return; - } - if (dy < 0) { - dy = -dy; - stepy = -1; - } else stepy = 1; - - if (dx < 0) { - dx = -dx; - stepx = -1; - } else stepx = 1; - - dy <<= 1; - dx <<= 1; - - nk_wayland_ctx_setpixel(win, x0, y0, col); - if (dx > dy) { - int fraction = dy - (dx >> 1); - while (x0 != x1) { - if (fraction >= 0) { - y0 += stepy; - fraction -= dx; - } - x0 += stepx; - fraction += dy; - nk_wayland_ctx_setpixel(win, x0, y0, col); - } - } else { - int fraction = dx - (dy >> 1); - while (y0 != y1) { - if (fraction >= 0) { - x0 += stepx; - fraction -= dy; - } - y0 += stepy; - fraction += dx; - nk_wayland_ctx_setpixel(win, x0, y0, col); - } - } -} - -static void -nk_wayland_fill_rect(const struct nk_wayland* win, - const short x, const short y, const short w, const short h, - const short r, const struct nk_color col) -{ - int i; - if (r == 0) { - for (i = 0; i < h; i++) - nk_wayland_stroke_line(win, x, y + i, x + w, y + i, 1, col); - } else { - const short xc = x + r; - const short yc = y + r; - const short wc = (short)(w - 2 * r); - const short hc = (short)(h - 2 * r); - - struct nk_vec2i pnts[12]; - pnts[0].x = x; - pnts[0].y = yc; - pnts[1].x = xc; - pnts[1].y = yc; - pnts[2].x = xc; - pnts[2].y = y; - - pnts[3].x = xc + wc; - pnts[3].y = y; - pnts[4].x = xc + wc; - pnts[4].y = yc; - pnts[5].x = x + w; - pnts[5].y = yc; - - pnts[6].x = x + w; - pnts[6].y = yc + hc; - pnts[7].x = xc + wc; - pnts[7].y = yc + hc; - pnts[8].x = xc + wc; - pnts[8].y = y + h; - - pnts[9].x = xc; - pnts[9].y = y + h; - pnts[10].x = xc; - pnts[10].y = yc + hc; - pnts[11].x = x; - pnts[11].y = yc + hc; - - nk_wayland_fill_polygon(win, pnts, 12, col); - - nk_wayland_fill_arc(win, xc + wc - r, y, - (unsigned)r*2, (unsigned)r*2, 0 , col); - nk_wayland_fill_arc(win, x, y, - (unsigned)r*2, (unsigned)r*2, 90 , col); - nk_wayland_fill_arc(win, x, yc + hc - r, - (unsigned)r*2, (unsigned)r*2, 270 , col); - nk_wayland_fill_arc(win, xc + wc - r, yc + hc - r, - (unsigned)r*2, (unsigned)r*2, 180 , col); - } -} - -static void nk_wayland_stroke_arc(const struct nk_wayland* win, - short x0, short y0, short w, short h, const short s, - const short line_thickness, const struct nk_color col) -{ - /* Bresenham's ellipses - modified to draw one quarter */ - const int a2 = (w * w) / 4; - const int b2 = (h * h) / 4; - const int fa2 = 4 * a2, fb2 = 4 * b2; - int x, y, sigma; - - NK_UNUSED(line_thickness); - - if (s != 0 && s != 90 && s != 180 && s != 270) return; - if (w < 1 || h < 1) return; - - /* Convert upper left to center */ - h = (h + 1) / 2; - w = (w + 1) / 2; - x0 += w; y0 += h; - - /* First half */ - for (x = 0, y = h, sigma = 2*b2+a2*(1-2*h); b2*x <= a2*y; x++) { - if (s == 180) - nk_wayland_ctx_setpixel(win, x0 + x, y0 + y, col); - else if (s == 270) - nk_wayland_ctx_setpixel(win, x0 - x, y0 + y, col); - else if (s == 0) - nk_wayland_ctx_setpixel(win, x0 + x, y0 - y, col); - else if (s == 90) - nk_wayland_ctx_setpixel(win, x0 - x, y0 - y, col); - if (sigma >= 0) { - sigma += fa2 * (1 - y); - y--; - } sigma += b2 * ((4 * x) + 6); - } - - /* Second half */ - for (x = w, y = 0, sigma = 2*a2+b2*(1-2*w); a2*y <= b2*x; y++) { - if (s == 180) - nk_wayland_ctx_setpixel(win, x0 + x, y0 + y, col); - else if (s == 270) - nk_wayland_ctx_setpixel(win, x0 - x, y0 + y, col); - else if (s == 0) - nk_wayland_ctx_setpixel(win, x0 + x, y0 - y, col); - else if (s == 90) - nk_wayland_ctx_setpixel(win, x0 - x, y0 - y, col); - if (sigma >= 0) { - sigma += fb2 * (1 - x); - x--; - } sigma += a2 * ((4 * y) + 6); - } -} - - - - -static void nk_wayland_stroke_rect(const struct nk_wayland* win, - const short x, const short y, const short w, const short h, - const short r, const short line_thickness, const struct nk_color col) -{ - if (r == 0) { - nk_wayland_stroke_line(win, x, y, x + w, y, line_thickness, col); - nk_wayland_stroke_line(win, x, y + h, x + w, y + h, line_thickness, col); - nk_wayland_stroke_line(win, x, y, x, y + h, line_thickness, col); - nk_wayland_stroke_line(win, x + w, y, x + w, y + h, line_thickness, col); - } else { - const short xc = x + r; - const short yc = y + r; - const short wc = (short)(w - 2 * r); - const short hc = (short)(h - 2 * r); - - nk_wayland_stroke_line(win, xc, y, xc + wc, y, line_thickness, col); - nk_wayland_stroke_line(win, x + w, yc, x + w, yc + hc, line_thickness, col); - nk_wayland_stroke_line(win, xc, y + h, xc + wc, y + h, line_thickness, col); - nk_wayland_stroke_line(win, x, yc, x, yc + hc, line_thickness, col); - - nk_wayland_stroke_arc(win, xc + wc - r, y, - (unsigned)r*2, (unsigned)r*2, 0 , line_thickness, col); - nk_wayland_stroke_arc(win, x, y, - (unsigned)r*2, (unsigned)r*2, 90 , line_thickness, col); - nk_wayland_stroke_arc(win, x, yc + hc - r, - (unsigned)r*2, (unsigned)r*2, 270 , line_thickness, col); - nk_wayland_stroke_arc(win, xc + wc - r, yc + hc - r, - (unsigned)r*2, (unsigned)r*2, 180 , line_thickness, col); - } -} - -static void nk_wayland_fill_triangle(const struct nk_wayland *win, - const short x0, const short y0, const short x1, const short y1, - const short x2, const short y2, const struct nk_color col) -{ - struct nk_vec2i pnts[3]; - pnts[0].x = x0; - pnts[0].y = y0; - pnts[1].x = x1; - pnts[1].y = y1; - pnts[2].x = x2; - pnts[2].y = y2; - nk_wayland_fill_polygon(win, pnts, 3, col); -} - -static void nk_wayland_clear(const struct nk_wayland *win, const struct nk_color col) -{ - nk_wayland_fill_rect(win, 0, 0, win->width, win->height, 0, col); -} - -static void nk_wayland_fill_circle(struct nk_wayland* win, short x0, short y0, short w, short h, const struct nk_color col) -{ - /* Bresenham's ellipses */ - const int a2 = (w * w) / 4; - const int b2 = (h * h) / 4; - const int fa2 = 4 * a2, fb2 = 4 * b2; - int x, y, sigma; - - /* Convert upper left to center */ - h = (h + 1) / 2; - w = (w + 1) / 2; - x0 += w; - y0 += h; - - /* First half */ - for (x = 0, y = h, sigma = 2*b2+a2*(1-2*h); b2*x <= a2*y; x++) { - nk_wayland_stroke_line(win, x0 - x, y0 + y, x0 + x, y0 + y, 1, col); - nk_wayland_stroke_line(win, x0 - x, y0 - y, x0 + x, y0 - y, 1, col); - if (sigma >= 0) { - sigma += fa2 * (1 - y); - y--; - } sigma += b2 * ((4 * x) + 6); - } - /* Second half */ - for (x = w, y = 0, sigma = 2*a2+b2*(1-2*w); a2*y <= b2*x; y++) { - nk_wayland_stroke_line(win, x0 - x, y0 + y, x0 + x, y0 + y, 1, col); - nk_wayland_stroke_line(win, x0 - x, y0 - y, x0 + x, y0 - y, 1, col); - if (sigma >= 0) { - sigma += fb2 * (1 - x); - x--; - } sigma += a2 * ((4 * y) + 6); - } -} -/** - * Copy wayland_img into nk_wayland with scissor & stretch - */ -static void nk_wayland_copy_image(const struct nk_wayland *win, const struct wayland_img *src, - const struct nk_rect *dst_rect, - const struct nk_rect *src_rect, - const struct nk_rect *dst_scissors, - const struct nk_color *fg) -{ - short i, j; - struct nk_color col; - float xinc = src_rect->w / dst_rect->w; - float yinc = src_rect->h / dst_rect->h; - float xoff = src_rect->x, yoff = src_rect->y; - - // Simple nearest filtering rescaling - // TODO: use bilinear filter - for (j = 0; j < (short)dst_rect->h; j++) { - for (i = 0; i < (short)dst_rect->w; i++) { - if (dst_scissors) { - if (i + (int)(dst_rect->x + 0.5f) < dst_scissors->x || i + (int)(dst_rect->x + 0.5f) >= dst_scissors->w) - continue; - if (j + (int)(dst_rect->y + 0.5f) < dst_scissors->y || j + (int)(dst_rect->y + 0.5f) >= dst_scissors->h) - continue; - } - col = nk_wayland_img_getpixel(src, (int)xoff, (int) yoff); - if (col.r || col.g || col.b) - { - col.r = fg->r; - col.g = fg->g; - col.b = fg->b; - } - nk_wayland_blendpixel(win, i + (int)(dst_rect->x + 0.5f), j + (int)(dst_rect->y + 0.5f), col); - xoff += xinc; - } - xoff = src_rect->x; - yoff += yinc; - } -} - -static void nk_wayland_font_query_font_glyph(nk_handle handle, const float height, struct nk_user_font_glyph *glyph, const nk_rune codepoint, const nk_rune next_codepoint) -{ - float scale; - const struct nk_font_glyph *g; - struct nk_font *font; - NK_ASSERT(glyph); - NK_UNUSED(next_codepoint); - - font = (struct nk_font*)handle.ptr; - NK_ASSERT(font); - NK_ASSERT(font->glyphs); - if (!font || !glyph) - return; - - scale = height/font->info.height; - g = nk_font_find_glyph(font, codepoint); - glyph->width = (g->x1 - g->x0) * scale; - glyph->height = (g->y1 - g->y0) * scale; - glyph->offset = nk_vec2(g->x0 * scale, g->y0 * scale); - glyph->xadvance = (g->xadvance * scale); - glyph->uv[0] = nk_vec2(g->u0, g->v0); - glyph->uv[1] = nk_vec2(g->u1, g->v1); -} - -void nk_wayland_draw_text(const struct nk_wayland *win, const struct nk_user_font *font, const struct nk_rect rect, const char *text, const int len, const float font_height, const struct nk_color fg) -{ - float x = 0; - int text_len = 0; - nk_rune unicode = 0; - nk_rune next = 0; - int glyph_len = 0; - int next_glyph_len = 0; - struct nk_user_font_glyph g; - if (!len || !text) return; - - x = 0; - glyph_len = nk_utf_decode(text, &unicode, len); - if (!glyph_len) return; - - // draw every glyph image - while (text_len < len && glyph_len) { - struct nk_rect src_rect; - struct nk_rect dst_rect; - float char_width = 0; - if (unicode == NK_UTF_INVALID) break; - - // query currently drawn glyph information - next_glyph_len = nk_utf_decode(text + text_len + glyph_len, &next, (int)len - text_len); - nk_wayland_font_query_font_glyph(font->userdata, font_height, &g, unicode, - (next == NK_UTF_INVALID) ? '\0' : next); - - //calculate and draw glyph drawing rectangle and image - char_width = g.xadvance; - src_rect.x = g.uv[0].x * win->font_tex.w; - src_rect.y = g.uv[0].y * win->font_tex.h; - src_rect.w = g.uv[1].x * win->font_tex.w - g.uv[0].x * win->font_tex.w; - src_rect.h = g.uv[1].y * win->font_tex.h - g.uv[0].y * win->font_tex.h; - - dst_rect.x = x + g.offset.x + rect.x; - dst_rect.y = g.offset.y + rect.y; - dst_rect.w = ceilf(g.width); - dst_rect.h = ceilf(g.height); - - // Use software rescaling to blit glyph from font_text to framebuffer - nk_wayland_copy_image(win, &(win->font_tex), &dst_rect, &src_rect, &(win->scissors), &fg); - - // offset next glyph - text_len += glyph_len; - x += char_width; - glyph_len = next_glyph_len; - unicode = next; - } -} - -static void nk_wayland_render(struct nk_wayland *win, const struct nk_color clear, const unsigned char enable_clear) -{ - const struct nk_command *cmd; - const struct nk_command_text *tx; - const struct nk_command_scissor *s; - const struct nk_command_rect_filled *rf; - const struct nk_command_rect *r; - const struct nk_command_circle_filled *c; - const struct nk_command_triangle_filled *t; - const struct nk_command_line *l; - const struct nk_command_polygon_filled *p; - - if (enable_clear) - nk_wayland_clear(win, clear); - - nk_foreach(cmd, (struct nk_context*)&(win->ctx)) { - switch (cmd->type) { - case NK_COMMAND_NOP: - //printf("NK_COMMAND_NOP \n"); - break; - - case NK_COMMAND_SCISSOR: - s = (const struct nk_command_scissor*)cmd; - nk_wayland_scissor(win, s->x, s->y, s->w, s->h); - break; - - case NK_COMMAND_LINE: - l = (const struct nk_command_line *)cmd; - nk_wayland_stroke_line(win, l->begin.x, l->begin.y, l->end.x, l->end.y, l->line_thickness, l->color); - break; - - case NK_COMMAND_RECT: - r = (const struct nk_command_rect *)cmd; - nk_wayland_stroke_rect(win, r->x, r->y, r->w, r->h, (unsigned short)r->rounding, r->line_thickness, r->color); - break; - - case NK_COMMAND_RECT_FILLED: - rf = (const struct nk_command_rect_filled *)cmd; - nk_wayland_fill_rect(win, rf->x, rf->y, rf->w, rf->h, (unsigned short)rf->rounding, rf->color); - break; - - case NK_COMMAND_CIRCLE: - // printf("NK_COMMAND_CIRCLE \n"); - //const struct nk_command_circle *c = (const struct nk_command_circle *)cmd; - //nk_rawfb_stroke_circle(rawfb, c->x, c->y, c->w, c->h, c->line_thickness, c->color); - break; - - case NK_COMMAND_CIRCLE_FILLED: - c = (const struct nk_command_circle_filled *)cmd; - nk_wayland_fill_circle(win, c->x, c->y, c->w, c->h, c->color); - - //const struct nk_command_circle_filled *c = (const struct nk_command_circle_filled *)cmd; - //nk_rawfb_fill_circle(rawfb, c->x, c->y, c->w, c->h, c->color); - break; - - case NK_COMMAND_TRIANGLE: - //printf("NK_COMMAND_TRIANGLE \n"); - //const struct nk_command_triangle*t = (const struct nk_command_triangle*)cmd; - //nk_rawfb_stroke_triangle(rawfb, t->a.x, t->a.y, t->b.x, t->b.y, t->c.x, t->c.y, t->line_thickness, t->color); - break; - - case NK_COMMAND_TRIANGLE_FILLED: - t = (const struct nk_command_triangle_filled *)cmd; - nk_wayland_fill_triangle(win, t->a.x, t->a.y, t->b.x, t->b.y, t->c.x, t->c.y, t->color); - break; - - case NK_COMMAND_POLYGON: - // printf("NK_COMMAND_POLYGON \n"); - //const struct nk_command_polygon *p =(const struct nk_command_polygon*)cmd; - //nk_rawfb_stroke_polygon(rawfb, p->points, p->point_count, p->line_thickness,p->color); - break; - - case NK_COMMAND_POLYGON_FILLED: - // printf("NK_COMMAND_POLYGON_FILLED \n"); - p = (const struct nk_command_polygon_filled *)cmd; - nk_wayland_fill_polygon(win, p->points, p->point_count, p->color); - break; - - case NK_COMMAND_POLYLINE: - // printf("NK_COMMAND_POLYLINE \n"); - //const struct nk_command_polyline *p = (const struct nk_command_polyline *)cmd; - //nk_rawfb_stroke_polyline(rawfb, p->points, p->point_count, p->line_thickness, p->color); - break; - - case NK_COMMAND_TEXT: - tx = (const struct nk_command_text*)cmd; - nk_wayland_draw_text(win, tx->font, nk_rect(tx->x, tx->y, tx->w, tx->h), tx->string, tx->length, tx->height, tx->foreground); - break; - - case NK_COMMAND_CURVE: - // printf("NK_COMMAND_CURVE \n"); - //const struct nk_command_curve *q = (const struct nk_command_curve *)cmd; - //nk_rawfb_stroke_curve(rawfb, q->begin, q->ctrl[0], q->ctrl[1], q->end, 22, q->line_thickness, q->color); - break; - - case NK_COMMAND_RECT_MULTI_COLOR: - // printf("NK_COMMAND_RECT_MULTI_COLOR \n"); - //const struct nk_command_rect_multi_color *q = (const struct nk_command_rect_multi_color *)cmd; - //nk_rawfb_draw_rect_multi_color(rawfb, q->x, q->y, q->w, q->h, q->left, q->top, q->right, q->bottom); - break; - - case NK_COMMAND_IMAGE: - //printf("NK_COMMAND_IMAGE \n"); - // const struct nk_command_image *q = (const struct nk_command_image *)cmd; - // nk_rawfb_drawimage(rawfb, q->x, q->y, q->w, q->h, &q->img, &q->col); - break; - - case NK_COMMAND_ARC: - printf("NK_COMMAND_ARC \n"); - assert(0 && "NK_COMMAND_ARC not implemented\n"); - break; - - case NK_COMMAND_ARC_FILLED: - printf("NK_COMMAND_ARC \n"); - assert(0 && "NK_COMMAND_ARC_FILLED not implemented\n"); - break; - - default: - printf("unhandled OP: %d \n", cmd->type); - break; - } - } nk_clear(&(win->ctx)); -} - -#endif From 31b5729d66403e4ca1b6ff6df2958c49f3bc2c8d Mon Sep 17 00:00:00 2001 From: Rob Loach Date: Tue, 9 Apr 2024 14:00:50 -0400 Subject: [PATCH 106/106] [overview] Fix show_markers boolean type (#633) --- demo/common/overview.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demo/common/overview.c b/demo/common/overview.c index f5572f8..e008a47 100644 --- a/demo/common/overview.c +++ b/demo/common/overview.c @@ -633,7 +633,7 @@ overview(struct nk_context *ctx) float id = 0; static int col_index = -1; static int line_index = -1; - static int show_markers = nk_true; + static nk_bool show_markers = nk_true; float step = (2*3.141592654f) / 32; int i;