<commit_before>#include <algorithm>
#include <fstream>
#include <iostream>
#include <regex>
#include <SDL.h>
#include <SDL_image.h>
//#include <unistd.h>
//#include <rpc.h>

#include "DirectoryScanner.hh"

const auto company = u8"即死ゲーム開発会社";
const auto product = "image viewer ++";
const int defaultWidth = 800;
const int defaultHeight = 600;

void newImage(SDL_Window *window, SDL_Surface *screen, const std::string &path, float scale, SDL_Rect &offset, bool resizeWindow = false)
{
    SDL_FillRect(screen, nullptr, 0);

    auto image = IMG_Load(path.c_str());

    SDL_Rect imageSize;

    SDL_GetClipRect(image, &imageSize);

    if (resizeWindow) {
        if (imageSize.w > imageSize.h) {
            auto width = defaultWidth;
            auto height = static_cast<int>(static_cast<float>(imageSize.h) / static_cast<float>(imageSize.w) * defaultWidth);
            SDL_SetWindowSize(window, width, height);
        } else {
            auto width = static_cast<int>(static_cast<float>(imageSize.w) / static_cast<float>(imageSize.h) * defaultHeight);
            auto height = defaultHeight;
            SDL_SetWindowSize(window, width, height);
        }

        screen = SDL_GetWindowSurface(window);
    }

    SDL_Rect windowSize;

    SDL_GetClipRect(screen, &windowSize);

    int windowWidth;
    int windowHeight;

    SDL_GetWindowSize(window, &windowWidth, &windowHeight);

    float imageWidthCorrected;
    float imageHeightCorrected;
    float imageWidthUnscaled = imageSize.w;
    float imageHeightUnscaled = imageSize.h;

    if (imageWidthUnscaled> imageHeightUnscaled) {
        imageWidthCorrected = static_cast<float>(windowWidth);
        imageHeightCorrected = static_cast<float>(windowWidth) * imageHeightUnscaled / imageWidthUnscaled;

        if (imageHeightCorrected > static_cast<float>(windowHeight)) {
            imageWidthCorrected = static_cast<float>(windowHeight) * imageWidthUnscaled / imageHeightUnscaled;
            imageHeightCorrected = static_cast<float>(windowHeight);
        }
    } else {
        imageWidthCorrected = static_cast<float>(windowHeight) * imageWidthUnscaled / imageHeightUnscaled;
        imageHeightCorrected = static_cast<float>(windowHeight);

        if (imageWidthCorrected > static_cast<float>(windowWidth)) {
            imageWidthCorrected = static_cast<float>(windowWidth);
            imageHeightCorrected = static_cast<float>(windowWidth) * imageHeightUnscaled / imageWidthUnscaled;
        }
    }

    float imageWidth = imageWidthCorrected * scale;
    float imageHeight = imageHeightCorrected * scale;
    float halfImageWidth = imageWidth / 2.0f;
    float halfImageHeight = imageHeight / 2.0f;
    float halfWindowWidth = windowWidth / 2.0f;
    float halfWindowHeight = windowHeight / 2.0f;
    float imageAbscissa = halfWindowWidth - halfImageWidth;
    float imageOrdinate = halfWindowHeight - halfImageHeight;

    if (scale > 1.0) {
        if (imageWidth >= windowWidth && offset.x - halfImageWidth + halfWindowWidth > 0.0f) {
            offset.x = static_cast<int>(halfImageWidth - halfWindowWidth);
        }

        if (imageHeight >= windowHeight && offset.y - halfImageHeight + halfWindowHeight > 0.0f) {
            offset.y = static_cast<int>(halfImageHeight - halfWindowHeight);
        }

        if (imageWidth >= windowWidth && offset.x + halfImageWidth - halfWindowWidth < 0.0f) {
            offset.x = static_cast<int>(halfWindowWidth - halfImageWidth);
        }

        if (imageHeight >= windowHeight && offset.y + imageHeight / 2.0 - halfWindowHeight < 0.0f) {
            offset.y = static_cast<int>(halfWindowHeight - halfImageHeight);
        }

        imageAbscissa = halfWindowWidth - halfImageWidth + offset.x;
        imageOrdinate = halfWindowHeight - halfImageHeight + offset.y;
    }

    SDL_Rect imagePosition;

    imagePosition.x = static_cast<int>(imageAbscissa);
    imagePosition.y = static_cast<int>(imageOrdinate);
    imagePosition.w = static_cast<int>(imageWidth);
    imagePosition.h = static_cast<int>(imageHeight);

    SDL_SetWindowTitle(window, path.c_str());

    SDL_BlitScaled(image, nullptr, screen, &imagePosition);

    SDL_FreeSurface(image);

    SDL_UpdateWindowSurface(window);

    SDL_FlushEvent(SDL_KEYDOWN);
    SDL_FlushEvent(SDL_MOUSEWHEEL);
    SDL_FlushEvent(SDL_MOUSEMOTION);
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        std::cerr << "usage: " << argv[0] << " <image>" << std::endl;

        return EXIT_FAILURE;
    }

    std::string argument(argv[1]);

    if (argument.find('\\') != std::string::npos) {
        std::replace(argument.begin(), argument.end(), '\\', '/');
    }

    auto lastSeparator = argument.rfind('/');
    std::string directory;

    if (lastSeparator != std::string::npos) {
        directory = argument.substr(0, lastSeparator);
    } else {
        directory = ".";
    }

    std::cout << directory << std::endl;

    SDL_Init(SDL_INIT_EVENTS | SDL_INIT_VIDEO);
    IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG);

    SDL_Rect windowSize = { 0 };
    windowSize.w = defaultWidth;
    windowSize.h = defaultHeight;

    SDL_Window *window = SDL_CreateWindow(product, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, defaultWidth,
        defaultHeight,
        SDL_WINDOW_BORDERLESS | SDL_WINDOW_OPENGL);
    SDL_Surface *screen = SDL_GetWindowSurface(window);

    auto path = SDL_GetPrefPath(company, product);

    auto pathFull = path + std::string("config.ini");

    std::cout << path << std::endl;

    SDL_RWops *file = SDL_RWFromFile(pathFull.c_str(), "w");

    SDL_RWwrite(file, "Hello, world!", 1, 13);
    SDL_RWclose(file);

    SDL_free(path);

    DirectoryScanner scanner(directory, 0);

    auto list = scanner.enumerate();
    auto current = std::find(list.cbegin(), list.cend(), argument);

    bool alive = true;
    bool zooming = false;
    bool resizing = false;
    bool moving = false;
    std::tuple<int, int> origin;
    float scale = 1.0f;
    SDL_Rect offset = { 0 };

    newImage(window, screen, *current, scale, offset, true);

    while (alive) {
        SDL_Event event;

        while (SDL_PollEvent(&event)) {
            switch (event.type) {
                case SDL_KEYDOWN:
                    switch (event.key.keysym.sym) {
                        case SDLK_ESCAPE:
                            alive = false;
                            break;

                        case SDLK_LEFT:
                            if (current == list.cbegin()) {
                                current = list.cend();
                            }

                            --current;

                            scale = 1.0f;
                            offset = { 0 };
                            newImage(window, screen, *current, scale, offset);
                            break;

                        case SDLK_RIGHT:
                            ++current;

                            if (current == list.cend()) {
                                current = list.cbegin();
                            }

                            scale = 1.0f;
                            offset = { 0 };
                            newImage(window, screen, *current, scale, offset);
                            break;

                        case SDLK_TAB:
                            zooming = !zooming;

                            break;

                        case SDLK_LSHIFT:
                            resizing = true;
                            SDL_SetRelativeMouseMode(SDL_TRUE);

                            break;

                        case SDLK_LCTRL:
                            moving = true;
                            SDL_SetRelativeMouseMode(SDL_TRUE);

                            break;

                        case SDLK_SPACE:
                            if ((SDL_GetWindowFlags(window) & SDL_WINDOW_MAXIMIZED) == 0) {
                                newImage(window, screen, *current, scale, offset, true);
                            } else {
                                auto image = IMG_Load(current->c_str());

                                SDL_Rect imageSize;
                                SDL_Rect realWindowSize;
                                SDL_GetClipRect(image, &imageSize);
                                SDL_GetClipRect(screen, &realWindowSize);

                                SDL_FreeSurface(image);

                                scale = static_cast<float>(realWindowSize.w) / (static_cast<float>(realWindowSize.h) * static_cast<float>(imageSize.w) / static_cast<float>(imageSize.h));
                                offset.x = 0;
                                offset.y = static_cast<int>(static_cast<float>(imageSize.h) / 2.0f * scale);
                                newImage(window, screen, *current, scale, offset);
                            }

                            break;

                        default:
                            break;
                    }
                    break;

                case SDL_KEYUP:
                    if (event.key.keysym.sym == SDLK_LSHIFT) {
                        resizing = false;
                        SDL_SetRelativeMouseMode(SDL_FALSE);
                        SDL_WarpMouseInWindow(window, windowSize.w / 2, windowSize.h / 2);
                    } else if (event.key.keysym.sym == SDLK_LCTRL) {
                        moving = false;
                        SDL_SetRelativeMouseMode(SDL_FALSE);
                        SDL_WarpMouseInWindow(window, windowSize.w / 2, windowSize.h / 2);
                    }

                    break;

                case SDL_MOUSEWHEEL:
                    if (!zooming) {
                        if (event.wheel.y > 0) {
                            if (current == list.cbegin()) {
                                current = list.cend();
                            }

                            --current;
                        } else {
                            ++current;

                            if (current == list.cend()) {
                                current = list.cbegin();
                            }
                        }

                        scale = 1.0f;
                        offset = { 0 };
                        newImage(window, screen, *current, scale, offset);
                    } else {
                        if (event.wheel.y > 0) {
                            scale *= 1.4128f;
                        } else {
                            scale *= 0.7078143f;
                        }

                        newImage(window, screen, *current, scale, offset);
                    }

                    break;

                case SDL_MOUSEBUTTONDOWN:
                    switch (event.button.button) {
                        case SDL_BUTTON_LEFT:
                            if (event.button.clicks == 1) {
                                moving = true;
                                SDL_SetRelativeMouseMode(SDL_TRUE);
                            } else if (event.button.clicks == 2) {
                                if ((SDL_GetWindowFlags(window) & SDL_WINDOW_MAXIMIZED) == 0) {
                                    SDL_MaximizeWindow(window);
                                    SDL_Rect maximizedSize;
                                    SDL_Surface *maximizedScreen = SDL_GetWindowSurface(window);
                                    SDL_GetClipRect(maximizedScreen, &maximizedSize);
                                    SDL_WarpMouseInWindow(window, maximizedSize.w / 2, maximizedSize.h / 2);
                                } else {
                                    SDL_RestoreWindow(window);
                                    SDL_WarpMouseInWindow(window, windowSize.w / 2, windowSize.h / 2);
                                }
                            }

                            break;

                        case SDL_BUTTON_RIGHT:
                            resizing = true;
                            origin = std::make_tuple(0, 0);
                            SDL_SetRelativeMouseMode(SDL_TRUE);

                            break;

                        case SDL_BUTTON_MIDDLE:
                            alive = false;

                            break;

                        default:
                            break;
                    }

                    break;

                case SDL_MOUSEBUTTONUP:
                    if (moving || resizing) {
                        SDL_SetRelativeMouseMode(SDL_FALSE);
                        SDL_WarpMouseInWindow(window, windowSize.w / 2, windowSize.h / 2);
                        SDL_FlushEvent(SDL_MOUSEBUTTONDOWN);
                    }

                    switch (event.button.button) {
                        case SDL_BUTTON_LEFT:
                            moving = false;
                            origin = std::make_tuple(-1, -1);

                            break;

                        case SDL_BUTTON_RIGHT:
                            resizing = false;

                            break;

                        default:
                            break;
                    }

                    break;

                case SDL_MOUSEMOTION:
                    if (((SDL_GetWindowFlags(window) & SDL_WINDOW_MAXIMIZED) == 0) && resizing) {
                        windowSize.w = std::max(0, windowSize.w + event.motion.xrel);
                        windowSize.h = std::max(0, windowSize.h + event.motion.yrel);
                        SDL_SetWindowSize(window, windowSize.w, windowSize.h);
                        origin = std::make_tuple(event.motion.x, event.motion.y);
                    } else if (moving) {
                        if (zooming) {
                            offset.x += event.motion.xrel;
                            offset.y += event.motion.yrel;
                            newImage(window, screen, *current, scale, offset);
                        } else if (((SDL_GetWindowFlags(window) & SDL_WINDOW_MAXIMIZED) == 0)) {
                            windowSize.x += event.motion.xrel;
                            windowSize.y += event.motion.yrel;
                            SDL_SetWindowPosition(window, windowSize.x, windowSize.y);
                        }
                    }

                    break;

                case SDL_WINDOWEVENT:
                    switch (event.window.event) {
                        case SDL_WINDOWEVENT_SIZE_CHANGED:
                            screen = SDL_GetWindowSurface(window);
                            newImage(window, screen, *current, scale, offset);
                            break;

                        default:
                            break;
                    }

                    break;

                default:
                    break;
            }
        }
    }

    SDL_SetRelativeMouseMode(SDL_FALSE);
    SDL_ShowCursor(1);

    IMG_Quit();

    SDL_DestroyWindow(window);
    SDL_Quit();

    return EXIT_SUCCESS;
}
<commit_msg>Remove unnecessary headers and code<commit_after>#include <algorithm>
#include <fstream>
#include <iostream>
#include <SDL.h>
#include <SDL_image.h>

