Replaced settings menu with a more powerful ImGUI implementation.

This commit is contained in:
David Salvisberg 2015-07-14 11:41:31 +02:00
parent 733a7fadda
commit 9e9c000dfd
18 changed files with 19720 additions and 680 deletions

View File

@ -157,6 +157,12 @@ set(MAIN_HEADERS
src/sharedmidistate.h src/sharedmidistate.h
src/fluid-fun.h src/fluid-fun.h
src/sdl-util.h src/sdl-util.h
src/imgui/imconfig.h
src/imgui/imgui.h
src/imgui/imgui_impl_sdl.h
src/imgui/stb_rect_pack.h
src/imgui/stb_textedit.h
src/imgui/stb_truetype.h
) )
set(MAIN_SOURCE set(MAIN_SOURCE
@ -203,6 +209,8 @@ set(MAIN_SOURCE
src/autotilesvx.cpp src/autotilesvx.cpp
src/midisource.cpp src/midisource.cpp
src/fluid-fun.cpp src/fluid-fun.cpp
src/imgui/imgui.cpp
src/imgui/imgui_impl_sdl.cpp
) )
source_group("MKXP Source" FILES ${MAIN_SOURCE} ${MAIN_HEADERS}) source_group("MKXP Source" FILES ${MAIN_SOURCE} ${MAIN_HEADERS})

40
src/bundledfont.h Normal file
View File

@ -0,0 +1,40 @@
/*
** bundledfont.h
**
** This file is part of mkxp.
**
** Copyright (C) 2014 Jonas Kulla <Nyocurio@gmail.com>
**
** mkxp is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 2 of the License, or
** (at your option) any later version.
**
** mkxp is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with mkxp. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef BUNDLEDFONT_H
#define BUNDLEDFONT_H
#define BUNDLED_FONT liberation
#define BUNDLED_FONT_DECL(FONT) \
extern unsigned char assets_##FONT##_ttf[]; \
extern unsigned int assets_##FONT##_ttf_len;
BUNDLED_FONT_DECL(liberation)
#define BUNDLED_FONT_D(f) assets_## f ##_ttf
#define BUNDLED_FONT_L(f) assets_## f ##_ttf_len
// Go fuck yourself CPP
#define BNDL_F_D(f) BUNDLED_FONT_D(f)
#define BNDL_F_L(f) BUNDLED_FONT_L(f)
#endif

View File

@ -133,6 +133,7 @@ typedef std::vector<std::string> StringVec;
namespace po = boost::program_options; namespace po = boost::program_options;
#define CONF_FILE "mkxp.conf" #define CONF_FILE "mkxp.conf"
#define CONF_FILE_TMP "mkxp-conf.tmp"
Config::Config() Config::Config()
: rgssVersion(0), : rgssVersion(0),
@ -160,6 +161,184 @@ Config::Config()
SE.sourceCount = 6; SE.sourceCount = 6;
} }
/* Pre-convert value to string since we don't care about the type at this point anymore */
static bool updateConfigFileValue(const char *key, const char *value)
{
/* Open files for reading and writing */
std::ifstream confRead;
confRead.open(CONF_FILE);
std::ofstream confWrite;
confWrite.open(CONF_FILE_TMP, std::ofstream::trunc);
if(confWrite && confRead)
{
/* Buffer to store config file lines */
char buf[512];
bool valWritten = false;
while(!confRead.eof())
{
/* Get next line */
confRead.getline(buf, 512);
if(confRead.fail())
{
/* This means we either encountered an empty line,
/* which is fine, or the line was too big. Maybe
/* handle the case of long lines in the future? */
}
else if(strncmp(buf, key, strlen(key)) == 0)
{
/* This is the line we want to overwrite. For now
/* discard duplicate lines of the same key */
if(valWritten)
continue;
confWrite << key << '=' << value;
valWritten = true;
}
else
{
/* Just copy the old line into the new file,
/* use gcount()-1 to not copy null character
/* but only if not EOF */
assert(confRead.gcount() > 0 && confRead.gcount() < 512);
int trim = confRead.eof() ? 0 : 1;
confWrite.write(buf, confRead.gcount()-trim);
}
if(!confRead.eof())
confWrite << '\n';
}
confRead.close();
confWrite.close();
/* Backup old config file and move the new one into place */
remove(CONF_FILE);
rename(CONF_FILE_TMP, CONF_FILE);
return true;
}
Debug() << CONF_FILE": Failed to update config file.\n";
if(confRead.is_open())
confRead.close();
if(confWrite.is_open())
confWrite.close();
return false;
}
bool Config::store(const char *key, int value)
{
std::ifstream confFileRead;
confFileRead.open(CONF_FILE);
int curValue;
if(confFileRead)
{
/* First read the config file to get the currently stored value
/* and check whether it's in the config file at all */
po::options_description podesc;
po::variables_map vm;
podesc.add_options()(key, po::value<int>()->required());
try
{
try
{
po::store(po::parse_config_file(confFileRead, podesc, true), vm);
po::notify(vm);
curValue = vm[key].as<int>();
}
catch(po::multiple_occurrences e)
{
/* This is fine we're gonna remove the duplicates when storing */
curValue = ~value;
}
if(curValue == value)
{
/* We don't need to store anything */
return true;
}
else
{
/* Update the relevant config file line */
char num[21];
snprintf(num, 21, "%d", value);
return updateConfigFileValue(key, num);
}
} catch (...) {}
confFileRead.close();
}
/* Open file for writing */
std::ofstream confFileWrite(CONF_FILE, std::ofstream::app);
if(confFileWrite)
{
/* Append new config line */
confFileWrite << '\n' << key << '=' << value;
confFileWrite.close();
return true;
}
/* Some error with opening the file occured */
Debug() << CONF_FILE": Failed to update config file.\n";
return false;
}
bool Config::store(const char *key, bool value)
{
std::ifstream confFileRead;
confFileRead.open(CONF_FILE);
bool curValue;
if(confFileRead)
{
/* First read the config file to get the currently stored value */
po::options_description podesc;
po::variables_map vm;
podesc.add_options()(key, po::value<bool>()->required());
try
{
try
{
po::store(po::parse_config_file(confFileRead, podesc, true), vm);
po::notify(vm);
curValue = vm[key].as<bool>();
}
catch(po::multiple_occurrences &e)
{
/* This is fine we're gonna remove the duplicates when storing */
curValue = !value;
}
if(curValue == value)
{
/* We don't need to store anything */
return true;
}
else
{
/* Update the relevant config file line */
return updateConfigFileValue(key, value ? "true" : "false");
}
} catch (...) {}
confFileRead.close();
}
/* Open file for writing */
std::ofstream confFileWrite(CONF_FILE, std::ofstream::app);
if(confFileWrite)
{
/* Append new config line */
confFileWrite << '\n' << key << '=' << std::boolalpha << value;
confFileWrite.close();
return true;
}
/* Some error with opening the file occured */
Debug() << CONF_FILE": Failed to update config file.\n";
return false;
}
void Config::read(int argc, char *argv[]) void Config::read(int argc, char *argv[])
{ {
#define PO_DESC_ALL \ #define PO_DESC_ALL \

View File

@ -94,6 +94,8 @@ struct Config
Config(); Config();
void read(int argc, char *argv[]); void read(int argc, char *argv[]);
bool store(const char* key, int value);
bool store(const char* key, bool value);
void readGameINI(); void readGameINI();
}; };

View File

@ -30,7 +30,6 @@
#include "sharedstate.h" #include "sharedstate.h"
#include "graphics.h" #include "graphics.h"
#include "settingsmenu.h"
#include "debugwriter.h" #include "debugwriter.h"
#include <string.h> #include <string.h>
@ -47,26 +46,13 @@ EventThread::MouseState EventThread::mouseState =
0, 0, false, { false } 0, 0, false, { false }
}; };
/* User event codes */ uint32_t EventThread::UsrIdStart = -1;
enum
{
REQUEST_SETFULLSCREEN = 0,
REQUEST_WINRESIZE,
REQUEST_MESSAGEBOX,
REQUEST_SETCURSORVISIBLE,
UPDATE_FPS,
EVENT_COUNT
};
static uint32_t usrIdStart;
bool EventThread::allocUserEvents() bool EventThread::allocUserEvents()
{ {
usrIdStart = SDL_RegisterEvents(EVENT_COUNT); EventThread::UsrIdStart = SDL_RegisterEvents(EVENT_COUNT);
if (usrIdStart == (uint32_t) -1) if (EventThread::UsrIdStart == (uint32_t) -1)
return false; return false;
return true; return true;
@ -74,7 +60,8 @@ bool EventThread::allocUserEvents()
EventThread::EventThread() EventThread::EventThread()
: fullscreen(false), : fullscreen(false),
showCursor(false) showCursor(false),
sMenu(0)
{} {}
void EventThread::process(RGSSThreadData &rtData) void EventThread::process(RGSSThreadData &rtData)
@ -112,8 +99,6 @@ void EventThread::process(RGSSThreadData &rtData)
bool resetting = false; bool resetting = false;
SettingsMenu *sMenu = 0;
while (true) while (true)
{ {
if (!SDL_WaitEvent(&event)) if (!SDL_WaitEvent(&event))
@ -357,7 +342,7 @@ void EventThread::process(RGSSThreadData &rtData)
default : default :
/* Handle user events */ /* Handle user events */
switch(event.type - usrIdStart) switch(event.type - EventThread::UsrIdStart)
{ {
case REQUEST_SETFULLSCREEN : case REQUEST_SETFULLSCREEN :
setFullscreen(win, static_cast<bool>(event.user.code)); setFullscreen(win, static_cast<bool>(event.user.code));
@ -419,7 +404,7 @@ void EventThread::cleanup()
SDL_Event event; SDL_Event event;
while (SDL_PollEvent(&event)) while (SDL_PollEvent(&event))
if ((event.type - usrIdStart) == REQUEST_MESSAGEBOX) if ((event.type - EventThread::UsrIdStart) == REQUEST_MESSAGEBOX)
free(event.user.data1); free(event.user.data1);
} }
@ -458,7 +443,7 @@ void EventThread::requestFullscreenMode(bool mode)
return; return;
SDL_Event event; SDL_Event event;
event.type = usrIdStart + REQUEST_SETFULLSCREEN; event.type = EventThread::UsrIdStart + REQUEST_SETFULLSCREEN;
event.user.code = static_cast<Sint32>(mode); event.user.code = static_cast<Sint32>(mode);
SDL_PushEvent(&event); SDL_PushEvent(&event);
} }
@ -466,7 +451,7 @@ void EventThread::requestFullscreenMode(bool mode)
void EventThread::requestWindowResize(int width, int height) void EventThread::requestWindowResize(int width, int height)
{ {
SDL_Event event; SDL_Event event;
event.type = usrIdStart + REQUEST_WINRESIZE; event.type = EventThread::UsrIdStart + REQUEST_WINRESIZE;
event.window.data1 = width; event.window.data1 = width;
event.window.data2 = height; event.window.data2 = height;
SDL_PushEvent(&event); SDL_PushEvent(&event);
@ -475,7 +460,7 @@ void EventThread::requestWindowResize(int width, int height)
void EventThread::requestShowCursor(bool mode) void EventThread::requestShowCursor(bool mode)
{ {
SDL_Event event; SDL_Event event;
event.type = usrIdStart + REQUEST_SETCURSORVISIBLE; event.type = EventThread::UsrIdStart + REQUEST_SETCURSORVISIBLE;
event.user.code = mode; event.user.code = mode;
SDL_PushEvent(&event); SDL_PushEvent(&event);
} }
@ -487,7 +472,7 @@ void EventThread::showMessageBox(const char *body, int flags)
SDL_Event event; SDL_Event event;
event.user.code = flags; event.user.code = flags;
event.user.data1 = strdup(body); event.user.data1 = strdup(body);
event.type = usrIdStart + REQUEST_MESSAGEBOX; event.type = EventThread::UsrIdStart + REQUEST_MESSAGEBOX;
SDL_PushEvent(&event); SDL_PushEvent(&event);
/* Keep repainting screen while box is open */ /* Keep repainting screen while box is open */
@ -508,6 +493,14 @@ bool EventThread::getShowCursor() const
void EventThread::notifyFrame() void EventThread::notifyFrame()
{ {
/* If settings menu is active send it updates to redraw its frames */
if (sMenu)
{
SDL_Event event;
event.user.type = EventThread::UsrIdStart + UPDATE_POPUP;
SDL_PushEvent(&event);
}
if (!fps.displaying) if (!fps.displaying)
return; return;
@ -541,6 +534,6 @@ void EventThread::notifyFrame()
SDL_Event event; SDL_Event event;
event.user.code = avgFPS; event.user.code = avgFPS;
event.user.type = usrIdStart + UPDATE_FPS; event.user.type = EventThread::UsrIdStart + UPDATE_FPS;
SDL_PushEvent(&event); SDL_PushEvent(&event);
} }

View File

@ -26,6 +26,7 @@
#include "etc-internal.h" #include "etc-internal.h"
#include "sdl-util.h" #include "sdl-util.h"
#include "keybindings.h" #include "keybindings.h"
#include "settingsmenu.h"
#include <SDL_scancode.h> #include <SDL_scancode.h>
#include <SDL_joystick.h> #include <SDL_joystick.h>
@ -62,6 +63,7 @@ public:
}; };
static MouseState mouseState; static MouseState mouseState;
static uint32_t UsrIdStart;
static bool allocUserEvents(); static bool allocUserEvents();
@ -85,6 +87,20 @@ public:
/* RGSS thread calls this once per frame */ /* RGSS thread calls this once per frame */
void notifyFrame(); void notifyFrame();
/* User event codes */
enum
{
REQUEST_SETFULLSCREEN = 0,
REQUEST_WINRESIZE,
REQUEST_MESSAGEBOX,
REQUEST_SETCURSORVISIBLE,
UPDATE_FPS,
UPDATE_POPUP,
EVENT_COUNT
};
private: private:
void resetInputStates(); void resetInputStates();
void setFullscreen(SDL_Window *, bool mode); void setFullscreen(SDL_Window *, bool mode);
@ -92,6 +108,7 @@ private:
bool fullscreen; bool fullscreen;
bool showCursor; bool showCursor;
SettingsMenu *sMenu;
AtomicFlag msgBoxDone; AtomicFlag msgBoxDone;
struct struct

View File

@ -27,27 +27,13 @@
#include "boost-hash.h" #include "boost-hash.h"
#include "util.h" #include "util.h"
#include "config.h" #include "config.h"
#include "bundledfont.h"
#include <string> #include <string>
#include <utility> #include <utility>
#include <SDL_ttf.h> #include <SDL_ttf.h>
#define BUNDLED_FONT liberation
#define BUNDLED_FONT_DECL(FONT) \
extern unsigned char assets_##FONT##_ttf[]; \
extern unsigned int assets_##FONT##_ttf_len;
BUNDLED_FONT_DECL(liberation)
#define BUNDLED_FONT_D(f) assets_## f ##_ttf
#define BUNDLED_FONT_L(f) assets_## f ##_ttf_len
// Go fuck yourself CPP
#define BNDL_F_D(f) BUNDLED_FONT_D(f)
#define BNDL_F_L(f) BUNDLED_FONT_L(f)
typedef std::pair<std::string, int> FontKey; typedef std::pair<std::string, int> FontKey;
static SDL_RWops *openBundledFont() static SDL_RWops *openBundledFont()

View File

@ -73,6 +73,8 @@ typedef void (APIENTRYP _PFNGLDELETESHADERPROC) (GLuint shader);
typedef void (APIENTRYP _PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar* const* strings, const GLint* lengths); typedef void (APIENTRYP _PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar* const* strings, const GLint* lengths);
typedef void (APIENTRYP _PFNGLCOMPILESHADERPROC) (GLuint shader); typedef void (APIENTRYP _PFNGLCOMPILESHADERPROC) (GLuint shader);
typedef void (APIENTRYP _PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader); typedef void (APIENTRYP _PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader);
typedef void (APIENTRYP _PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader);
typedef GLint (APIENTRYP _PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar * name);
typedef void (APIENTRYP _PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint* param); typedef void (APIENTRYP _PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint* param);
typedef void (APIENTRYP _PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei* length, GLchar* infoLog); typedef void (APIENTRYP _PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei* length, GLchar* infoLog);
@ -110,6 +112,11 @@ typedef void (APIENTRYP _PFNGLGENVERTEXARRAYSPROC) (GLsizei n, GLuint* arrays);
typedef void (APIENTRYP _PFNGLDELETEVERTEXARRAYSPROC) (GLsizei n, const GLuint* arrays); typedef void (APIENTRYP _PFNGLDELETEVERTEXARRAYSPROC) (GLsizei n, const GLuint* arrays);
typedef void (APIENTRYP _PFNGLBINDVERTEXARRAYPROC) (GLuint array); typedef void (APIENTRYP _PFNGLBINDVERTEXARRAYPROC) (GLuint array);
/* Map/Unmap buffer */
typedef void * (APIENTRYP _PFNGLMAPBUFFERPROC) (GLenum target, GLenum access);
typedef GLboolean (APIENTRYP _PFNGLUNMAPBUFFERPROC) (GLenum target);
typedef void (APIENTRYP _PFNGLDRAWARRAYSPROC) (GLenum mode, GLint first, GLsizei count);
#ifdef GLES2_HEADER #ifdef GLES2_HEADER
#define GL_NUM_EXTENSIONS 0x821D #define GL_NUM_EXTENSIONS 0x821D
#define GL_READ_FRAMEBUFFER 0x8CA8 #define GL_READ_FRAMEBUFFER 0x8CA8
@ -153,6 +160,8 @@ typedef void (APIENTRYP _PFNGLBINDVERTEXARRAYPROC) (GLuint array);
GL_FUN(ShaderSource, _PFNGLSHADERSOURCEPROC) \ GL_FUN(ShaderSource, _PFNGLSHADERSOURCEPROC) \
GL_FUN(CompileShader, _PFNGLCOMPILESHADERPROC) \ GL_FUN(CompileShader, _PFNGLCOMPILESHADERPROC) \
GL_FUN(AttachShader, _PFNGLATTACHSHADERPROC) \ GL_FUN(AttachShader, _PFNGLATTACHSHADERPROC) \
GL_FUN(DetachShader, _PFNGLDETACHSHADERPROC) \
GL_FUN(GetAttribLocation, _PFNGLGETATTRIBLOCATIONPROC) \
GL_FUN(GetShaderiv, _PFNGLGETSHADERIVPROC) \ GL_FUN(GetShaderiv, _PFNGLGETSHADERIVPROC) \
GL_FUN(GetShaderInfoLog, _PFNGLGETSHADERINFOLOGPROC) \ GL_FUN(GetShaderInfoLog, _PFNGLGETSHADERINFOLOGPROC) \
/* Program */ \ /* Program */ \
@ -173,7 +182,11 @@ typedef void (APIENTRYP _PFNGLBINDVERTEXARRAYPROC) (GLuint array);
GL_FUN(BindAttribLocation, _PFNGLBINDATTRIBLOCATIONPROC) \ GL_FUN(BindAttribLocation, _PFNGLBINDATTRIBLOCATIONPROC) \
GL_FUN(EnableVertexAttribArray, _PFNGLENABLEVERTEXATTRIBARRAYPROC) \ GL_FUN(EnableVertexAttribArray, _PFNGLENABLEVERTEXATTRIBARRAYPROC) \
GL_FUN(DisableVertexAttribArray, _PFNGLDISABLEVERTEXATTRIBARRAYPROC) \ GL_FUN(DisableVertexAttribArray, _PFNGLDISABLEVERTEXATTRIBARRAYPROC) \
GL_FUN(VertexAttribPointer, _PFNGLVERTEXATTRIBPOINTERPROC) GL_FUN(VertexAttribPointer, _PFNGLVERTEXATTRIBPOINTERPROC) \
/* Map/Unmap buffer */ \
GL_FUN(MapBuffer, _PFNGLMAPBUFFERPROC) \
GL_FUN(UnmapBuffer, _PFNGLUNMAPBUFFERPROC) \
GL_FUN(DrawArrays, _PFNGLDRAWARRAYSPROC)
#define GL_FBO_FUN \ #define GL_FBO_FUN \
/* Framebuffer object */ \ /* Framebuffer object */ \

21
src/imgui/LICENSE Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014-2015 Omar Cornut and ImGui contributors
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.

56
src/imgui/imconfig.h Normal file
View File

@ -0,0 +1,56 @@
//-----------------------------------------------------------------------------
// USER IMPLEMENTATION
// This file contains compile-time options for ImGui.
// Other options (memory allocation overrides, callbacks, etc.) can be set at runtime via the ImGuiIO structure - ImGui::GetIO().
//-----------------------------------------------------------------------------
#pragma once
//---- Define assertion handler. Defaults to calling assert().
//#define IM_ASSERT(_EXPR) MyAssert(_EXPR)
//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows.
//#define IMGUI_API __declspec( dllexport )
//#define IMGUI_API __declspec( dllimport )
//---- Include imgui_user.inl at the end of imgui.cpp so you can include code that extends ImGui using its private data/functions.
//#define IMGUI_INCLUDE_IMGUI_USER_INL
//---- Include imgui_user.h at the end of imgui.h
//#define IMGUI_INCLUDE_IMGUI_USER_H
//---- Don't implement default handlers for Windows (so as not to link with OpenClipboard() and others Win32 functions)
//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS
//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS
//---- Don't implement help and test window functionality (ShowUserGuide()/ShowStyleEditor()/ShowTestWindow() methods will be empty)
#define IMGUI_DISABLE_TEST_WINDOWS
//---- Don't define obsolete functions names
#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
//---- Implement STB libraries in a namespace to avoid conflicts
#define IMGUI_STB_NAMESPACE ImStb
//---- Define constructor and implicit cast operators to convert back<>forth from your math types and ImVec2/ImVec4.
/*
#define IM_VEC2_CLASS_EXTRA \
ImVec2(const MyVec2& f) { x = f.x; y = f.y; } \
operator MyVec2() const { return MyVec2(x,y); }
#define IM_VEC4_CLASS_EXTRA \
ImVec4(const MyVec4& f) { x = f.x; y = f.y; z = f.z; w = f.w; } \
operator MyVec4() const { return MyVec4(x,y,z,w); }
*/
//---- Freely implement extra functions within the ImGui:: namespace.
//---- Declare helpers or widgets implemented in imgui_user.inl or elsewhere, so end-user doesn't need to include multiple files.
//---- e.g. you can create variants of the ImGui::Value() helper for your low-level math types, or your own widgets/helpers.
/*
namespace ImGui
{
void Value(const char* prefix, const MyVec2& v, const char* float_format = NULL);
void Value(const char* prefix, const MyVec4& v, const char* float_format = NULL);
}
*/

13007
src/imgui/imgui.cpp Normal file

File diff suppressed because it is too large Load Diff

1175
src/imgui/imgui.h Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,362 @@
// ImGui SDL2 binding with OpenGL
// https://github.com/ocornut/imgui
#include <SDL.h>
#include <SDL_syswm.h>
#include "gl-fun.h"
#include "imgui/imgui.h"
#include "imgui/imgui_impl_sdl.h"
// Data
static double g_Time = 0.0f;
static bool g_MousePressed[3] = { false, false, false };
static float g_MouseWheel = 0.0f;
static GLuint g_FontTexture = 0;
static int g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0;
static int g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0;
static int g_AttribLocationPosition = 0, g_AttribLocationUV = 0, g_AttribLocationColor = 0;
static int g_VboSize = 0;
static unsigned int g_VboHandle = 0, g_VaoHandle = 0;
// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
// If text or lines are blurry when integrating ImGui in your engine:
// - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
static void ImGui_ImplSdl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
{
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
GLint last_program, last_texture;
gl.GetIntegerv(GL_CURRENT_PROGRAM, &last_program);
gl.GetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
gl.Enable(GL_BLEND);
gl.BlendEquation(GL_FUNC_ADD);
gl.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
gl.Disable(GL_CULL_FACE);
gl.Disable(GL_DEPTH_TEST);
gl.Enable(GL_SCISSOR_TEST);
gl.ActiveTexture(GL_TEXTURE0);
// Setup orthographic projection matrix
const float width = ImGui::GetIO().DisplaySize.x;
const float height = ImGui::GetIO().DisplaySize.y;
const float ortho_projection[4][4] =
{
{ 2.0f/width, 0.0f, 0.0f, 0.0f },
{ 0.0f, 2.0f/-height, 0.0f, 0.0f },
{ 0.0f, 0.0f, -1.0f, 0.0f },
{ -1.0f, 1.0f, 0.0f, 1.0f },
};
gl.UseProgram(g_ShaderHandle);
gl.Uniform1i(g_AttribLocationTex, 0);
gl.UniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
// Grow our buffer according to what we need
int total_vtx_count = 0;
for (int n = 0; n < cmd_lists_count; n++)
total_vtx_count += cmd_lists[n]->vtx_buffer.size();
gl.BindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
int needed_vtx_size = total_vtx_count * sizeof(ImDrawVert);
if (g_VboSize < needed_vtx_size)
{
g_VboSize = needed_vtx_size + 5000 * sizeof(ImDrawVert); // Grow buffer
gl.BufferData(GL_ARRAY_BUFFER, (GLsizeiptr)g_VboSize, NULL, GL_STREAM_DRAW);
}
// Copy and convert all vertices into a single contiguous buffer
unsigned char* buffer_data = (unsigned char*)gl.MapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
if (!buffer_data)
return;
for (int n = 0; n < cmd_lists_count; n++)
{
const ImDrawList* cmd_list = cmd_lists[n];
memcpy(buffer_data, &cmd_list->vtx_buffer[0], cmd_list->vtx_buffer.size() * sizeof(ImDrawVert));
buffer_data += cmd_list->vtx_buffer.size() * sizeof(ImDrawVert);
}
gl.UnmapBuffer(GL_ARRAY_BUFFER);
gl.BindBuffer(GL_ARRAY_BUFFER, 0);
gl.BindVertexArray(g_VaoHandle);
int cmd_offset = 0;
for (int n = 0; n < cmd_lists_count; n++)
{
const ImDrawList* cmd_list = cmd_lists[n];
int vtx_offset = cmd_offset;
const ImDrawCmd* pcmd_end = cmd_list->commands.end();
for (const ImDrawCmd* pcmd = cmd_list->commands.begin(); pcmd != pcmd_end; pcmd++)
{
if (pcmd->user_callback)
{
pcmd->user_callback(cmd_list, pcmd);
}
else
{
gl.BindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->texture_id);
gl.Scissor((int)pcmd->clip_rect.x, (int)(height - pcmd->clip_rect.w), (int)(pcmd->clip_rect.z - pcmd->clip_rect.x), (int)(pcmd->clip_rect.w - pcmd->clip_rect.y));
gl.DrawArrays(GL_TRIANGLES, vtx_offset, pcmd->vtx_count);
}
vtx_offset += pcmd->vtx_count;
}
cmd_offset = vtx_offset;
}
// Restore modified state
gl.BindVertexArray(0);
gl.UseProgram(last_program);
gl.Disable(GL_SCISSOR_TEST);
gl.BindTexture(GL_TEXTURE_2D, last_texture);
}
static const char* ImGui_ImplSdl_GetClipboardText()
{
return SDL_GetClipboardText();
}
static void ImGui_ImplSdl_SetClipboardText(const char* text)
{
SDL_SetClipboardText(text);
}
bool ImGui_ImplSdl_ProcessEvent(const SDL_Event &event)
{
ImGuiIO& io = ImGui::GetIO();
switch (event.type)
{
case SDL_MOUSEWHEEL:
{
if (event.wheel.y > 0)
g_MouseWheel = 1;
if (event.wheel.y < 0)
g_MouseWheel = -1;
return true;
}
case SDL_MOUSEBUTTONDOWN:
{
if (event.button.button == SDL_BUTTON_LEFT) g_MousePressed[0] = true;
if (event.button.button == SDL_BUTTON_RIGHT) g_MousePressed[1] = true;
if (event.button.button == SDL_BUTTON_MIDDLE) g_MousePressed[2] = true;
return true;
}
case SDL_TEXTINPUT:
{
ImGuiIO& io = ImGui::GetIO();
const char * text = event.text.text;
for(int i=0; i<16; i++)
{
char key = text[i];
if(key>31 && key<256)
{
io.AddInputCharacter(key);
}
if(key == '\0')
{
break;
}
}
return true;
}
case SDL_KEYDOWN:
case SDL_KEYUP:
{
int key = SDL_GetScancodeFromKey(event.key.keysym.sym);
io.KeysDown[key] = (event.type == SDL_KEYDOWN);
io.KeyShift = ((SDL_GetModState() & KMOD_SHIFT) != 0);
io.KeyCtrl = ((SDL_GetModState() & KMOD_CTRL) != 0);
io.KeyAlt = ((SDL_GetModState() & KMOD_ALT) != 0);
return true;
}
}
return false;
}
void ImGui_ImplSdl_CreateFontsTexture()
{
ImGuiIO& io = ImGui::GetIO();
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits for OpenGL3 demo because it is more likely to be compatible with user's existing shader.
gl.GenTextures(1, &g_FontTexture);
gl.BindTexture(GL_TEXTURE_2D, g_FontTexture);
gl.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
gl.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
gl.TexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
// Store our identifier
io.Fonts->TexID = (void *)(intptr_t)g_FontTexture;
// Cleanup (don't clear the input data if you want to append new fonts later)
io.Fonts->ClearInputData();
io.Fonts->ClearTexData();
}
bool ImGui_ImplSdl_CreateDeviceObjects()
{
const GLchar *vertex_shader =
"#version 130\n"
"uniform mat4 ProjMtx;\n"
"in vec2 Position;\n"
"in vec2 UV;\n"
"in vec4 Color;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* fragment_shader =
"#version 130\n"
"uniform sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n"
"}\n";
g_ShaderHandle = gl.CreateProgram();
g_VertHandle = gl.CreateShader(GL_VERTEX_SHADER);
g_FragHandle = gl.CreateShader(GL_FRAGMENT_SHADER);
gl.ShaderSource(g_VertHandle, 1, &vertex_shader, 0);
gl.ShaderSource(g_FragHandle, 1, &fragment_shader, 0);
gl.CompileShader(g_VertHandle);
gl.CompileShader(g_FragHandle);
gl.AttachShader(g_ShaderHandle, g_VertHandle);
gl.AttachShader(g_ShaderHandle, g_FragHandle);
gl.LinkProgram(g_ShaderHandle);
g_AttribLocationTex = gl.GetUniformLocation(g_ShaderHandle, "Texture");
g_AttribLocationProjMtx = gl.GetUniformLocation(g_ShaderHandle, "ProjMtx");
g_AttribLocationPosition = gl.GetAttribLocation(g_ShaderHandle, "Position");
g_AttribLocationUV = gl.GetAttribLocation(g_ShaderHandle, "UV");
g_AttribLocationColor = gl.GetAttribLocation(g_ShaderHandle, "Color");
gl.GenBuffers(1, &g_VboHandle);
gl.GenVertexArrays(1, &g_VaoHandle);
gl.BindVertexArray(g_VaoHandle);
gl.BindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
gl.EnableVertexAttribArray(g_AttribLocationPosition);
gl.EnableVertexAttribArray(g_AttribLocationUV);
gl.EnableVertexAttribArray(g_AttribLocationColor);
#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
gl.VertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos));
gl.VertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv));
gl.VertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col));
#undef OFFSETOF
gl.BindVertexArray(0);
gl.BindBuffer(GL_ARRAY_BUFFER, 0);
ImGui_ImplSdl_CreateFontsTexture();
return true;
}
bool ImGui_ImplSdl_Init(SDL_Window *window)
{
ImGuiIO& io = ImGui::GetIO();
io.KeyMap[ImGuiKey_Tab] = SDLK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP;
io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN;
io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP;
io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN;
io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME;
io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END;
io.KeyMap[ImGuiKey_Delete] = SDLK_DELETE;
io.KeyMap[ImGuiKey_Backspace] = SDLK_BACKSPACE;
io.KeyMap[ImGuiKey_Enter] = SDLK_RETURN;
io.KeyMap[ImGuiKey_Escape] = SDLK_ESCAPE;
io.KeyMap[ImGuiKey_A] = SDLK_a;
io.KeyMap[ImGuiKey_C] = SDLK_c;
io.KeyMap[ImGuiKey_V] = SDLK_v;
io.KeyMap[ImGuiKey_X] = SDLK_x;
io.KeyMap[ImGuiKey_Y] = SDLK_y;
io.KeyMap[ImGuiKey_Z] = SDLK_z;
io.IniFilename = "";
io.LogFilename = "";
io.RenderDrawListsFn = ImGui_ImplSdl_RenderDrawLists;
io.SetClipboardTextFn = ImGui_ImplSdl_SetClipboardText;
io.GetClipboardTextFn = ImGui_ImplSdl_GetClipboardText;
return true;
}
void ImGui_ImplSdl_NewFrame(SDL_Window *window)
{
if (!g_FontTexture)
ImGui_ImplSdl_CreateDeviceObjects();
ImGuiIO& io = ImGui::GetIO();
// Setup display size (every frame to accommodate for window resizing)
int w, h;
SDL_GetWindowSize(window, &w, &h);
io.DisplaySize = ImVec2((float)w, (float)h);
// Setup time step
Uint32 time = SDL_GetTicks();
double current_time = time / 1000.0;
io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f);
g_Time = current_time;
// Setup inputs
// (we already got mouse wheel, keyboard keys & characters from gl.fw callbacks polled in gl.fwPollEvents())
int mx, my;
Uint32 mouseMask = SDL_GetMouseState(&mx, &my);
if (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_FOCUS)
io.MousePos = ImVec2((float)mx, (float)my); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
else
io.MousePos = ImVec2(-1,-1);
io.MouseDown[0] = g_MousePressed[0] || (mouseMask & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame.
io.MouseDown[1] = g_MousePressed[1] || (mouseMask & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0;
io.MouseDown[2] = g_MousePressed[2] || (mouseMask & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0;
g_MousePressed[0] = g_MousePressed[1] = g_MousePressed[2] = false;
io.MouseWheel = g_MouseWheel;
g_MouseWheel = 0.0f;
// Hide OS mouse cursor if ImGui is drawing it
SDL_ShowCursor(io.MouseDrawCursor ? 0 : 1);
// Start the frame
ImGui::NewFrame();
}
void ImGui_ImplSdl_Shutdown()
{
if (g_VaoHandle) gl.DeleteVertexArrays(1, &g_VaoHandle);
if (g_VboHandle) gl.DeleteBuffers(1, &g_VboHandle);
g_VaoHandle = 0;
g_VboHandle = 0;
gl.DetachShader(g_ShaderHandle, g_VertHandle);
gl.DeleteShader(g_VertHandle);
g_VertHandle = 0;
gl.DetachShader(g_ShaderHandle, g_FragHandle);
gl.DeleteShader(g_FragHandle);
g_FragHandle = 0;
gl.DeleteProgram(g_ShaderHandle);
g_ShaderHandle = 0;
if (g_FontTexture)
{
gl.DeleteTextures(1, &g_FontTexture);
ImGui::GetIO().Fonts->TexID = 0;
g_FontTexture = 0;
}
g_VboSize = 0;
ImGui::Shutdown();
}

View File

@ -0,0 +1,11 @@
// ImGui SDL2 binding with OpenGL
// https://github.com/ocornut/imgui
struct SDL_Window;
typedef union SDL_Event SDL_Event;
bool ImGui_ImplSdl_Init(SDL_Window *window);
void ImGui_ImplSdl_Shutdown();
void ImGui_ImplSdl_NewFrame(SDL_Window *window);
bool ImGui_ImplSdl_ProcessEvent(const SDL_Event &event);
bool ImGui_ImplSdl_CreateDeviceObjects();

547
src/imgui/stb_rect_pack.h Normal file
View File

@ -0,0 +1,547 @@
// stb_rect_pack.h - v0.05 - public domain - rectangle packing
// Sean Barrett 2014
//
// Useful for e.g. packing rectangular textures into an atlas.
// Does not do rotation.
//
// Not necessarily the awesomest packing method, but better than
// the totally naive one in stb_truetype (which is primarily what
// this is meant to replace).
//
// Has only had a few tests run, may have issues.
//
// More docs to come.
//
// No memory allocations; uses qsort() and assert() from stdlib.
//
// This library currently uses the Skyline Bottom-Left algorithm.
//
// Please note: better rectangle packers are welcome! Please
// implement them to the same API, but with a different init
// function.
//
// Version history:
//
// 0.05: added STBRP_ASSERT to allow replacing assert
// 0.04: fixed minor bug in STBRP_LARGE_RECTS support
// 0.01: initial release
//////////////////////////////////////////////////////////////////////////////
//
// INCLUDE SECTION
//
#ifndef STB_INCLUDE_STB_RECT_PACK_H
#define STB_INCLUDE_STB_RECT_PACK_H
#define STB_RECT_PACK_VERSION 1
#ifdef STBRP_STATIC
#define STBRP_DEF static
#else
#define STBRP_DEF extern
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef struct stbrp_context stbrp_context;
typedef struct stbrp_node stbrp_node;
typedef struct stbrp_rect stbrp_rect;
#ifdef STBRP_LARGE_RECTS
typedef int stbrp_coord;
#else
typedef unsigned short stbrp_coord;
#endif
STBRP_DEF void stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects);
// Assign packed locations to rectangles. The rectangles are of type
// 'stbrp_rect' defined below, stored in the array 'rects', and there
// are 'num_rects' many of them.
//
// Rectangles which are successfully packed have the 'was_packed' flag
// set to a non-zero value and 'x' and 'y' store the minimum location
// on each axis (i.e. bottom-left in cartesian coordinates, top-left
// if you imagine y increasing downwards). Rectangles which do not fit
// have the 'was_packed' flag set to 0.
//
// You should not try to access the 'rects' array from another thread
// while this function is running, as the function temporarily reorders
// the array while it executes.
//
// To pack into another rectangle, you need to call stbrp_init_target
// again. To continue packing into the same rectangle, you can call
// this function again. Calling this multiple times with multiple rect
// arrays will probably produce worse packing results than calling it
// a single time with the full rectangle array, but the option is
// available.
struct stbrp_rect
{
// reserved for your use:
int id;
// input:
stbrp_coord w, h;
// output:
stbrp_coord x, y;
int was_packed; // non-zero if valid packing
}; // 16 bytes, nominally
STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes);
// Initialize a rectangle packer to:
// pack a rectangle that is 'width' by 'height' in dimensions
// using temporary storage provided by the array 'nodes', which is 'num_nodes' long
//
// You must call this function every time you start packing into a new target.
//
// There is no "shutdown" function. The 'nodes' memory must stay valid for
// the following stbrp_pack_rects() call (or calls), but can be freed after
// the call (or calls) finish.
//
// Note: to guarantee best results, either:
// 1. make sure 'num_nodes' >= 'width'
// or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1'
//
// If you don't do either of the above things, widths will be quantized to multiples
// of small integers to guarantee the algorithm doesn't run out of temporary storage.
//
// If you do #2, then the non-quantized algorithm will be used, but the algorithm
// may run out of temporary storage and be unable to pack some rectangles.
STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem);
// Optionally call this function after init but before doing any packing to
// change the handling of the out-of-temp-memory scenario, described above.
// If you call init again, this will be reset to the default (false).
STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic);
// Optionally select which packing heuristic the library should use. Different
// heuristics will produce better/worse results for different data sets.
// If you call init again, this will be reset to the default.
enum
{
STBRP_HEURISTIC_Skyline_default=0,
STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default,
STBRP_HEURISTIC_Skyline_BF_sortHeight
};
//////////////////////////////////////////////////////////////////////////////
//
// the details of the following structures don't matter to you, but they must
// be visible so you can handle the memory allocations for them
struct stbrp_node
{
stbrp_coord x,y;
stbrp_node *next;
};
struct stbrp_context
{
int width;
int height;
int align;
int init_mode;
int heuristic;
int num_nodes;
stbrp_node *active_head;
stbrp_node *free_head;
stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2'
};
#ifdef __cplusplus
}
#endif
#endif
//////////////////////////////////////////////////////////////////////////////
//
// IMPLEMENTATION SECTION
//
#ifdef STB_RECT_PACK_IMPLEMENTATION
#include <stdlib.h>
#ifndef STBRP_ASSERT
#include <assert.h>
#define STBRP_ASSERT assert
#endif
enum
{
STBRP__INIT_skyline = 1
};
STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic)
{
switch (context->init_mode) {
case STBRP__INIT_skyline:
STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight);
context->heuristic = heuristic;
break;
default:
STBRP_ASSERT(0);
}
}
STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem)
{
if (allow_out_of_mem)
// if it's ok to run out of memory, then don't bother aligning them;
// this gives better packing, but may fail due to OOM (even though
// the rectangles easily fit). @TODO a smarter approach would be to only
// quantize once we've hit OOM, then we could get rid of this parameter.
context->align = 1;
else {
// if it's not ok to run out of memory, then quantize the widths
// so that num_nodes is always enough nodes.
//
// I.e. num_nodes * align >= width
// align >= width / num_nodes
// align = ceil(width/num_nodes)
context->align = (context->width + context->num_nodes-1) / context->num_nodes;
}
}
STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes)
{
int i;
#ifndef STBRP_LARGE_RECTS
STBRP_ASSERT(width <= 0xffff && height <= 0xffff);
#endif
for (i=0; i < num_nodes-1; ++i)
nodes[i].next = &nodes[i+1];
nodes[i].next = NULL;
context->init_mode = STBRP__INIT_skyline;
context->heuristic = STBRP_HEURISTIC_Skyline_default;
context->free_head = &nodes[0];
context->active_head = &context->extra[0];
context->width = width;
context->height = height;
context->num_nodes = num_nodes;
stbrp_setup_allow_out_of_mem(context, 0);
// node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly)
context->extra[0].x = 0;
context->extra[0].y = 0;
context->extra[0].next = &context->extra[1];
context->extra[1].x = (stbrp_coord) width;
#ifdef STBRP_LARGE_RECTS
context->extra[1].y = (1<<30);
#else
context->extra[1].y = 65535;
#endif
context->extra[1].next = NULL;
}
// find minimum y position if it starts at x1
static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste)
{
(void)c;
stbrp_node *node = first;
int x1 = x0 + width;
int min_y, visited_width, waste_area;
STBRP_ASSERT(first->x <= x0);
#if 0
// skip in case we're past the node
while (node->next->x <= x0)
++node;
#else
STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency
#endif
STBRP_ASSERT(node->x <= x0);
min_y = 0;
waste_area = 0;
visited_width = 0;
while (node->x < x1) {
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
waste_area += visited_width * (node->y - min_y);
min_y = node->y;
// the first time through, visited_width might be reduced
if (node->x < x0)
visited_width += node->next->x - x0;
else
visited_width += node->next->x - node->x;
} else {
// add waste area
int under_width = node->next->x - node->x;
if (under_width + visited_width > width)
under_width = width - visited_width;
waste_area += under_width * (min_y - node->y);
visited_width += under_width;
}
node = node->next;
}
*pwaste = waste_area;
return min_y;
}
typedef struct
{
int x,y;
stbrp_node **prev_link;
} stbrp__findresult;
static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height)
{
int best_waste = (1<<30), best_x, best_y = (1 << 30);
stbrp__findresult fr;
stbrp_node **prev, *node, *tail, **best = NULL;
// align to multiple of c->align
width = (width + c->align - 1);
width -= width % c->align;
STBRP_ASSERT(width % c->align == 0);
node = c->active_head;
prev = &c->active_head;
while (node->x + width <= c->width) {
int y,waste;
y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste);
if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL
// bottom left
if (y < best_y) {
best_y = y;
best = prev;
}
} else {
// best-fit
if (y + height <= c->height) {
// can only use it if it first vertically
if (y < best_y || (y == best_y && waste < best_waste)) {
best_y = y;
best_waste = waste;
best = prev;
}
}
}
prev = &node->next;
node = node->next;
}
best_x = (best == NULL) ? 0 : (*best)->x;
// if doing best-fit (BF), we also have to try aligning right edge to each node position
//
// e.g, if fitting
//
// ____________________
// |____________________|
//
// into
//
// | |
// | ____________|
// |____________|
//
// then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned
//
// This makes BF take about 2x the time
if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) {
tail = c->active_head;
node = c->active_head;
prev = &c->active_head;
// find first node that's admissible
while (tail->x < width)
tail = tail->next;
while (tail) {
int xpos = tail->x - width;
int y,waste;
STBRP_ASSERT(xpos >= 0);
// find the left position that matches this
while (node->next->x <= xpos) {
prev = &node->next;
node = node->next;
}
STBRP_ASSERT(node->next->x > xpos && node->x <= xpos);
y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste);
if (y + height < c->height) {
if (y <= best_y) {
if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) {
best_x = xpos;
STBRP_ASSERT(y <= best_y);
best_y = y;
best_waste = waste;
best = prev;
}
}
}
tail = tail->next;
}
}
fr.prev_link = best;
fr.x = best_x;
fr.y = best_y;
return fr;
}
static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height)
{
// find best position according to heuristic
stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height);
stbrp_node *node, *cur;
// bail if:
// 1. it failed
// 2. the best node doesn't fit (we don't always check this)
// 3. we're out of memory
if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) {
res.prev_link = NULL;
return res;
}
// on success, create new node
node = context->free_head;
node->x = (stbrp_coord) res.x;
node->y = (stbrp_coord) (res.y + height);
context->free_head = node->next;
// insert the new node into the right starting point, and
// let 'cur' point to the remaining nodes needing to be
// stiched back in
cur = *res.prev_link;
if (cur->x < res.x) {
// preserve the existing one, so start testing with the next one
stbrp_node *next = cur->next;
cur->next = node;
cur = next;
} else {
*res.prev_link = node;
}
// from here, traverse cur and free the nodes, until we get to one
// that shouldn't be freed
while (cur->next && cur->next->x <= res.x + width) {
stbrp_node *next = cur->next;
// move the current node to the free list
cur->next = context->free_head;
context->free_head = cur;
cur = next;
}
// stitch the list back in
node->next = cur;
if (cur->x < res.x + width)
cur->x = (stbrp_coord) (res.x + width);
#ifdef _DEBUG
cur = context->active_head;
while (cur->x < context->width) {
STBRP_ASSERT(cur->x < cur->next->x);
cur = cur->next;
}
STBRP_ASSERT(cur->next == NULL);
{
stbrp_node *L1 = NULL, *L2 = NULL;
int count=0;
cur = context->active_head;
while (cur) {
L1 = cur;
cur = cur->next;
++count;
}
cur = context->free_head;
while (cur) {
L2 = cur;
cur = cur->next;
++count;
}
STBRP_ASSERT(count == context->num_nodes+2);
}
#endif
return res;
}
static int rect_height_compare(const void *a, const void *b)
{
stbrp_rect *p = (stbrp_rect *) a;
stbrp_rect *q = (stbrp_rect *) b;
if (p->h > q->h)
return -1;
if (p->h < q->h)
return 1;
return (p->w > q->w) ? -1 : (p->w < q->w);
}
static int rect_width_compare(const void *a, const void *b)
{
stbrp_rect *p = (stbrp_rect *) a;
stbrp_rect *q = (stbrp_rect *) b;
if (p->w > q->w)
return -1;
if (p->w < q->w)
return 1;
return (p->h > q->h) ? -1 : (p->h < q->h);
}
static int rect_original_order(const void *a, const void *b)
{
stbrp_rect *p = (stbrp_rect *) a;
stbrp_rect *q = (stbrp_rect *) b;
return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed);
}
#ifdef STBRP_LARGE_RECTS
#define STBRP__MAXVAL 0xffffffff
#else
#define STBRP__MAXVAL 0xffff
#endif
STBRP_DEF void stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)
{
int i;
// we use the 'was_packed' field internally to allow sorting/unsorting
for (i=0; i < num_rects; ++i) {
rects[i].was_packed = i;
#ifndef STBRP_LARGE_RECTS
STBRP_ASSERT(rects[i].w <= 0xffff && rects[i].h <= 0xffff);
#endif
}
// sort according to heuristic
qsort(rects, num_rects, sizeof(rects[0]), rect_height_compare);
for (i=0; i < num_rects; ++i) {
stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h);
if (fr.prev_link) {
rects[i].x = (stbrp_coord) fr.x;
rects[i].y = (stbrp_coord) fr.y;
} else {
rects[i].x = rects[i].y = STBRP__MAXVAL;
}
}
// unsort
qsort(rects, num_rects, sizeof(rects[0]), rect_original_order);
// set was_packed flags
for (i=0; i < num_rects; ++i)
rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);
}
#endif

1254
src/imgui/stb_textedit.h Normal file

File diff suppressed because it is too large Load Diff

2672
src/imgui/stb_truetype.h Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff