Added ImGUI FPS slider along with an RLE decoder for .rle conways game of life files

This commit is contained in:
MitchellHansen
2017-04-08 18:58:13 -07:00
parent 823f2e78aa
commit efc9c34ebe
20 changed files with 39052 additions and 9 deletions

419
src/imgui/imgui-SFML.cpp Normal file
View File

@@ -0,0 +1,419 @@
#include "imgui/imgui-SFML.h"
#include "imgui/imgui.h"
#include <SFML/OpenGL.hpp>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/Window/Event.hpp>
#include <SFML/Window/Window.hpp>
#include <cstddef> // offsetof, NULL
#include <cassert>
// Supress warnings caused by converting from uint to void* in pCmd->TextureID
#ifdef __clang__
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int'
#elif defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
#endif
static bool s_windowHasFocus = true;
static bool s_mousePressed[3] = { false, false, false };
static sf::Texture* s_fontTexture = NULL; // owning pointer to internal font atlas which is used if user doesn't set custom sf::Texture.
namespace
{
ImVec2 getTopLeftAbsolute(const sf::FloatRect& rect);
ImVec2 getDownRightAbsolute(const sf::FloatRect& rect);
inline void RenderDrawLists(ImDrawData* draw_data); // rendering callback function prototype
// Implementation of ImageButton overload
bool imageButtonImpl(const sf::Texture& texture, const sf::FloatRect& textureRect, const sf::Vector2f& size, const int framePadding,
const sf::Color& bgColor, const sf::Color& tintColor);
} // anonymous namespace for helper / "private" functions
namespace ImGui
{
namespace SFML
{
void Init(sf::RenderTarget& target, sf::Texture* fontTexture)
{
ImGuiIO& io = ImGui::GetIO();
// init keyboard mapping
io.KeyMap[ImGuiKey_Tab] = sf::Keyboard::Tab;
io.KeyMap[ImGuiKey_LeftArrow] = sf::Keyboard::Left;
io.KeyMap[ImGuiKey_RightArrow] = sf::Keyboard::Right;
io.KeyMap[ImGuiKey_UpArrow] = sf::Keyboard::Up;
io.KeyMap[ImGuiKey_DownArrow] = sf::Keyboard::Down;
io.KeyMap[ImGuiKey_PageUp] = sf::Keyboard::PageUp;
io.KeyMap[ImGuiKey_PageDown] = sf::Keyboard::PageDown;
io.KeyMap[ImGuiKey_Home] = sf::Keyboard::Home;
io.KeyMap[ImGuiKey_End] = sf::Keyboard::End;
io.KeyMap[ImGuiKey_Delete] = sf::Keyboard::Delete;
io.KeyMap[ImGuiKey_Backspace] = sf::Keyboard::BackSpace;
io.KeyMap[ImGuiKey_Enter] = sf::Keyboard::Return;
io.KeyMap[ImGuiKey_Escape] = sf::Keyboard::Escape;
io.KeyMap[ImGuiKey_A] = sf::Keyboard::A;
io.KeyMap[ImGuiKey_C] = sf::Keyboard::C;
io.KeyMap[ImGuiKey_V] = sf::Keyboard::V;
io.KeyMap[ImGuiKey_X] = sf::Keyboard::X;
io.KeyMap[ImGuiKey_Y] = sf::Keyboard::Y;
io.KeyMap[ImGuiKey_Z] = sf::Keyboard::Z;
// init rendering
io.DisplaySize = static_cast<sf::Vector2f>(target.getSize());
io.RenderDrawListsFn = RenderDrawLists; // set render callback
if (fontTexture == NULL) {
if (s_fontTexture) { // delete previously created texture
delete s_fontTexture;
}
s_fontTexture = new sf::Texture;
createFontTexture(*s_fontTexture);
setFontTexture(*s_fontTexture);
} else {
setFontTexture(*fontTexture);
}
}
void ProcessEvent(const sf::Event& event)
{
ImGuiIO& io = ImGui::GetIO();
if (s_windowHasFocus) {
switch (event.type)
{
case sf::Event::MouseButtonPressed: // fall-through
case sf::Event::MouseButtonReleased:
{
int button = event.mouseButton.button;
if (event.type == sf::Event::MouseButtonPressed &&
button >= 0 && button < 3) {
s_mousePressed[event.mouseButton.button] = true;
}
}
break;
case sf::Event::MouseWheelMoved:
io.MouseWheel += static_cast<float>(event.mouseWheel.delta);
break;
case sf::Event::KeyPressed: // fall-through
case sf::Event::KeyReleased:
io.KeysDown[event.key.code] = (event.type == sf::Event::KeyPressed);
io.KeyCtrl = event.key.control;
io.KeyShift = event.key.shift;
io.KeyAlt = event.key.alt;
break;
case sf::Event::TextEntered:
if (event.text.unicode > 0 && event.text.unicode < 0x10000) {
io.AddInputCharacter(static_cast<ImWchar>(event.text.unicode));
}
break;
default:
break;
}
}
switch (event.type)
{
case sf::Event::LostFocus:
s_windowHasFocus = false;
break;
case sf::Event::GainedFocus:
s_windowHasFocus = true;
break;
default:
break;
}
}
void Update(sf::RenderWindow& window, sf::Time dt)
{
Update(window, window, dt);
}
void Update(sf::Window& window, sf::RenderTarget& target, sf::Time dt)
{
Update(sf::Mouse::getPosition(window), static_cast<sf::Vector2f>(target.getSize()), dt);
window.setMouseCursorVisible(!ImGui::GetIO().MouseDrawCursor); // don't draw mouse cursor if ImGui draws it
}
void Update(const sf::Vector2i& mousePos, const sf::Vector2f& displaySize, sf::Time dt)
{
ImGuiIO& io = ImGui::GetIO();
io.DisplaySize = displaySize;
io.DeltaTime = dt.asSeconds();
if (s_windowHasFocus) {
io.MousePos = mousePos;
for (int i = 0; i < 3; ++i) {
io.MouseDown[i] = s_mousePressed[i] || sf::Mouse::isButtonPressed((sf::Mouse::Button)i);
s_mousePressed[i] = false;
}
}
assert(io.Fonts->Fonts.Size > 0); // You forgot to create and set up font atlas (see createFontTexture)
ImGui::NewFrame();
}
void Shutdown()
{
ImGui::GetIO().Fonts->TexID = NULL;
if (s_fontTexture) { // if internal texture was created, we delete it
delete s_fontTexture;
s_fontTexture = NULL;
}
ImGui::Shutdown(); // need to specify namespace here, otherwise ImGui::SFML::Shutdown would be called
}
void createFontTexture(sf::Texture& texture)
{
unsigned char* pixels;
int width, height;
ImGuiIO& io = ImGui::GetIO();
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
texture.create(width, height);
texture.update(pixels);
io.Fonts->ClearInputData();
io.Fonts->ClearTexData();
}
void setFontTexture(sf::Texture& texture)
{
ImGui::GetIO().Fonts->TexID = (void*)texture.getNativeHandle();
if (&texture != s_fontTexture) { // internal texture is not needed anymore
delete s_fontTexture;
s_fontTexture = NULL;
}
}
} // end of namespace SFML
/////////////// Image Overloads
void Image(const sf::Texture& texture,
const sf::Color& tintColor, const sf::Color& borderColor)
{
Image(texture, static_cast<sf::Vector2f>(texture.getSize()), tintColor, borderColor);
}
void Image(const sf::Texture& texture, const sf::Vector2f& size,
const sf::Color& tintColor, const sf::Color& borderColor)
{
ImGui::Image((void*)texture.getNativeHandle(), size, ImVec2(0, 0), ImVec2(1, 1), tintColor, borderColor);
}
void Image(const sf::Texture& texture, const sf::FloatRect& textureRect,
const sf::Color& tintColor, const sf::Color& borderColor)
{
Image(texture, sf::Vector2f(textureRect.width, textureRect.height), textureRect, tintColor, borderColor);
}
void Image(const sf::Texture& texture, const sf::Vector2f& size, const sf::FloatRect& textureRect,
const sf::Color& tintColor, const sf::Color& borderColor)
{
sf::Vector2f textureSize = static_cast<sf::Vector2f>(texture.getSize());
ImVec2 uv0(textureRect.left / textureSize.x, textureRect.top / textureSize.y);
ImVec2 uv1((textureRect.left + textureRect.width) / textureSize.x,
(textureRect.top + textureRect.height) / textureSize.y);
ImGui::Image((void*)texture.getNativeHandle(), size, uv0, uv1, tintColor, borderColor);
}
void Image(const sf::Sprite& sprite,
const sf::Color& tintColor, const sf::Color& borderColor)
{
sf::FloatRect bounds = sprite.getGlobalBounds();
Image(sprite, sf::Vector2f(bounds.width, bounds.height), tintColor, borderColor);
}
void Image(const sf::Sprite& sprite, const sf::Vector2f& size,
const sf::Color& tintColor, const sf::Color& borderColor)
{
const sf::Texture* texturePtr = sprite.getTexture();
// sprite without texture cannot be drawn
if (!texturePtr) { return; }
Image(*texturePtr, size, tintColor, borderColor);
}
/////////////// Image Button Overloads
bool ImageButton(const sf::Texture& texture,
const int framePadding, const sf::Color& bgColor, const sf::Color& tintColor)
{
return ImageButton(texture, static_cast<sf::Vector2f>(texture.getSize()), framePadding, bgColor, tintColor);
}
bool ImageButton(const sf::Texture& texture, const sf::Vector2f& size,
const int framePadding, const sf::Color& bgColor, const sf::Color& tintColor)
{
sf::Vector2f textureSize = static_cast<sf::Vector2f>(texture.getSize());
return ::imageButtonImpl(texture, sf::FloatRect(0.f, 0.f, textureSize.x, textureSize.y), size, framePadding, bgColor, tintColor);
}
bool ImageButton(const sf::Sprite& sprite,
const int framePadding, const sf::Color& bgColor, const sf::Color& tintColor)
{
sf::FloatRect spriteSize = sprite.getGlobalBounds();
return ImageButton(sprite, sf::Vector2f(spriteSize.width, spriteSize.height), framePadding, bgColor, tintColor);
}
bool ImageButton(const sf::Sprite& sprite, const sf::Vector2f& size,
const int framePadding, const sf::Color& bgColor, const sf::Color& tintColor)
{
const sf::Texture* texturePtr = sprite.getTexture();
if (!texturePtr) { return false; }
return ::imageButtonImpl(*texturePtr, static_cast<sf::FloatRect>(sprite.getTextureRect()), size, framePadding, bgColor, tintColor);
}
/////////////// Draw_list Overloads
void DrawLine(const sf::Vector2f& a, const sf::Vector2f& b, const sf::Color& color,
float thickness)
{
ImDrawList* draw_list = ImGui::GetWindowDrawList();
sf::Vector2f pos = ImGui::GetCursorScreenPos();
draw_list->AddLine(a + pos, b + pos, ColorConvertFloat4ToU32(color), thickness);
}
void DrawRect(const sf::FloatRect& rect, const sf::Color& color,
float rounding, int rounding_corners, float thickness)
{
ImDrawList* draw_list = ImGui::GetWindowDrawList();
draw_list->AddRect(
getTopLeftAbsolute(rect),
getDownRightAbsolute(rect),
ColorConvertFloat4ToU32(color), rounding, rounding_corners, thickness);
}
void DrawRectFilled(const sf::FloatRect& rect, const sf::Color& color,
float rounding, int rounding_corners)
{
ImDrawList* draw_list = ImGui::GetWindowDrawList();
draw_list->AddRect(
getTopLeftAbsolute(rect),
getDownRightAbsolute(rect),
ColorConvertFloat4ToU32(color), rounding, rounding_corners);
}
} // end of namespace ImGui
namespace
{
ImVec2 getTopLeftAbsolute(const sf::FloatRect & rect)
{
ImVec2 pos = ImGui::GetCursorScreenPos();
return ImVec2(rect.left + pos.x, rect.top + pos.y);
}
ImVec2 getDownRightAbsolute(const sf::FloatRect & rect)
{
ImVec2 pos = ImGui::GetCursorScreenPos();
return ImVec2(rect.left + rect.width + pos.x, rect.top + rect.height + pos.y);
}
// Rendering callback
void RenderDrawLists(ImDrawData* draw_data)
{
if (draw_data->CmdListsCount == 0) {
return;
}
ImGuiIO& io = ImGui::GetIO();
assert(io.Fonts->TexID != NULL); // You forgot to create and set font texture
// scale stuff (needed for proper handling of window resize)
int fb_width = static_cast<int>(io.DisplaySize.x * io.DisplayFramebufferScale.x);
int fb_height = static_cast<int>(io.DisplaySize.y * io.DisplayFramebufferScale.y);
if (fb_width == 0 || fb_height == 0) { return; }
draw_data->ScaleClipRects(io.DisplayFramebufferScale);
// Save OpenGL state
GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_SCISSOR_TEST);
glEnable(GL_TEXTURE_2D);
glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
glMatrixMode(GL_TEXTURE);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0.0f, io.DisplaySize.x, io.DisplaySize.y, 0.0f, -1.0f, +1.0f);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
for (int n = 0; n < draw_data->CmdListsCount; ++n) {
const ImDrawList* cmd_list = draw_data->CmdLists[n];
const unsigned char* vtx_buffer = (const unsigned char*)&cmd_list->VtxBuffer.front();
const ImDrawIdx* idx_buffer = &cmd_list->IdxBuffer.front();
glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + offsetof(ImDrawVert, pos)));
glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + offsetof(ImDrawVert, uv)));
glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (void*)(vtx_buffer + offsetof(ImDrawVert, col)));
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); ++cmd_i) {
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback) {
pcmd->UserCallback(cmd_list, pcmd);
} else {
GLuint tex_id = (GLuint)*((unsigned int*)&pcmd->TextureId);
glBindTexture(GL_TEXTURE_2D, tex_id);
glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w),
(int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, GL_UNSIGNED_SHORT, idx_buffer);
}
idx_buffer += pcmd->ElemCount;
}
}
// Restore modified state
glBindTexture(GL_TEXTURE_2D, (GLuint)last_texture);
glMatrixMode(GL_TEXTURE);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glPopAttrib();
glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
}
bool imageButtonImpl(const sf::Texture& texture, const sf::FloatRect& textureRect, const sf::Vector2f& size, const int framePadding,
const sf::Color& bgColor, const sf::Color& tintColor)
{
sf::Vector2f textureSize = static_cast<sf::Vector2f>(texture.getSize());
ImVec2 uv0(textureRect.left / textureSize.x, textureRect.top / textureSize.y);
ImVec2 uv1((textureRect.left + textureRect.width) / textureSize.x,
(textureRect.top + textureRect.height) / textureSize.y);
return ImGui::ImageButton((void*)texture.getNativeHandle(), size, uv0, uv1, framePadding, bgColor, tintColor);
}
} // end of anonymous namespace