#include "DirectoryScanner.hh"

const auto company = u8"即死ゲーム開発会社";
const auto product = "image viewer ++";
const int defaultWidth = 800;
const int defaultHeight = 600;

// TODO:
// - speed up
// - add support for (animated) .gif files

void newImage(SDL_Window *window, SDL_Surface *screen, const std::string &path, float scale, SDL_Rect &offset, bool resizeWindow = false)
{
    SDL_FillRect(screen, nullptr, 0);

   auto image = IMG_Load(path.c_str());

    SDL_Rect imageSize;

    SDL_GetClipRect(image, &imageSize);

    if (resizeWindow) {
        if (imageSize.w > imageSize.h) {
            auto width = defaultWidth;
            auto height = static_cast<int>(static_cast<float>(imageSize.h) / static_cast<float>(imageSize.w) * defaultWidth);
            SDL_SetWindowSize(window, width, height);
        } else {
            auto width = static_cast<int>(static_cast<float>(imageSize.w) / static_cast<float>(imageSize.h) * defaultHeight);
            auto height = defaultHeight;
            SDL_SetWindowSize(window, width, height);
        }

        screen = SDL_GetWindowSurface(window);
    }

    SDL_Rect windowSize;

    SDL_GetClipRect(screen, &windowSize);

    int windowWidth;
    int windowHeight;

    SDL_GetWindowSize(window, &windowWidth, &windowHeight);

    float imageWidthCorrected;
    float imageHeightCorrected;
    float imageWidthUnscaled = imageSize.w;
    float imageHeightUnscaled = imageSize.h;

    if (imageWidthUnscaled> imageHeightUnscaled) {
        imageWidthCorrected = static_cast<float>(windowWidth);
        imageHeightCorrected = static_cast<float>(windowWidth) * imageHeightUnscaled / imageWidthUnscaled;

        if (imageHeightCorrected > static_cast<float>(windowHeight)) {
            imageWidthCorrected = static_cast<float>(windowHeight) * imageWidthUnscaled / imageHeightUnscaled;
            imageHeightCorrected = static_cast<float>(windowHeight);
        }
    } else {
        imageWidthCorrected = static_cast<float>(windowHeight) * imageWidthUnscaled / imageHeightUnscaled;
        imageHeightCorrected = static_cast<float>(windowHeight);

        if (imageWidthCorrected > static_cast<float>(windowWidth)) {
            imageWidthCorrected = static_cast<float>(windowWidth);
            imageHeightCorrected = static_cast<float>(windowWidth) * imageHeightUnscaled / imageWidthUnscaled;
        }
    }

    float imageWidth = imageWidthCorrected * scale;
    float imageHeight = imageHeightCorrected * scale;
    float halfImageWidth = imageWidth / 2.0f;
    float halfImageHeight = imageHeight / 2.0f;
    float halfWindowWidth = windowWidth / 2.0f;
    float halfWindowHeight = windowHeight / 2.0f;
    float imageAbscissa = halfWindowWidth - halfImageWidth;
    float imageOrdinate = halfWindowHeight - halfImageHeight;

    if (scale > 1.0) {
        if (imageWidth >= windowWidth && offset.x - halfImageWidth + halfWindowWidth > 0.0f) {
            offset.x = static_cast<int>(halfImageWidth - halfWindowWidth);
        }

        if (imageHeight >= windowHeight && offset.y - halfImageHeight + halfWindowHeight > 0.0f) {
            offset.y = static_cast<int>(halfImageHeight - halfWindowHeight);
        }

        if (imageWidth >= windowWidth && offset.x + halfImageWidth - halfWindowWidth < 0.0f) {
            offset.x = static_cast<int>(halfWindowWidth - halfImageWidth);
        }

        if (imageHeight >= windowHeight && offset.y + imageHeight / 2.0 - halfWindowHeight < 0.0f) {
            offset.y = static_cast<int>(halfWindowHeight - halfImageHeight);
        }

        imageAbscissa = halfWindowWidth - halfImageWidth + offset.x;
        imageOrdinate = halfWindowHeight - halfImageHeight + offset.y;
    }

    SDL_Rect imagePosition;

    imagePosition.x = static_cast<int>(imageAbscissa);
    imagePosition.y = static_cast<int>(imageOrdinate);
    imagePosition.w = static_cast<int>(imageWidth);
    imagePosition.h = static_cast<int>(imageHeight);

    SDL_SetWindowTitle(window, path.c_str());

    SDL_BlitScaled(image, nullptr, screen, &imagePosition);

    SDL_FreeSurface(image);

    SDL_UpdateWindowSurface(window);

    SDL_FlushEvent(SDL_KEYDOWN);
    SDL_FlushEvent(SDL_MOUSEWHEEL);
    SDL_FlushEvent(SDL_MOUSEMOTION);
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        std::cerr << "usage: " << argv[0] << " <image>" << std::endl;

        return EXIT_FAILURE;
    }

    std::string argument(argv[1]);

    if (argument.find('\\') != std::string::npos) {
        std::replace(argument.begin(), argument.end(), '\\', '/');
    }

    auto lastSeparator = argument.rfind('/');
    std::string directory;

    if (lastSeparator != std::string::npos) {
        directory = argument.substr(0, lastSeparator);
    } else {
        directory = ".";
    }

    std::cout << directory << std::endl;

    SDL_Init(SDL_INIT_EVENTS | SDL_INIT_VIDEO);
    IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG);

    SDL_Rect windowSize = { 0 };
    windowSize.w = defaultWidth;
    windowSize.h = defaultHeight;

    SDL_Window *window = SDL_CreateWindow(product, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, defaultWidth,
        defaultHeight,
        SDL_WINDOW_BORDERLESS | SDL_WINDOW_OPENGL);
    SDL_Surface *screen = SDL_GetWindowSurface(window);

    auto path = SDL_GetPrefPath(company, product);

    auto pathFull = path + std::string("config.ini");

    std::cout << path << std::endl;

    SDL_RWops *file = SDL_RWFromFile(pathFull.c_str(), "w");

    SDL_RWwrite(file, "Hello, world!", 1, 13);
    SDL_RWclose(file);

    SDL_free(path);

    DirectoryScanner scanner(directory, 0);

    auto list = scanner.enumerate();
    auto current = std::find(list.cbegin(), list.cend(), argument);

    bool alive = true;
    bool zooming = false;
    bool resizing = false;
    bool moving = false;
    float scale = 1.0f;
    SDL_Rect offset = { 0 };

    newImage(window, screen, *current, scale, offset, true);

    while (alive) {
        SDL_Event event;

        while (SDL_PollEvent(&event)) {
            switch (event.type) {
                case SDL_KEYDOWN:
                    switch (event.key.keysym.sym) {
                        case SDLK_ESCAPE:
                            alive = false;
                            break;

                        case SDLK_LEFT:
                            if (current == list.cbegin()) {
                                current = list.cend();
                            }

                            --current;

                            scale = 1.0f;
                            offset = { 0 };
                            newImage(window, screen, *current, scale, offset);
                            break;

                        case SDLK_RIGHT:
                            ++current;

                            if (current == list.cend()) {
                                current = list.cbegin();
                            }

                            scale = 1.0f;
                            offset = { 0 };
                            newImage(window, screen, *current, scale, offset);
                            break;

                        case SDLK_TAB:
                            zooming = !zooming;

                            break;

                        case SDLK_LSHIFT:
                            resizing = true;
                            SDL_SetRelativeMouseMode(SDL_TRUE);

                            break;

                        case SDLK_LCTRL:
                            moving = true;
                            SDL_SetRelativeMouseMode(SDL_TRUE);

                            break;

                        case SDLK_SPACE:
                            if ((SDL_GetWindowFlags(window) & SDL_WINDOW_MAXIMIZED) == 0) {
                                newImage(window, screen, *current, scale, offset, true);
                            } else {
                                auto image = IMG_Load(current->c_str());

                                SDL_Rect imageSize;
                                SDL_Rect realWindowSize;
                                SDL_GetClipRect(image, &imageSize);
                                SDL_GetClipRect(screen, &realWindowSize);

                                SDL_FreeSurface(image);

                                scale = static_cast<float>(realWindowSize.w) / (static_cast<float>(realWindowSize.h) * static_cast<float>(imageSize.w) / static_cast<float>(imageSize.h));
                                offset.x = 0;
                                offset.y = static_cast<int>(static_cast<float>(imageSize.h) / 2.0f * scale);
                                newImage(window, screen, *current, scale, offset);
                            }

                            break;

                        default:
                            break;
                    }
                    break;

                case SDL_KEYUP:
                    if (event.key.keysym.sym == SDLK_LSHIFT) {
                        resizing = false;
                        SDL_SetRelativeMouseMode(SDL_FALSE);
                        SDL_WarpMouseInWindow(window, windowSize.w / 2, windowSize.h / 2);
                    } else if (event.key.keysym.sym == SDLK_LCTRL) {
                        moving = false;
                        SDL_SetRelativeMouseMode(SDL_FALSE);
                        SDL_WarpMouseInWindow(window, windowSize.w / 2, windowSize.h / 2);
                    }

                    break;

                case SDL_MOUSEWHEEL:
                    if (!zooming) {
                        if (event.wheel.y > 0) {
                            if (current == list.cbegin()) {
                                current = list.cend();
                            }

                            --current;
                        } else {
                            ++current;

                            if (current == list.cend()) {
                                current = list.cbegin();
                            }
                        }

                        scale = 1.0f;
                        offset = { 0 };
                        newImage(window, screen, *current, scale, offset);
                    } else {
                        if (event.wheel.y > 0) {
                            scale *= 1.4128f;
                        } else {
                            scale *= 0.7078143f;
                        }

                        newImage(window, screen, *current, scale, offset);
                    }

                    break;

                case SDL_MOUSEBUTTONDOWN:
                    switch (event.button.button) {
                        case SDL_BUTTON_LEFT:
                            if (event.button.clicks == 1) {
                                moving = true;
                                SDL_SetRelativeMouseMode(SDL_TRUE);
                            } else if (event.button.clicks == 2) {
                                if ((SDL_GetWindowFlags(window) & SDL_WINDOW_MAXIMIZED) == 0) {
                                    SDL_MaximizeWindow(window);
                                    SDL_Rect maximizedSize;
                                    SDL_Surface *maximizedScreen = SDL_GetWindowSurface(window);
                                    SDL_GetClipRect(maximizedScreen, &maximizedSize);
                                    SDL_WarpMouseInWindow(window, maximizedSize.w / 2, maximizedSize.h / 2);
                                } else {
                                    SDL_RestoreWindow(window);
                                    SDL_WarpMouseInWindow(window, windowSize.w / 2, windowSize.h / 2);
                                }
                            }

                            break;

                        case SDL_BUTTON_RIGHT:
                            resizing = true;
                            SDL_SetRelativeMouseMode(SDL_TRUE);

                            break;

                        case SDL_BUTTON_MIDDLE:
                            alive = false;

                            break;

                        default:
                            break;
                    }

                    break;

                case SDL_MOUSEBUTTONUP:
                    if (moving || resizing) {
                        SDL_SetRelativeMouseMode(SDL_FALSE);
                        SDL_WarpMouseInWindow(window, windowSize.w / 2, windowSize.h / 2);
                        SDL_FlushEvent(SDL_MOUSEBUTTONDOWN);
                    }

                    switch (event.button.button) {
                        case SDL_BUTTON_LEFT:
                            moving = false;

                            break;

                        case SDL_BUTTON_RIGHT:
                            resizing = false;

                            break;

                        default:
                            break;
                    }

                    break;

                case SDL_MOUSEMOTION:
                    if (((SDL_GetWindowFlags(window) & SDL_WINDOW_MAXIMIZED) == 0) && resizing) {
                        windowSize.w = std::max(0, windowSize.w + event.motion.xrel);
                        windowSize.h = std::max(0, windowSize.h + event.motion.yrel);
                        SDL_SetWindowSize(window, windowSize.w, windowSize.h);
                    } else if (moving) {
                        if (zooming) {
                            offset.x += event.motion.xrel;
                            offset.y += event.motion.yrel;
                            newImage(window, screen, *current, scale, offset);
                        } else if (((SDL_GetWindowFlags(window) & SDL_WINDOW_MAXIMIZED) == 0)) {
                            windowSize.x += event.motion.xrel;
                            windowSize.y += event.motion.yrel;
                            SDL_SetWindowPosition(window, windowSize.x, windowSize.y);
                        }
                    }

                    break;

                case SDL_WINDOWEVENT:
                    switch (event.window.event) {
                        case SDL_WINDOWEVENT_SIZE_CHANGED:
                            screen = SDL_GetWindowSurface(window);
                            newImage(window, screen, *current, scale, offset);
                            break;

                        default:
                            break;
                    }

                    break;

                default:
                    break;
            }
        }
    }

    SDL_SetRelativeMouseMode(SDL_FALSE);
    SDL_ShowCursor(1);

    IMG_Quit();

    SDL_DestroyWindow(window);
    SDL_Quit();

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <arm_neon.h>
#include "rng.hpp"

template <typename ST, typename DT>
inline DT cv_vpacks_(ST v0, ST v1)
{
	DT a;
	return a;
}

template <typename ST, typename DT>
inline DT cv_vpack_(ST v0, ST v1)
{
	DT a;
	return a;
}

template <>
inline uint16x8_t cv_vpacks_(uint32x4_t v0, uint32x4_t v1)
{
	return vcombine_u16(vqmovn_u32(v0), vqmovn_u32(v1));
}

template <>
inline uint8x16_t cv_vpacks_(uint16x8_t v0, uint16x8_t v1)
{
	return vcombine_u8(vqmovn_u16(v0), vqmovn_u16(v1));
}

template <>
inline int16x8_t cv_vpacks_(int32x4_t v0, int32x4_t v1)
{
	return vcombine_s16(vqmovn_s32(v0), vqmovn_s32(v1));
}

template <>
inline int8x16_t cv_vpacks_(int16x8_t v0, int16x8_t v1)
{
	return vcombine_s8(vqmovn_s16(v0), vqmovn_s16(v1));
}

template <>
inline uint16x8_t cv_vpack_(uint32x4_t v0, uint32x4_t v1)
{
	return vcombine_u16(vmovn_u32(v0), vmovn_u32(v1));
}

template <>
inline uint8x16_t cv_vpack_(uint16x8_t v0, uint16x8_t v1)
{
	return vcombine_u8(vmovn_u16(v0), vmovn_u16(v1));
}

template <>
inline int16x8_t cv_vpack_(int32x4_t v0, int32x4_t v1)
{
	return vcombine_s16(vmovn_s32(v0), vmovn_s32(v1));
}

template <>
inline int8x16_t cv_vpack_(int16x8_t v0, int16x8_t v1)
{
	return vcombine_s8(vmovn_s16(v0), vmovn_s16(v1));
}

template <typename ST>
void fill(ST* ptr, RNG& r)
{
	unsigned int cLoop = 16/sizeof(ST);
	for(unsigned int i = 0;i < cLoop;i++)
		ptr[i] = (r.next() & 0x7f);
}

template <typename ST, typename DT>
void debugPack(const ST* src0, const ST* src1, DT* dst)
{
	for(uint32_t i = 0;i < (16/sizeof(ST));i++)
	{
		dst[i*2  ] = (DT)(src0[i]);
		dst[i*2+1] = (DT)(src1[i]);
	}
}

template <typename ST, typename DT>
void dumpArray(const ST* src0, const ST* src1, const DT* dst)
{
	using namespace std;
	unsigned int srcLoop = 16/sizeof(ST);
	unsigned int dstLoop = 16/sizeof(DT);
	cout << "src0:";
	for(unsigned int i = 0;i < srcLoop;i++)
	{
		cout << '\t' << src0[i];
	}
	cout << endl;
	cout << "src1:";
	for(unsigned int i = 0;i < srcLoop;i++)
	{
		cout << '\t' << src1[i];
	}
	cout << endl;
	cout << "dst :";
	for(unsigned int i = 0;i < dstLoop;i++)
	{
		cout << '\t' << dst[i];
	}
	cout << endl;
}

template <typename ST, typename DT>
void verifyArray(ST* src0, ST* src1, DT* dst, RNG& r)
{
	fill(src0, r);
	fill(src1, r);
	debugPack((const ST*)src0, (const ST*)src1, (DT*)dst);
	dumpArray(src0, src1, dst);
}

int main(int argc, char** argv)
{
	RNG r(0x123);
	uint32_t src0[4], src1[4];
	uint16_t dst[8];
	verifyArray(src0, src1, dst, r);

	return 0;
}
<commit_msg>forgot to use unpack<commit_after>#include <iostream>
#include <arm_neon.h>
#include "rng.hpp"

inline uint32x4_t cv_vunpack_lo_u32(uint32x4_t v0, uint32x4_t v1)
{
	uint32x2x2_t result = vzip_u32(vget_low_u32(v0), vget_low_u32(v1));
	return vcombine_u32(result.val[0], result.val[1]);
}

inline uint32x4_t cv_vunpack_hi_u32(uint32x4_t v0, uint32x4_t v1)
{
	uint32x2x2_t result = vzip_u32(vget_high_u32(v0), vget_high_u32(v1));
	return vcombine_u32(result.val[0], result.val[1]);
}