9853
src/imgui/imgui.cpp Normal file

File diff suppressed because it is too large Load Diff

2638
src/imgui/imgui_demo.cpp Normal file

File diff suppressed because it is too large Load Diff

2394
src/imgui/imgui_draw.cpp Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -6,6 +6,8 @@
#include "util.hpp"
#include <thread>
#include "OpenCL.h"
#include "imgui/imgui-SFML.h"
#include "imgui/imgui.h"
float elap_time() {
static std::chrono::time_point<std::chrono::system_clock> start;
@@ -38,10 +40,144 @@ void generate_nodes(sf::Uint8* nodes) {
}
struct rle_info {
std::string title;
std::string author;
std::string comments;
sf::Vector2i dimensions;
};
rle_info load_rle(sf::Uint8* nodes, sf::Vector2i dimensions, std::string filename) {
rle_info info;
for (int i = 0; i < dimensions.x * dimensions.y; i++) {
nodes[i] = 0;
}
std::ifstream file(filename);
if (!file.is_open()) {
std::cout << "unable to open file" << std::endl;
return info;
}
for (std::string line; std::getline(file, line); )
{
// Grab the header comments
if (line[0] == '#') {
std::string data = line.substr(3, line.size() - 3);
switch (line[1]) {
case 'C': {
info.comments += data;
break;
}
case 'O': {
info.author += data;
break;
}
case 'N': {
info.title += data;
break;
}
default : {
std::cout << "Case : " << line[1] << " not supported" << std::endl;
}
}
}
// grab the dimensions
else if (line[0] == 'x') {
// Naively assume that it is in the exact form "x = <num>, y = <num>,"
std::stringstream ss(line);
std::string temp;
ss >> temp >> temp >> temp;
info.dimensions.x = std::stoi(temp.substr(0, temp.size() - 1));
ss >> temp >> temp >> temp;
info.dimensions.y = std::stoi(temp.substr(0, temp.size() - 1));
}
// Decode the RLE
else {
std::vector<std::vector<char>> grid;
std::stringstream ss(line);
std::string token;
while (std::getline(ss, token, '$')) {
std::vector<char> char_line;
unsigned int token_pos = 0;
std::string tmp;
while (token_pos < token.size()) {
char status = -1;
if (token[token_pos] == 'b')
status = 0;
else if (token[token_pos] == 'o')
status = 1;
else if (token[token_pos] == '!')
break;
else
tmp += token[token_pos];
token_pos++;
if (status >= 0) {
if (tmp.empty()) {
char_line.push_back(status);
}
else {
int count = std::stoi(tmp);
for (int i = 0; i < count; i++) {
char_line.push_back(status);
}
tmp.clear();
}
}
}
grid.push_back(char_line);
}
int y_mod = 200;
int x_mod = 200;
for (int y = 0; y < grid.size(); y++) {
for (int x = 0; x < grid.at(y).size(); x++) {
nodes[(y+y_mod) * dimensions.x + (x+x_mod)] = grid.at(y).at(x);
}
}
}
}
std::cout << info.author << std::endl;
std::cout << info.title << std::endl;
std::cout << info.comments << std::endl;
return info;
}
int main() {
sf::RenderWindow window(sf::VideoMode(WINDOW_X, WINDOW_Y), "conways-game-of-life-opencl");
window.setFramerateLimit(300);
int simulation_speed = 100;
window.setFramerateLimit(simulation_speed);
ImGui::SFML::Init(window);
window.resetGLStates();
float physic_step = 0.166f;
float physic_time = 0.0f;
@@ -61,8 +197,9 @@ int main() {
cl.create_buffer("image_res", sizeof(sf::Vector2i), &image_resolution);
sf::Uint8* nodes = new sf::Uint8[WINDOW_X * WINDOW_Y];
generate_nodes(nodes);
nodes[0] = 1;
//generate_nodes(nodes);
load_rle(nodes, sf::Vector2i(WINDOW_X, WINDOW_Y), "../assets/puffer_breeder_1.rle");
cl.create_buffer("first_node_buffer", WINDOW_X * WINDOW_Y, (void*)nodes, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR);
cl.create_buffer("second_node_buffer", WINDOW_X * WINDOW_Y, (void*)nodes, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR);
@@ -75,6 +212,11 @@ int main() {
cl.set_kernel_arg("conways", 3, "second_node_buffer");
cl.set_kernel_arg("conways", 4, "buffer_flip");
sf::Clock sf_delta_clock;
while (window.isOpen())
{
sf::Event event; // Handle input
@@ -116,16 +258,33 @@ int main() {
physic_time += physic_step;
}
ImGui::SFML::Update(window, sf_delta_clock.restart());
window.clear(sf::Color::White);
cl.run_kernel("conways", image_resolution);
cl.draw(&window);
ImGui::Begin("Sim");
if (ImGui::SliderInt("Simulation Speed", &simulation_speed, 30, 500)) {
window.setFramerateLimit(simulation_speed);
}
ImGui::End();
ImGui::Render();
if (buffer_flip == 1)
buffer_flip = 0;
else
buffer_flip = 1;
// ImGui screws stuff up after the render, rendering a drawable resets it
window.draw(sf::CircleShape(0));
window.display();
}