inline uint16x8_t cv_vunpack_lo_u16(uint16x8_t v0, uint16x8_t v1)
{
	uint16x4x2_t result = vzip_u16(vget_low_u16(v0), vget_low_u16(v1));
	return vcombine_u16(result.val[0], result.val[1]);
}

inline uint16x8_t cv_vunpack_hi_u16(uint16x8_t v0, uint16x8_t v1)
{
	uint16x4x2_t result = vzip_u16(vget_high_u16(v0), vget_high_u16(v1));
	return vcombine_u16(result.val[0], result.val[1]);
}

inline uint8x16_t cv_vunpack_lo_u8(uint8x16_t v0, uint8x16_t v1)
{
	uint8x8x2_t result = vzip_u8(vget_low_u8(v0), vget_low_u8(v1));
	return vcombine_u8(result.val[0], result.val[1]);
}

inline uint8x16_t cv_vunpack_hi_u8(uint8x16_t v0, uint8x16_t v1)
{
	uint8x8x2_t result = vzip_u8(vget_high_u8(v0), vget_high_u8(v1));
	return vcombine_u8(result.val[0], result.val[1]);
}

inline int32x4_t cv_vunpack_lo_s32(int32x4_t v0, int32x4_t v1)
{
	int32x2x2_t result = vzip_s32(vget_low_s32(v0), vget_low_s32(v1));
	return vcombine_s32(result.val[0], result.val[1]);
}

inline int32x4_t cv_vunpack_hi_s32(int32x4_t v0, int32x4_t v1)
{
	int32x2x2_t result = vzip_s32(vget_high_s32(v0), vget_high_s32(v1));
	return vcombine_s32(result.val[0], result.val[1]);
}

inline int16x8_t cv_vunpack_lo_s16(int16x8_t v0, int16x8_t v1)
{
	int16x4x2_t result = vzip_s16(vget_low_s16(v0), vget_low_s16(v1));
	return vcombine_s16(result.val[0], result.val[1]);
}

inline int16x8_t cv_vunpack_hi_s16(int16x8_t v0, int16x8_t v1)
{
	int16x4x2_t result = vzip_s16(vget_high_s16(v0), vget_high_s16(v1));
	return vcombine_s16(result.val[0], result.val[1]);
}

inline int8x16_t cv_vunpack_lo_s8(int8x16_t v0, int8x16_t v1)
{
	int8x8x2_t result = vzip_s8(vget_low_s8(v0), vget_low_s8(v1));
	return vcombine_s8(result.val[0], result.val[1]);
}

inline int8x16_t cv_vunpack_hi_s8(int8x16_t v0, int8x16_t v1)
{
	int8x8x2_t result = vzip_s8(vget_high_s8(v0), vget_high_s8(v1));
	return vcombine_s8(result.val[0], result.val[1]);
}

inline uint16x8_t cv_vpacks_u32(uint32x4_t v0, uint32x4_t v1)
{
	return vcombine_u16(vqmovn_u32(v0), vqmovn_u32(v1));
}

inline uint8x16_t cv_vpacks_u16(uint16x8_t v0, uint16x8_t v1)
{
	return vcombine_u8(vqmovn_u16(v0), vqmovn_u16(v1));
}

inline int16x8_t cv_vpacks_s32(int32x4_t v0, int32x4_t v1)
{
	return vcombine_s16(vqmovn_s32(v0), vqmovn_s32(v1));
}

inline int8x16_t cv_vpacks_s16(int16x8_t v0, int16x8_t v1)
{
	return vcombine_s8(vqmovn_s16(v0), vqmovn_s16(v1));
}

inline uint16x8_t cv_vpack_u32(uint32x4_t v0, uint32x4_t v1)
{
	return vcombine_u16(vmovn_u32(v0), vmovn_u32(v1));
}

inline uint8x16_t cv_vpack_u16(uint16x8_t v0, uint16x8_t v1)
{
	return vcombine_u8(vmovn_u16(v0), vmovn_u16(v1));
}

inline int16x8_t cv_vpack_s32(int32x4_t v0, int32x4_t v1)
{
	return vcombine_s16(vmovn_s32(v0), vmovn_s32(v1));
}

inline int8x16_t cv_vpack_s16(int16x8_t v0, int16x8_t v1)
{
	return vcombine_s8(vmovn_s16(v0), vmovn_s16(v1));
}

template <typename ST>
void fill(ST* ptr, RNG& r)
{
	unsigned int cLoop = 16/sizeof(ST);
	for(unsigned int i = 0;i < cLoop;i++)
		ptr[i] = (r.next() & 0x7f);
}

template <typename T>
void debugUnpack(const T* src0, const T* src1, T* dst0, T* dst1)
{
	unsigned int cLoop = (16 / sizeof(T)) >> 1;
	for(unsigned int i = 0;i < cLoop;i++)
	{
		dst0[i*2  ] = src0[i];
		dst0[i*2+1] = src1[i];
		dst1[i*2  ] = src0[i+cLoop];
		dst1[i*2+1] = src1[i+cLoop];
	}
}

template <typename T>
void dumpArray(const char* header, const T* src0)
{
	using namespace std;
	unsigned int cLoop = 16/sizeof(T);
	cout << header;
	for(unsigned int i = 0;i < cLoop;i++)
	{
		cout << '\t' << src0[i];
	}
	cout << endl;
}

template <typename T>
void debugUnpackVector(const T* src0, const T* src1, T* dstLow, T* dstHigh)
{
	return;
}

template <typename ST, typename DT>
void debugVector(const ST* src0, const ST* src1, DT* dst)
{
	return;
}

template <>
void debugUnpackVector(const int32_t* src0, const int32_t* src1, int32_t* dstLow, int32_t* dstHigh)
{
	int32x4_t v0 = vld1q_s32(src0);
	int32x4_t v1 = vld1q_s32(src1);
	int32x4_t d0 = cv_vunpack_lo_s32(v0, v1);
	int32x4_t d1 = cv_vunpack_hi_s32(v0, v1);
	vst1q_s32(dstLow,  d0);
	vst1q_s32(dstHigh, d1);
	return;
}

template <>
void debugUnpackVector(const int16_t* src0, const int16_t* src1, int16_t* dstLow, int16_t* dstHigh)
{
	int16x8_t v0 = vld1q_s16(src0);
	int16x8_t v1 = vld1q_s16(src1);
	int16x8_t d0 = cv_vunpack_lo_s16(v0, v1);
	int16x8_t d1 = cv_vunpack_hi_s16(v0, v1);
	vst1q_s16(dstLow,  d0);
	vst1q_s16(dstHigh, d1);
	return;
}

template <>
void debugUnpackVector(const int8_t* src0, const int8_t* src1, int8_t* dstLow, int8_t* dstHigh)
{
	int8x16_t v0 = vld1q_s8(src0);
	int8x16_t v1 = vld1q_s8(src1);
	int8x16_t d0 = cv_vunpack_lo_s8(v0, v1);
	int8x16_t d1 = cv_vunpack_hi_s8(v0, v1);
	vst1q_s8(dstLow,  d0);
	vst1q_s8(dstHigh, d1);
	return;
}

template <>
void debugUnpackVector(const uint32_t* src0, const uint32_t* src1, uint32_t* dstLow, uint32_t* dstHigh)
{
	uint32x4_t v0 = vld1q_u32(src0);
	uint32x4_t v1 = vld1q_u32(src1);
	uint32x4_t d0 = cv_vunpack_lo_u32(v0, v1);
	uint32x4_t d1 = cv_vunpack_hi_u32(v0, v1);
	vst1q_u32(dstLow,  d0);
	vst1q_u32(dstHigh, d1);
	return;
}

template <>
void debugUnpackVector(const uint16_t* src0, const uint16_t* src1, uint16_t* dstLow, uint16_t* dstHigh)
{
	uint16x8_t v0 = vld1q_u16(src0);
	uint16x8_t v1 = vld1q_u16(src1);
	uint16x8_t d0 = cv_vunpack_lo_u16(v0, v1);
	uint16x8_t d1 = cv_vunpack_hi_u16(v0, v1);
	vst1q_u16(dstLow,  d0);
	vst1q_u16(dstHigh, d1);
	return;
}

template <>
void debugUnpackVector(const uint8_t* src0, const uint8_t* src1, uint8_t* dstLow, uint8_t* dstHigh)
{
	uint8x16_t v0 = vld1q_u8(src0);
	uint8x16_t v1 = vld1q_u8(src1);
	uint8x16_t d0 = cv_vunpack_lo_u8(v0, v1);
	uint8x16_t d1 = cv_vunpack_hi_u8(v0, v1);
	vst1q_u8(dstLow,  d0);
	vst1q_u8(dstHigh, d1);
	return;
}

template <>
void debugVector(const int32_t* src0, const int32_t* src1, int16_t* dst)
{
	int32x4_t v0 = vld1q_s32(src0);
	int32x4_t v1 = vld1q_s32(src1);
	int16x8_t d0 = cv_vpack_s32(v0, v1);
	vst1q_s16(dst, d0);
	return;
}

template <>
void debugVector(const int16_t* src0, const int16_t* src1, int8_t* dst)
{
	int16x8_t v0 = vld1q_s16(src0);
	int16x8_t v1 = vld1q_s16(src1);
	int8x16_t d0 = cv_vpack_s16(v0, v1);
	vst1q_s8(dst, d0);
	return;
}

template <>
void debugVector(const uint32_t* src0, const uint32_t* src1, uint16_t* dst)
{
	uint32x4_t v0 = vld1q_u32(src0);
	uint32x4_t v1 = vld1q_u32(src1);
	uint16x8_t d0 = cv_vpack_u32(v0, v1);
	vst1q_u16(dst, d0);
	return;
}

template <>
void debugVector(const uint16_t* src0, const uint16_t* src1, uint8_t* dst)
{
	uint16x8_t v0 = vld1q_u16(src0);
	uint16x8_t v1 = vld1q_u16(src1);
	uint8x16_t d0 = cv_vpack_u16(v0, v1);
	vst1q_u8(dst, d0);
	return;
}

template <typename T>
void verifyArray(T* src0, T* src1, T* dst_l, T* dst_h, T* dst_v0, T* dst_v1, RNG& r)
{
	fill(src0, r);
	fill(src1, r);
	debugUnpack((const T*)src0, (const T*)src1, (T*)dst_l,  (T*)dst_h);
	debugUnpackVector((const T*)src0, (const T*)src1, (T*)dst_v0, (T*)dst_v1);
	dumpArray("src0:", src0);
	dumpArray("src1:", src1);
	dumpArray("dstL:", dst_l);
	dumpArray("dstH:", dst_h);
	dumpArray("vec0:", dst_v0);
	dumpArray("vec1:", dst_v1);
}

int main(int argc, char** argv)
{
	RNG r(0x123);
	uint32_t src0[4],   src1[4];
	uint32_t dst_l[4],  dst_h[4];
	uint32_t dst_v0[4], dst_v1[4];
	verifyArray(src0, src1, dst_l, dst_h, dst_v0, dst_v1, r);

	return 0;
}
<|endoftext|>


<commit_before>//
//  main.cpp
//  NPointsToOrigin
//
//  Created by Teddy Engel on 22/02/2015.
//  Copyright (c) 2015 Teddy Engel. All rights reserved.
//

#include <vector>
#include <cmath>
#include <iostream>

// Our point class
class Point2D
{
public:
    Point2D(int x, int y)
    {
        this->x = x;
        this->y = y;
    }

    int x;
    int y;
};

// We don't need the exact distance, the pow-ed distance is fine for comparison
int DistanceToOrigin(const Point2D &point)
{
    return pow(point.x, 2) + pow(point.y, 2);
}

// We sort by the distance to origin, using a simple insertion sort
void SortByDistanceToOrigin(const std::vector<Point2D*> &input, std::vector<Point2D*> &output)
{
    for(auto &point : input)
    {
        int curDistance = DistanceToOrigin(*point);
        bool bInserted = false;
        int j = 0;

        for (auto &pointOutput: output)
        {
            int outputDistance = DistanceToOrigin(*pointOutput);

            if (curDistance < outputDistance && j > 0)
            {
                output.insert(output.begin()+(j), point);
                bInserted = true;
                break;
            }
            j++;
        }
        if (!bInserted)
        {
            output.push_back(point);
        }
    }
}

// Prints N elements from the vector collection
void PrintNElements(const std::vector<Point2D*> &elements, const int &n)
{
    for (int i = 0; i < elements.size() && i < n; i++)
    {
        std::cout << "(" << elements[i]->x << "," << elements[i]->y << ")" << std::endl;
    }
}

int main(int argc, const char * argv[]) {
    /* n closest points to origin */

    // Allocate points
    std::vector<Point2D*> points;
    points.push_back(new Point2D(1, 2));
    points.push_back(new Point2D(9, 4));
    points.push_back(new Point2D(1, 6));
    points.push_back(new Point2D(5, 8));
    points.push_back(new Point2D(3, 0));
    points.push_back(new Point2D(2, 2));
    points.push_back(new Point2D(1, 4));
    points.push_back(new Point2D(7, 6));
    points.push_back(new Point2D(2, 8));
    points.push_back(new Point2D(3, 1));
    points.push_back(new Point2D(6, 4));

    // Calculate n closest
    std::cout << "Our points:" << std::endl;
    for(auto &point : points)
    {
        std::cout << "(" << point->x << "," << point->y << ")" << std::endl;
    }

    // We sort the points by distance to origin in the closestPoints collection
    std::vector<Point2D*> closestPoints;
    SortByDistanceToOrigin(points, closestPoints);

    // And display the first N elements of the collection
    int n = 5;
    std::cout << "Closest " << n << " points to origin:" << std::endl;
    PrintNElements(closestPoints, n);

    // Delete points
    for(auto &point : points)
    {
        delete point;
    }
    closestPoints.clear();
    points.clear();

    return 0;
}
<commit_msg>- Update comments<commit_after>//
//  main.cpp
//  NPointsToOrigin
//
//  Created by Teddy Engel on 22/02/2015.
//  Copyright (c) 2015 Teddy Engel. All rights reserved.
//

#include <vector>
#include <cmath>
#include <iostream>

// Our point class
class Point2D
{
public:
    Point2D(int x, int y)
    {
        this->x = x;
        this->y = y;
    }

    int x;
    int y;
};

// We don't need the exact distance, the pow-ed distance is fine for comparison
int DistanceToOrigin(const Point2D &point)
{
    return pow(point.x, 2) + pow(point.y, 2);
}

// We sort by the distance to origin, using a simple insertion sort
void SortByDistanceToOrigin(const std::vector<Point2D*> &input, std::vector<Point2D*> &output)
{
    for(auto &point : input)
    {
        int curDistance = DistanceToOrigin(*point);
        bool bInserted = false;
        int j = 0;

        for (auto &pointOutput: output)
        {
            int outputDistance = DistanceToOrigin(*pointOutput);

            if (curDistance < outputDistance && j > 0)
            {
                output.insert(output.begin()+(j), point);
                bInserted = true;
                break;
            }
            j++;
        }
        if (!bInserted)
        {
            output.push_back(point);
        }
    }
}

// Prints N elements from the vector collection
void PrintNElements(const std::vector<Point2D*> &elements, const int &n)
{
    for (int i = 0; i < elements.size() && i < n; i++)
    {
        std::cout << "(" << elements[i]->x << "," << elements[i]->y << ")" << std::endl;
    }
}

int main(int argc, const char * argv[]) {
    /* n closest points to origin */

    // Allocate points
    std::vector<Point2D*> points;
    points.push_back(new Point2D(1, 2));
    points.push_back(new Point2D(9, 4));
    points.push_back(new Point2D(1, 6));
    points.push_back(new Point2D(5, 8));
    points.push_back(new Point2D(3, 0));
    points.push_back(new Point2D(2, 2));
    points.push_back(new Point2D(1, 4));
    points.push_back(new Point2D(7, 6));
    points.push_back(new Point2D(2, 8));
    points.push_back(new Point2D(3, 1));
    points.push_back(new Point2D(6, 4));

    // Display initial points
    std::cout << "Our points:" << std::endl;
    for(auto &point : points)
    {
        std::cout << "(" << point->x << "," << point->y << ")" << std::endl;
    }

    // We sort the points by distance and insert in the closestPoints collection
    std::vector<Point2D*> closestPoints;
    SortByDistanceToOrigin(points, closestPoints);

    // We display the first N elements of the collection
    int n = 5;
    std::cout << "Closest " << n << " points to origin:" << std::endl;
    PrintNElements(closestPoints, n);

    // Delete points
    for(auto &point : points)
    {
        delete point;
    }
    closestPoints.clear();
    points.clear();

    return 0;
}
<|endoftext|>


<commit_before>#include <GL/glew.h>
#include <GL/gl.h>
#include <iostream>
#include <string>

#include "display.h"
#include "renderobject.h"
#include "renderchain.h"
#include "sprite.h"
#include "utilities.hpp"

void dosomething()
{
	std::cout << "shit" << std::endl;
}

class ShittyObject : public RenderObject
{
public:
    ShittyObject()
    {
        m_VBO = 0;
		m_verts = nullptr;
    }

	~ShittyObject()
	{}

	bool InitObject()
	{
		m_verts = new Vector3f[3];

		m_verts[0] = Vector3f(-1.0f, -1.0f, 0.0f);
		m_verts[1] = Vector3f(1.0f, -1.0f, 0.0f);
		m_verts[2] = Vector3f(0.0f, 1.0f, 0.0f);

		glGenBuffers(1, &m_VBO);
		glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
		glBufferData(GL_ARRAY_BUFFER, sizeof(Vector3f) * 3, m_verts, GL_STATIC_DRAW);

		return true;
	}

	void Destroy()
	{
		glDeleteBuffers(1, &m_VBO);
	}

	void Render()
	{
		glEnableVertexAttribArray(0);
		glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
		glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
		glDrawArrays(GL_TRIANGLES, 0, 3);
		glDisableVertexAttribArray(0);
	}

private:
    GLuint m_VBO;
    Vector3f* m_verts;
};

int main(int argc, char **argv)
{
	Display* display = new Display();
	if(!display->InitDisplay(1280, 720, "OpenGL Game"))
	{
		std::cout << "Couldn't init display" << std::endl;
		return 1;
	}

	RenderChain* renderChain = new RenderChain();
	if(!renderChain->InitRenderChain(10))
	{
		std::cout << "Couldn't init render chain" << std::endl;
		return 1;
	}

	ShittyObject* obj = new ShittyObject();
	if(!obj->InitObject())
	{
		std::cout << "Couldn't init shitty object" << std::endl;
		return 1;
	}

	std::cout << "Information: " << std::endl;
	std::cout << "\tGL Version: " << glGetString(GL_VERSION) << std::endl;
	std::cout << "\tDisplay Address: " << display << std::endl;
	std::cout << "\tRender Chain Address: " << renderChain << std::endl;

	while(!display->IsClosed())
    {
		glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

		renderChain->AttachRenderObject(obj);
		renderChain->RenderObjectChain();

        display->Update();
    }

	obj->Destroy();
	SafeDelete(obj);
	renderChain->Destroy();
	SafeDelete(renderChain);
	display->Destroy();
	SafeDelete(display);
	return 0;
}
<commit_msg>Fixed merge conf<commit_after>#include <GL/glew.h>
#include <GL/gl.h>
#include <iostream>
#include <string>

#include "display.h"
#include "renderobject.h"
#include "renderchain.h"
#include "sprite.h"
#include "utilities.hpp"

class ShittyObject : public RenderObject
{
public:
    ShittyObject()
    {
        m_VBO = 0;
		m_verts = nullptr;
    }

	~ShittyObject()
	{}

	bool InitObject()
	{
		m_verts = new Vector3f[3];

		m_verts[0] = Vector3f(-1.0f, -1.0f, 0.0f);
		m_verts[1] = Vector3f(1.0f, -1.0f, 0.0f);
		m_verts[2] = Vector3f(0.0f, 1.0f, 0.0f);

		glGenBuffers(1, &m_VBO);
		glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
		glBufferData(GL_ARRAY_BUFFER, sizeof(Vector3f) * 3, m_verts, GL_STATIC_DRAW);

		return true;
	}

	void Destroy()
	{
		glDeleteBuffers(1, &m_VBO);
	}

	void Render()
	{
		glEnableVertexAttribArray(0);
		glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
		glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
		glDrawArrays(GL_TRIANGLES, 0, 3);
		glDisableVertexAttribArray(0);
	}

private:
    GLuint m_VBO;
    Vector3f* m_verts;
};

int main(int argc, char **argv)
{
	Display* display = new Display();
	if(!display->InitDisplay(1280, 720, "OpenGL Game"))
	{
		std::cout << "Couldn't init display" << std::endl;
		return 1;
	}

	RenderChain* renderChain = new RenderChain();
	if(!renderChain->InitRenderChain(10))
	{
		std::cout << "Couldn't init render chain" << std::endl;
		return 1;
	}

	ShittyObject* obj = new ShittyObject();
	if(!obj->InitObject())
	{
		std::cout << "Couldn't init shitty object" << std::endl;
		return 1;
	}

	std::cout << "Information: " << std::endl;
	std::cout << "\tGL Version: " << glGetString(GL_VERSION) << std::endl;
	std::cout << "\tDisplay Address: " << display << std::endl;
	std::cout << "\tRender Chain Address: " << renderChain << std::endl;

	while(!display->IsClosed())
    {
		glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

		renderChain->AttachRenderObject(obj);
		renderChain->RenderObjectChain();

        display->Update();
    }

	obj->Destroy();
	SafeDelete(obj);
	renderChain->Destroy();
	SafeDelete(renderChain);
	display->Destroy();
	SafeDelete(display);
	return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 Jussi Pakkanen.
 *
 * This file is part of mcdemo.
 *
 * Mcdemo is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License.
 *
 * Mcdemo 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with Mcdemo; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include<SDL.h>
#include<cstdio>
#include<cstdlib>

int main(int /*argc*/, char **/*argv*/) {
    if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_GAMECONTROLLER |
            SDL_INIT_JOYSTICK | SDL_INIT_AUDIO) != 0) {
        fprintf(stderr, "Could not initialize SDL: %s\n", SDL_GetError());
        return 1;
    }
    atexit(SDL_Quit);
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_DEBUG);
    return 0;
}
<commit_msg>Build window, renderer and main loop.<commit_after>/*
 * Copyright (c) 2015 Jussi Pakkanen.
 *
 * This file is part of mcdemo.
 *
 * Mcdemo is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License.
 *
 * Mcdemo 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with Mcdemo; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include<SDL.h>
#include<cstdio>
#include<cstdlib>
#include<memory>

const int SCREEN_WIDTH = 1920/2;
const int SCREEN_HEIGHT = 1080/2;
const uint32_t FTIME = (1000/60);

void mainloop(SDL_Window *win, SDL_Renderer *rend) {
    SDL_Event e;
    auto last_frame = SDL_GetTicks();
    SDL_RendererInfo f;
    SDL_GetRendererInfo(rend, &f);
    bool has_vsync = f.flags & SDL_RENDERER_PRESENTVSYNC;
    while(true) {
        while(SDL_PollEvent(&e)) {
            if(e.type == SDL_QUIT) {
                return;
            } else if(e.type == SDL_KEYDOWN) {
                switch(e.key.keysym.sym) {
                case  SDLK_ESCAPE:
                case  SDLK_q:
                    return;
                }
            } else if(e.type == SDL_JOYBUTTONDOWN) {
                return;
            }
        }

        if(!has_vsync) {
            auto time_spent = SDL_GetTicks() - last_frame;
            if(time_spent < FTIME) {
                SDL_Delay(FTIME - time_spent);
            }
        }
        last_frame = SDL_GetTicks(); // Not accurate, but I don't care.
    }
}

int main(int /*argc*/, char **/*argv*/) {
    if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_GAMECONTROLLER |
            SDL_INIT_JOYSTICK | SDL_INIT_AUDIO) != 0) {
        fprintf(stderr, "Could not initialize SDL: %s\n", SDL_GetError());
        return 1;
    }
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_DEBUG);
    atexit(SDL_Quit);
    std::unique_ptr<SDL_Window, void (*)(SDL_Window*)>
        win(SDL_CreateWindow("Mcdemo", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, 0),
                SDL_DestroyWindow);
    std::unique_ptr<SDL_Renderer, void (*)(SDL_Renderer*)> rend(SDL_CreateRenderer(win.get(), -1, SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC),
            SDL_DestroyRenderer);
    mainloop(win.get(), rend.get());
    return 0;
}
<|endoftext|>


<commit_before>5ff4bbba-2749-11e6-997e-e0f84713e7b8<commit_msg>Backup, rebase this later<commit_after>6003fdbd-2749-11e6-ad27-e0f84713e7b8<|endoftext|>


<commit_before>8d844921-4b02-11e5-8537-28cfe9171a43<commit_msg>I'm done<commit_after>8d926b4a-4b02-11e5-896c-28cfe9171a43<|endoftext|>


<commit_before>#include <QCoreApplication>
#include <QDomDocument>
#include <QStringList>
#include <QFile>
#include <QDir>
#include <iostream>

#include "protocolparser.h"
#include "xmllinelocator.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    ProtocolParser parser;

    // The list of arguments
    QStringList arguments = a.arguments();

    if(arguments.size() <= 1)
    {
        std::cout << "Protocol generator usage:" << std::endl;
        std::cout << "ProtoGen input.xml [outputpath] [-docs docspath] [-latex] [-no-doxygen] [-no-markdown] [-no-helper-files] [-no-unrecognized-warnings]" << std::endl;
        return 2;   // no input file
    }

    // We expect the input file here
    QString filename;

    // The output path
    QString path;

    // Skip the first argument "ProtoGen.exe"
    for(int i = 1; i < arguments.size(); i++)
    {
        QString arg = arguments.at(i);

        if(arg.contains("-no-doxygen", Qt::CaseInsensitive))
            parser.disableDoxygen(true);
        else if(arg.contains("-no-markdown", Qt::CaseInsensitive))
            parser.disableMarkdown(true);
        else if(arg.contains("-no-helper-files", Qt::CaseInsensitive))
            parser.disableHelperFiles(true);
        else if(arg.endsWith(".xml"))
            filename = arg;
        else if (arg.contains("-latex", Qt::CaseInsensitive))
            parser.setLaTeXSupport(true);
        else if (arg.contains("-no-unrecognized-warnings", Qt::CaseInsensitive))
            parser.disableUnrecognizedWarnings(true);
        else if(arg.endsWith(".css"))
        {
            QFile file(arg);
            if(file.open(QIODevice::ReadOnly | QIODevice::Text))
            {
                parser.setInlineCSS(file.readAll());
                file.close();
            }
            else
                std::cerr << "warning: Failed to open " << QDir::toNativeSeparators(arg).toStdString() << ", using default css" << std::endl;
        }
        else if (arg.startsWith("-docs"))
        {
            // Is there an argument following this?
            if (arguments.size() > (i + 1))
            {
                // The following argument is the directory path for documents
                QString docs = ProtocolFile::sanitizePath(arguments.at(++i));

                // If the directory already exists, or we can make it, then use it
                if(QDir::current().mkdir(docs))
                    parser.setDocsPath(docs);
            }
        }
        else if((path.isEmpty()) && (arg != filename))
            path = arg;

    }// for all input arguments

    if(!filename.isEmpty())
    {
        if(parser.parse(filename, path))
            return 0;   // normal exit
        else
            return 1;   // input file in error
    }
    else
    {
        std::cerr << "error: must provide a protocol (*.xml) file." << std::endl;
        return 2;   // no input file
    }

}
<commit_msg>Added case to catch docs directory if it already exists (Note: mkdir() returns FALSE if the directory already exists!!)<commit_after>#include <QCoreApplication>
#include <QDomDocument>
#include <QStringList>
#include <QFile>
#include <QDir>
#include <iostream>

#include "protocolparser.h"
#include "xmllinelocator.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    ProtocolParser parser;

    // The list of arguments
    QStringList arguments = a.arguments();

    if(arguments.size() <= 1)
    {
        std::cout << "Protocol generator usage:" << std::endl;
        std::cout << "ProtoGen input.xml [outputpath] [-docs docspath] [-latex] [-no-doxygen] [-no-markdown] [-no-helper-files] [-no-unrecognized-warnings]" << std::endl;
        return 2;   // no input file
    }

    // We expect the input file here
    QString filename;

    // The output path
    QString path;

    // Skip the first argument "ProtoGen.exe"
    for(int i = 1; i < arguments.size(); i++)
    {
        QString arg = arguments.at(i);

        if(arg.contains("-no-doxygen", Qt::CaseInsensitive))
            parser.disableDoxygen(true);
        else if(arg.contains("-no-markdown", Qt::CaseInsensitive))
            parser.disableMarkdown(true);
        else if(arg.contains("-no-helper-files", Qt::CaseInsensitive))
            parser.disableHelperFiles(true);
        else if(arg.endsWith(".xml"))
            filename = arg;
        else if (arg.contains("-latex", Qt::CaseInsensitive))
            parser.setLaTeXSupport(true);
        else if (arg.contains("-no-unrecognized-warnings", Qt::CaseInsensitive))
            parser.disableUnrecognizedWarnings(true);
        else if(arg.endsWith(".css"))
        {
            QFile file(arg);
            if(file.open(QIODevice::ReadOnly | QIODevice::Text))
            {
                parser.setInlineCSS(file.readAll());
                file.close();
            }
            else
                std::cerr << "warning: Failed to open " << QDir::toNativeSeparators(arg).toStdString() << ", using default css" << std::endl;
        }
        else if (arg.startsWith("-docs"))
        {
            // Is there an argument following this?
            if (arguments.size() > (i + 1))
            {
                // The following argument is the directory path for documents
                QString docs = ProtocolFile::sanitizePath(arguments.at(++i));

                // If the directory already exists, or we can make it, then use it
                if(QDir(docs).exists() ||  QDir::current().mkdir(docs))
                    parser.setDocsPath(docs);
            }
        }
        else if((path.isEmpty()) && (arg != filename))
            path = arg;

    }// for all input arguments

    if(!filename.isEmpty())
    {
        if(parser.parse(filename, path))
            return 0;   // normal exit
        else
            return 1;   // input file in error
    }
    else
    {
        std::cerr << "error: must provide a protocol (*.xml) file." << std::endl;
        return 2;   // no input file
    }

}
<|endoftext|>


<commit_before>#ifdef _DEBUG
#include "testdatapath.h"
#endif

#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>

using namespace std;

int showImage(const cv::Mat& image, int wait = 0){
	static const string wname("EBookChecker");

	cv::imshow(wname, image);
	return cv::waitKey(wait);
}

int main(int argc, char** argv)
{

#ifndef _DEBUG
	string commandArgs =
		"@input |  | processing one image or image named serial number"
		;

	cv::CommandLineParser parser(argc, argv, commandArgs);

	string src = parser.get<string>(0);
#endif
	string src = TEST_DATA_0;

	cout << "input file:" << src << endl;

	cv::Mat image = cv::imread(src, CV_LOAD_IMAGE_GRAYSCALE);
	CV_Assert(image.channels() == 1 && image.type() == CV_8UC1);
	showImage(image);

	cv::Mat binary;
	int binaryMax = 255;
	int binaryThreshold = 128;
	cv::threshold(image, binary, binaryThreshold, binaryMax, cv::THRESH_BINARY_INV);
	CV_Assert(binary.channels() == 1 && image.type() == CV_8UC1);
	showImage(binary);
	cv::imwrite("binary.jpg", binary);

	cv::Mat integral;
	cv::integral(binary, integral);
	CV_Assert(integral.channels() == 1 && integral.type() == CV_32SC1);
	showImage(integral);
	cv::imwrite("integral.jpg", integral);
}<commit_msg>二値化時の最大値を1に。 積分画像を見やすくする処理を追加。 コメントも追加。 デバッグ時のマクロが間違っていたので修正<commit_after>#ifdef _DEBUG
#include "testdatapath.h"
#endif

#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>

using namespace std;

//摜\p֐
int showImage(const cv::Mat& image, int wait = 0){
	static const string wname("EBookChecker");

	cv::imshow(wname, image);
	return cv::waitKey(wait);
}

int main(int argc, char** argv)
{

#ifndef _DEBUG
	//R}hC̉́BfobO͎̎gȂ
	string commandArgs =
		"@input |  | processing one image or image named serial number"
		;

	cv::CommandLineParser parser(argc, argv, commandArgs);

	string src = parser.get<string>(0);
#else
	string src = TEST_DATA_0;
#endif

	cout << "input file:" << src << endl;

	//摜̓ǂݍ݁BO[XP[摜Ƃēǂݍ
	cv::Mat image = cv::imread(src, CV_LOAD_IMAGE_GRAYSCALE);
	CV_Assert(image.channels() == 1 && image.type() == CV_8UC1);
	showImage(image);

	//l
	cv::Mat binary;
	int binaryMax = 1;//l̍ől1ɁBϕƂɔƂ납Ƃ납킩΂B
	int binaryThreshold = 128;
	cv::threshold(image, binary, binaryThreshold, binaryMax, cv::THRESH_BINARY_INV);
	CV_Assert(binary.channels() == 1 && image.type() == CV_8UC1);
	showImage(binary);
	cv::imwrite("binary.jpg", binary);

	//ϕ摜̐
	cv::Mat integral;
	cv::integral(binary, integral);
	CV_Assert(integral.channels() == 1 && integral.type() == CV_32SC1);
	showImage(integral);
	cv::imwrite("integral.jpg", integral);

	//ϕ摜₷鏈
	cv::Mat integralVisible;
	double max;
	double min;
	cv::minMaxLoc(integral, &min, &max);//őlق̂ő3܂ŁBŏl0̂͂{0mF邽߂Ɏg
	CV_Assert(min == 0.0);//{ɍŏl0ɂȂĂ邩mF

	integral.convertTo(integralVisible, CV_8UC1, 255.0 / max); //beta͎gȂB0-255̒lƂ悤alpha^B
	showImage(integralVisible);
	cv::imwrite("integralVisible.jpg", integralVisible);

}<|endoftext|>


<commit_before>#include "common.h"
#include "bmpio.h"
#include "tracer.h"
#include "world.h"

using namespace std;

World world;
Bmp bmp;
Tracer tracer;
Camera camera;

char param[Cmd_length],res[Cmd_length];

int main(){
	//scanf("%s%s",param,res);
	world.CreateWorld("sample.txt");
	bmp.Initialize(camera.iheight,camera.iwidth);
	camera.Shooting();
	/*
	for(int j = 0;j < H;++ j)
		for(int i = 0;i < W;++ i)
			printf("%d %d %d\n",bmp.pic[i * H + j].red,bmp.pic[i * H + j].green,bmp.pic[i * H + j].blue);
	*/
	bmp.Output("result.bmp");
	return 0;
}
<commit_msg>Change the command<commit_after>#include "common.h"
#include "bmpio.h"
#include "tracer.h"
#include "world.h"

using namespace std;

World world;
Bmp bmp;
Tracer tracer;
Camera camera;

char param[Cmd_length],res[Cmd_length];

int main(){
	scanf("%s%s",param,res);
	world.CreateWorld(param);
	bmp.Initialize(camera.iheight,camera.iwidth);
	camera.Shooting();
	/*
	for(int j = 0;j < H;++ j)
		for(int i = 0;i < W;++ i)
			printf("%d %d %d\n",bmp.pic[i * H + j].red,bmp.pic[i * H + j].green,bmp.pic[i * H + j].blue);
	*/
	bmp.Output(res);
	puts("The Image is generated.Just enjoy your imagination!");
	getchar();
	puts("Press any key to close this window."); getchar();
	return 0;
}
<|endoftext|>


<commit_before>7559d554-4b02-11e5-a8ec-28cfe9171a43<commit_msg>This'll fix that<commit_after>7565f49c-4b02-11e5-8b41-28cfe9171a43<|endoftext|>


<commit_before>30f8c20f-ad59-11e7-93d7-ac87a332f658<commit_msg>this is my first commit?<commit_after>317692cf-ad59-11e7-90c4-ac87a332f658<|endoftext|>


<commit_before>// CS184 Simple OpenGL Example
#include <cstdlib>  //for rand

//#include "CImg.h"  //to get rgba data
//using namespace cimg_library;

#include <vector>
#include <iostream>
#include <fstream>
#include <cmath>
#include <string>
#include <cstring>
#include <stdlib.h>
#include <sstream>
#include <iterator>

#ifdef _WIN32
#include <windows.h>
#else
#include <sys/time.h>
#endif

#ifdef OSX
#include <GLUT/glut.h>
#include <OpenGL/glu.h>
#else
#include <GL/glut.h>
#include <GL/glu.h>
#endif

#include <time.h>
#include <math.h>

#include "bezier.h"
#include "utility.h"

#ifdef _WIN32
static DWORD lastTime;
#else
static struct timeval lastTime;
#endif
using namespace std;
#define PI 3.14159265
//load structure of models->patchs->curves->vertex

//****************************************************
// Global Variables
//****************************************************

string input_file_name;
float sub_div_parameter;
// switch from uniform to adaptive mode
bool adaptive = false;

//****************************************************
// Some Classes
//****************************************************

class Viewport {
  public:
    int w, h; // width and height
};
Viewport viewport;

//****************************************************
// Some Functions
//****************************************************

void parseCommandlineArguments(int argc, char *argv[]) {
  if(argc < 3) {
    printf("\nWrong number of command-line arguments. Arguments should be in the format:\n");
    printf("main [inputfile.bez] [float subdivision parameter] optional[-a]\n\n");
    exit(0);
  }
  input_file_name = argv[1];
  sub_div_parameter = atof(argv[2]);

  if(argc == 4 && strcmp(argv[3],"-a")) {
    adaptive = true;
  }
}

vector<string> splitAtWhiteSpace(string const &input) {
    istringstream buffer(input);
    vector<string> ret((istream_iterator<string>(buffer)), istream_iterator<string>());
    return ret;
}

void parseInputFile() {}
/* wants a char array   const char*
void parseInputFile() {
  ifstream input_file("models/" + input_file_name);
  string line;
  if(input_file.is_open()) {
    int numPatches = 0;
    getline(input_file, line);
    numPatches = atoi(line.c_str());

    for (int i = 0; i < numPatches; i++){
        float point_array[4][4];
        for(int c = 0; c < 4; c++) {
            getline(input_file, line);
            vector<string> coor_list;
            coor_list = splitAtWhiteSpace(line);
            for(int p = 0; p < 4; p++) {
                float x = atof(coor_list[p + 3*c].c_str());
                float y = atof(coor_list[p + 3*c].c_str());
                float z = atof(coor_list[p + 3*c].c_str());
                Point point(x, y, z);
                cout << x << " " << y << " " << z << "\n";
            }
            //float curve[4] = {atof(coor_list[0].c_str()), atof(coor_list[1]), atof(coor_list[2]), atof(coor_list[3])};
            //point_array[c] = curve;
        }
        //blank line
        getline(input_file, line);
    }
    input_file.close();
  }

}
*/

//****************************************************
// keyboard functions
//****************************************************

void special_keyboard(int key, int x, int y){

  switch(key){
  case GLUT_KEY_RIGHT:
    if(glutGetModifiers() == GLUT_ACTIVE_SHIFT) {
      printf("object will be translated right\n");
      break;
    }
    printf("object will be rotated right\n");
    break;
  case GLUT_KEY_LEFT:
    if(glutGetModifiers() == GLUT_ACTIVE_SHIFT) {
      printf("object will be translated left\n");
      break;
    }
    printf("object will be rotated left\n");
    break;
  case GLUT_KEY_UP:
    if(glutGetModifiers() == GLUT_ACTIVE_SHIFT) {
      printf("object will be translated up\n");
      break;
    }
    printf("object will be rotated up\n");
    break;
  case GLUT_KEY_DOWN:
    if(glutGetModifiers() == GLUT_ACTIVE_SHIFT) {
      printf("object will be translated down\n");
      break;
    }
    printf("object will be rotated down\n");
    break;
  }

}

void keyboard(unsigned char key, int x, int y){
  switch(key){
  case 's':
    printf("toggle between flat and smooth shading\n");
    break;
  case 'w':
    printf("toggle between filled and wireframe mode.\n");
    break;
  case 'c':
    printf("do vertex color shading based on the Gaussian Curvature of the surface.\n");
    break;
  case 43:
    // PLUS sign +
    printf("zoom in\n");
    break;
  case 45:
    // MINUS sign -
    printf("zoom out\n");
    break;
  }
}

//****************************************************
// reshape viewport if the window is resized
//****************************************************
void myReshape(int w, int h) {
  viewport.w = w;
  viewport.h = h;

  glViewport(0,0,viewport.w,viewport.h);// sets the rectangle that will be the window
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();                // loading the identity matrix for the screen

  //----------- setting the projection -------------------------
  // glOrtho sets left, right, bottom, top, zNear, zFar of the chord system

  // glOrtho(-1, 1 + (w-400)/200.0 , -1 -(h-400)/200.0, 1, 1, -1); // resize type = add
  // glOrtho(-w/400.0, w/400.0, -h/400.0, h/400.0, 1, -1); // resize type = center

  glOrtho(-1, 1, -1, 1, 1, -1);    // resize type = stretch

  //------------------------------------------------------------
}

//****************************************************
// sets the window up
//****************************************************
void initScene(){
  glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Clear to black, fully transparent

  myReshape(viewport.w,viewport.h);
}

//***************************************************
// function that does the actual drawing
//***************************************************
void myDisplay() {

  //----------------------- ----------------------- -----------------------
  // This is a quick hack to add a little bit of animation.
  static float tip = 0.5f;
  const  float stp = 0.01f;
  const  float beg = 0.1f;
  const  float end = 0.9f;

  tip += stp;
  if (tip>end) tip = beg;
  //----------------------- ----------------------- -----------------------

  glClear(GL_COLOR_BUFFER_BIT);                // clear the color buffer (sets everything to black)

  glMatrixMode(GL_MODELVIEW);                  // indicate we are specifying camera transformations
  glLoadIdentity();                            // make sure transformation is "zero'd"

  //-----------------------------------------------------------------------

  glFlush();
  glutSwapBuffers();                           // swap buffers (we earlier set double buffer)
}

//****************************************************
// called by glut when there are no messages to handle
//****************************************************
void myFrameMove() {
  //nothing here for now
#ifdef _WIN32
  Sleep(10);                                   //give ~10ms back to OS (so as not to waste the CPU)
#endif
  glutPostRedisplay(); // forces glut to call the display function (myDisplay())
}

//****************************************************
// the usual stuff, nothing exciting here
//****************************************************
int main(int argc, char *argv[]) {

  parseCommandlineArguments(argc, argv);

  parseInputFile();

  //This initializes glut
  glutInit(&argc, argv);

  //This tells glut to use a double-buffered window with red, green, and blue channels
  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);

  // Initalize theviewport size
  viewport.w = 1000;//1280
  viewport.h = 1000;

  //The size and position of the window
  glutInitWindowSize(viewport.w, viewport.h);
  glutInitWindowPosition(0, 0);
  glutCreateWindow("CS184! by Sebastian and Risa");

  initScene();                                 // quick function to set up scene
  glutDisplayFunc(myDisplay);                  // function to run when its time to draw something
  glutReshapeFunc(myReshape);                  // function to run when the window gets resized

  glutKeyboardFunc(keyboard);
  glutSpecialFunc(special_keyboard);

  glutIdleFunc(myFrameMove);                   // function to run when not handling any other task
  glutMainLoop();                              // infinite loop that will keep drawing and resizing and whatever else

  return 0;
}

<commit_msg>Finished code to parse input file<commit_after>// CS184 Simple OpenGL Example
#include <cstdlib>  //for rand

//#include "CImg.h"  //to get rgba data
//using namespace cimg_library;

#include <vector>
#include <iostream>
#include <fstream>
#include <cmath>
#include <string>
#include <cstring>
#include <stdlib.h>
#include <sstream>
#include <iterator>

#ifdef _WIN32
#include <windows.h>
#else
#include <sys/time.h>
#endif

#ifdef OSX
#include <GLUT/glut.h>
#include <OpenGL/glu.h>
#else
#include <GL/glut.h>
#include <GL/glu.h>
#endif

#include <time.h>
#include <math.h>

#include "bezier.h"
#include "utility.h"

#ifdef _WIN32
static DWORD lastTime;
#else
static struct timeval lastTime;
#endif
using namespace std;
#define PI 3.14159265
//load structure of models->patchs->curves->vertex

//****************************************************
// Global Variables
//****************************************************

string input_file_name;
float sub_div_parameter;
// switch from uniform to adaptive mode
bool adaptive = false;

//****************************************************
// Some Classes
//****************************************************

class Viewport {
  public:
    int w, h; // width and height
};
Viewport viewport;

//****************************************************
// Some Functions
//****************************************************

void parseCommandlineArguments(int argc, char *argv[]) {
  if(argc < 3) {
    printf("\nWrong number of command-line arguments. Arguments should be in the format:\n");
    printf("main [inputfile.bez] [float subdivision parameter] optional[-a]\n\n");
    exit(0);
  }
  input_file_name = argv[1];
  sub_div_parameter = atof(argv[2]);

  if(argc == 4 && strcmp(argv[3],"-a")) {
    adaptive = true;
  }
}

vector<string> splitAtWhiteSpace(string const &input) {
    istringstream buffer(input);
    vector<string> ret((istream_iterator<string>(buffer)), istream_iterator<string>());
    return ret;
}

Model parseInputFile() {
  ifstream input_file(input_file_name);
  string line;
  if(input_file.is_open()) {
    int numPatches = 0;
    getline(input_file, line);
    numPatches = atoi(line.c_str());
    vector<Patch> patches;
    for (int i = 0; i < numPatches; i++){
        Point point_array[4][4];
        for(int c = 0; c < 4; c++) {
            getline(input_file, line);
            vector<string> coor_list;
            coor_list = splitAtWhiteSpace(line);

            for(int p = 0; p < 4; p++) {
                float x = atof(coor_list[3*p].c_str());
                float y = atof(coor_list[3*p+1].c_str());
                float z = atof(coor_list[3*p+2].c_str());
                Point point(x, y, z);
                point_array[c][p] = point;
            }
        }
        Patch patch(point_array);
        patches.push_back(patch);

        getline(input_file, line); //blank line between patches
    }
    input_file.close();
    Model model(patches, Color(0, 1, 0));
    return model;
  }
  printf("input file was not found\n");
  exit(1);
}

//****************************************************
// keyboard functions
//****************************************************

void special_keyboard(int key, int x, int y){

  switch(key){
  case GLUT_KEY_RIGHT:
    if(glutGetModifiers() == GLUT_ACTIVE_SHIFT) {
      printf("object will be translated right\n");
      break;
    }
    printf("object will be rotated right\n");
    break;
  case GLUT_KEY_LEFT:
    if(glutGetModifiers() == GLUT_ACTIVE_SHIFT) {
      printf("object will be translated left\n");
      break;
    }
    printf("object will be rotated left\n");
    break;
  case GLUT_KEY_UP:
    if(glutGetModifiers() == GLUT_ACTIVE_SHIFT) {
      printf("object will be translated up\n");
      break;
    }
    printf("object will be rotated up\n");
    break;
  case GLUT_KEY_DOWN:
    if(glutGetModifiers() == GLUT_ACTIVE_SHIFT) {
      printf("object will be translated down\n");
      break;
    }
    printf("object will be rotated down\n");
    break;
  }

}

void keyboard(unsigned char key, int x, int y){
  switch(key){
  case 's':
    printf("toggle between flat and smooth shading\n");
    break;
  case 'w':
    printf("toggle between filled and wireframe mode.\n");
    break;
  case 'c':
    printf("do vertex color shading based on the Gaussian Curvature of the surface.\n");
    break;
  case 43:
    // PLUS sign +
    printf("zoom in\n");
    break;
  case 45:
    // MINUS sign -
    printf("zoom out\n");
    break;
  }
}

//****************************************************
// reshape viewport if the window is resized
//****************************************************
void myReshape(int w, int h) {
  viewport.w = w;
  viewport.h = h;

  glViewport(0,0,viewport.w,viewport.h);// sets the rectangle that will be the window
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();                // loading the identity matrix for the screen

  //----------- setting the projection -------------------------
  // glOrtho sets left, right, bottom, top, zNear, zFar of the chord system

  // glOrtho(-1, 1 + (w-400)/200.0 , -1 -(h-400)/200.0, 1, 1, -1); // resize type = add
  // glOrtho(-w/400.0, w/400.0, -h/400.0, h/400.0, 1, -1); // resize type = center

  glOrtho(-1, 1, -1, 1, 1, -1);    // resize type = stretch

  //------------------------------------------------------------
}

//****************************************************
// sets the window up
//****************************************************
void initScene(){
  glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Clear to black, fully transparent

  myReshape(viewport.w,viewport.h);
}

//***************************************************
// function that does the actual drawing
//***************************************************
void myDisplay() {

  //----------------------- ----------------------- -----------------------
  // This is a quick hack to add a little bit of animation.
  static float tip = 0.5f;
  const  float stp = 0.01f;
  const  float beg = 0.1f;
  const  float end = 0.9f;

  tip += stp;
  if (tip>end) tip = beg;
  //----------------------- ----------------------- -----------------------

  glClear(GL_COLOR_BUFFER_BIT);                // clear the color buffer (sets everything to black)

  glMatrixMode(GL_MODELVIEW);                  // indicate we are specifying camera transformations
  glLoadIdentity();                            // make sure transformation is "zero'd"

  //-----------------------------------------------------------------------

  glFlush();
  glutSwapBuffers();                           // swap buffers (we earlier set double buffer)
}

//****************************************************
// called by glut when there are no messages to handle
//****************************************************
void myFrameMove() {
  //nothing here for now
#ifdef _WIN32
  Sleep(10);                                   //give ~10ms back to OS (so as not to waste the CPU)
#endif
  glutPostRedisplay(); // forces glut to call the display function (myDisplay())
}

//****************************************************
// the usual stuff, nothing exciting here
//****************************************************
int main(int argc, char *argv[]) {

  parseCommandlineArguments(argc, argv);

  Model model = parseInputFile();

  //This initializes glut
  glutInit(&argc, argv);

  //This tells glut to use a double-buffered window with red, green, and blue channels
  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);

  // Initalize theviewport size
  viewport.w = 1000;//1280
  viewport.h = 1000;

  //The size and position of the window
  glutInitWindowSize(viewport.w, viewport.h);
  glutInitWindowPosition(0, 0);
  glutCreateWindow("CS184! by Sebastian and Risa");

  initScene();                                 // quick function to set up scene
  glutDisplayFunc(myDisplay);                  // function to run when its time to draw something
  glutReshapeFunc(myReshape);                  // function to run when the window gets resized

  glutKeyboardFunc(keyboard);
  glutSpecialFunc(special_keyboard);

  glutIdleFunc(myFrameMove);                   // function to run when not handling any other task
  glutMainLoop();                              // infinite loop that will keep drawing and resizing and whatever else

  return 0;
}

<|endoftext|>