Example usage for org.lwjgl.opengl GLUtil setupDebugMessageCallback

List of usage examples for org.lwjgl.opengl GLUtil setupDebugMessageCallback

Introduction

In this page you can find the example usage for org.lwjgl.opengl GLUtil setupDebugMessageCallback.

Prototype

@Nullable
public static Callback setupDebugMessageCallback() 

Source Link

Document

Detects the best debug output functionality to use and creates a callback that prints information to APIUtil#DEBUG_STREAM .

Usage

From source file:TruetypeOversample.java

License:Open Source License

private void createWindow(String title) {
    glfwSetErrorCallback(errorfun);/*from   ww  w .  j a  va 2  s.co m*/

    if (glfwInit() != GLFW_TRUE)
        throw new IllegalStateException("Unable to initialize GLFW");

    glfwDefaultWindowHints();
    glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
    glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
    this.window = glfwCreateWindow(ww, wh, title, NULL, NULL);

    if (window == NULL)
        throw new RuntimeException("Failed to create the GLFW window");

    windowSizefun.set(window);
    framebufferSizefun.set(window);
    keyfun.set(window);
    GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
    glfwSetWindowPos(window, (vidmode.width() - ww) / 2, (vidmode.height() - wh) / 2);
    glfwMakeContextCurrent(window);
    GL.createCapabilities();
    debugProc = GLUtil.setupDebugMessageCallback();
    glfwSwapInterval(1);
    glfwShowWindow(window);
    glfwInvoke(window, windowSizefun, framebufferSizefun);

    // Detect sRGB support
    GLCapabilities caps = GL.getCapabilities();
    supportsSRGB = caps.OpenGL30 || caps.GL_ARB_framebuffer_sRGB || caps.GL_EXT_framebuffer_sRGB;
}

From source file:EnvironmentTeapotDemo.java

License:Open Source License

void init() throws IOException {
    if (!glfwInit())
        throw new IllegalStateException("Unable to initialize GLFW");

    glfwDefaultWindowHints();/*from  w  ww .  j a  va2s  . c  o m*/
    glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
    glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
    window = glfwCreateWindow(width, height, "Spherical environment mapping with teapot demo", NULL, NULL);
    if (window == NULL)
        throw new AssertionError("Failed to create the GLFW window");

    System.out.println("Move the mouse to look around");
    System.out.println("Zoom in/out with mouse wheel");
    glfwSetFramebufferSizeCallback(window, fbCallback = new GLFWFramebufferSizeCallback() {
        @Override
        public void invoke(long window, int width, int height) {
            if (width > 0 && height > 0 && (EnvironmentTeapotDemo.this.fbWidth != width
                    || EnvironmentTeapotDemo.this.fbHeight != height)) {
                EnvironmentTeapotDemo.this.fbWidth = width;
                EnvironmentTeapotDemo.this.fbHeight = height;
            }
        }
    });
    glfwSetWindowSizeCallback(window, wsCallback = new GLFWWindowSizeCallback() {
        @Override
        public void invoke(long window, int width, int height) {
            if (width > 0 && height > 0 && (EnvironmentTeapotDemo.this.width != width
                    || EnvironmentTeapotDemo.this.height != height)) {
                EnvironmentTeapotDemo.this.width = width;
                EnvironmentTeapotDemo.this.height = height;
            }
        }
    });
    glfwSetKeyCallback(window, keyCallback = new GLFWKeyCallback() {
        @Override
        public void invoke(long window, int key, int scancode, int action, int mods) {
            if (action != GLFW_RELEASE)
                return;
            if (key == GLFW_KEY_ESCAPE) {
                glfwSetWindowShouldClose(window, true);
            }
        }
    });
    glfwSetCursorPosCallback(window, cpCallback = new GLFWCursorPosCallback() {
        @Override
        public void invoke(long window, double x, double y) {
            float nx = (float) x / width * 2.0f - 1.0f;
            float ny = (float) y / height * 2.0f - 1.0f;
            rotX = ny * (float) Math.PI * 0.5f;
            rotY = nx * (float) Math.PI;
        }
    });
    glfwSetScrollCallback(window, sCallback = new GLFWScrollCallback() {
        @Override
        public void invoke(long window, double xoffset, double yoffset) {
            if (yoffset < 0)
                fov *= 1.05f;
            else
                fov *= 1f / 1.05f;
            if (fov < 10.0f)
                fov = 10.0f;
            else if (fov > 120.0f)
                fov = 120.0f;
        }
    });

    GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
    glfwSetWindowPos(window, (vidmode.width() - width) / 2, (vidmode.height() - height) / 2);
    glfwMakeContextCurrent(window);
    glfwSwapInterval(0);
    glfwShowWindow(window);
    glfwSetCursorPos(window, width / 2, height / 2);

    IntBuffer framebufferSize = BufferUtils.createIntBuffer(2);
    nglfwGetFramebufferSize(window, memAddress(framebufferSize), memAddress(framebufferSize) + 4);
    fbWidth = framebufferSize.get(0);
    fbHeight = framebufferSize.get(1);

    caps = GL.createCapabilities();
    if (!caps.GL_ARB_shader_objects)
        throw new AssertionError("This demo requires the ARB_shader_objects extension.");
    if (!caps.GL_ARB_vertex_shader)
        throw new AssertionError("This demo requires the ARB_vertex_shader extension.");
    if (!caps.GL_ARB_fragment_shader)
        throw new AssertionError("This demo requires the ARB_fragment_shader extension.");
    debugProc = GLUtil.setupDebugMessageCallback();

    /* Create all needed GL resources */
    loadMesh();
    createTexture();
    createFullScreenQuad();
    createTeapotProgram();
    createEnvironmentProgram();
}

From source file:Image.java

private void init() {
    GLFWErrorCallback.createPrint().set();
    if (!glfwInit())
        throw new IllegalStateException("Unable to initialize GLFW");

    glfwDefaultWindowHints();/*from w  w w  .  j  av  a  2 s  . c  o m*/
    glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
    glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);

    this.window = glfwCreateWindow(ww, wh, "STB Image Demo", NULL, NULL);
    if (window == NULL)
        throw new RuntimeException("Failed to create the GLFW window");

    glfwSetWindowSizeCallback(window, this::windowSizeChanged);
    glfwSetFramebufferSizeCallback(window, Image::framebufferSizeChanged);

    glfwSetKeyCallback(window, (window, key, scancode, action, mods) -> {
        ctrlDown = (mods & GLFW_MOD_CONTROL) != 0;
        if (action == GLFW_RELEASE)
            return;

        switch (key) {
        case GLFW_KEY_ESCAPE:
            glfwSetWindowShouldClose(window, true);
            break;
        case GLFW_KEY_KP_ADD:
        case GLFW_KEY_EQUAL:
            setScale(scale + 1);
            break;
        case GLFW_KEY_KP_SUBTRACT:
        case GLFW_KEY_MINUS:
            setScale(scale - 1);
            break;
        case GLFW_KEY_0:
        case GLFW_KEY_KP_0:
            if (ctrlDown)
                setScale(0);
            break;
        }
    });

    glfwSetScrollCallback(window, (window, xoffset, yoffset) -> {
        if (ctrlDown)
            setScale(scale + (int) yoffset);
    });

    // Center window
    GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());

    glfwSetWindowPos(window, (vidmode.width() - ww) / 2, (vidmode.height() - wh) / 2);

    // Create context
    glfwMakeContextCurrent(window);
    GL.createCapabilities();
    debugProc = GLUtil.setupDebugMessageCallback();

    glfwSwapInterval(1);
    glfwShowWindow(window);

    //glfwInvoke(window, this::windowSizeChanged, Image::framebufferSizeChanged);
}

From source file:SpaceGame.java

License:Open Source License

private void init() throws IOException {
    if (!glfwInit())
        throw new IllegalStateException("Unable to initialize GLFW");

    glfwDefaultWindowHints();/*w w w  . jav  a  2 s.  c  o  m*/
    glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
    glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
    glfwWindowHint(GLFW_SAMPLES, 4);

    long monitor = glfwGetPrimaryMonitor();
    GLFWVidMode vidmode = glfwGetVideoMode(monitor);
    if (!windowed) {
        width = vidmode.width();
        height = vidmode.height();
        fbWidth = width;
        fbHeight = height;
    }
    window = glfwCreateWindow(width, height, "Little Space Shooter Game", !windowed ? monitor : 0L, NULL);
    if (window == NULL) {
        throw new AssertionError("Failed to create the GLFW window");
    }
    glfwSetCursor(window, glfwCreateStandardCursor(GLFW_CROSSHAIR_CURSOR));

    glfwSetFramebufferSizeCallback(window, fbCallback = new GLFWFramebufferSizeCallback() {
        public void invoke(long window, int width, int height) {
            if (width > 0 && height > 0
                    && (SpaceGame.this.fbWidth != width || SpaceGame.this.fbHeight != height)) {
                SpaceGame.this.fbWidth = width;
                SpaceGame.this.fbHeight = height;
            }
        }
    });
    glfwSetWindowSizeCallback(window, wsCallback = new GLFWWindowSizeCallback() {
        public void invoke(long window, int width, int height) {
            if (width > 0 && height > 0 && (SpaceGame.this.width != width || SpaceGame.this.height != height)) {
                SpaceGame.this.width = width;
                SpaceGame.this.height = height;
            }
        }
    });

    System.out.println("Press W/S to move forward/backward");
    System.out.println("Press L.Ctrl/Spacebar to move down/up");
    System.out.println("Press A/D to strafe left/right");
    System.out.println("Press Q/E to roll left/right");
    System.out.println("Hold the left mouse button to shoot");
    System.out.println("Hold the right mouse button to rotate towards the mouse cursor");
    glfwSetKeyCallback(window, keyCallback = new GLFWKeyCallback() {
        public void invoke(long window, int key, int scancode, int action, int mods) {
            if (key == GLFW_KEY_UNKNOWN)
                return;
            if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE) {
                glfwSetWindowShouldClose(window, true);
            }
            if (action == GLFW_PRESS || action == GLFW_REPEAT) {
                keyDown[key] = true;
            } else {
                keyDown[key] = false;
            }
        }
    });
    glfwSetCursorPosCallback(window, cpCallback = new GLFWCursorPosCallback() {
        public void invoke(long window, double xpos, double ypos) {
            float normX = (float) ((xpos - width / 2.0) / width * 2.0);
            float normY = (float) ((ypos - height / 2.0) / height * 2.0);
            SpaceGame.this.mouseX = Math.max(-width / 2.0f, Math.min(width / 2.0f, normX));
            SpaceGame.this.mouseY = Math.max(-height / 2.0f, Math.min(height / 2.0f, normY));
        }
    });
    glfwSetMouseButtonCallback(window, mbCallback = new GLFWMouseButtonCallback() {
        public void invoke(long window, int button, int action, int mods) {
            if (button == GLFW_MOUSE_BUTTON_LEFT) {
                if (action == GLFW_PRESS)
                    leftMouseDown = true;
                else if (action == GLFW_RELEASE)
                    leftMouseDown = false;
            } else if (button == GLFW_MOUSE_BUTTON_RIGHT) {
                if (action == GLFW_PRESS)
                    rightMouseDown = true;
                else if (action == GLFW_RELEASE)
                    rightMouseDown = false;
            }
        }
    });
    glfwMakeContextCurrent(window);
    glfwSwapInterval(0);
    glfwShowWindow(window);

    IntBuffer framebufferSize = BufferUtils.createIntBuffer(2);
    nglfwGetFramebufferSize(window, memAddress(framebufferSize), memAddress(framebufferSize) + 4);
    fbWidth = framebufferSize.get(0);
    fbHeight = framebufferSize.get(1);
    caps = GL.createCapabilities();
    if (!caps.OpenGL20) {
        throw new AssertionError("This demo requires OpenGL 2.0.");
    }
    debugProc = GLUtil.setupDebugMessageCallback();

    /* Create all needed GL resources */
    createCubemapTexture();
    createFullScreenQuad();
    createCubemapProgram();
    createShipProgram();
    createParticleProgram();
    createShip();
    createAsteroid();
    createShotProgram();
    createSphere();

    glEnableClientState(GL_VERTEX_ARRAY);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE);
}

From source file:cn.org.vbn.Texture2DArrayMipmapping.java

License:Open Source License

private void init() throws IOException {
    glfwSetErrorCallback(errCallback = new GLFWErrorCallback() {
        private GLFWErrorCallback delegate = GLFWErrorCallback.createPrint(System.err);

        @Override/*from  w  ww. j av a  2  s.  co  m*/
        public void invoke(int error, long description) {
            if (error == GLFW_VERSION_UNAVAILABLE)
                System.err.println("This demo requires OpenGL 3.0 or higher.");
            delegate.invoke(error, description);
        }

        @Override
        public void release() {
            delegate.release();
            super.release();
        }
    });

    if (glfwInit() != GL_TRUE)
        throw new IllegalStateException("Unable to initialize GLFW");

    glfwDefaultWindowHints();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
    glfwWindowHint(GLFW_VISIBLE, GL_FALSE);
    glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);

    window = glfwCreateWindow(width, height, "Mipmapping with 2D array textures", NULL, NULL);
    if (window == NULL) {
        throw new AssertionError("Failed to create the GLFW window");
    }

    glfwSetFramebufferSizeCallback(window, fbCallback = new GLFWFramebufferSizeCallback() {
        @Override
        public void invoke(long window, int width, int height) {
            if (width > 0 && height > 0 && (Texture2DArrayMipmapping.this.width != width
                    || Texture2DArrayMipmapping.this.height != height)) {
                Texture2DArrayMipmapping.this.width = width;
                Texture2DArrayMipmapping.this.height = height;
            }
        }
    });

    glfwSetKeyCallback(window, keyCallback = new GLFWKeyCallback() {
        @Override
        public void invoke(long window, int key, int scancode, int action, int mods) {
            if (action != GLFW_RELEASE)
                return;

            if (key == GLFW_KEY_ESCAPE) {
                glfwSetWindowShouldClose(window, GL_TRUE);
            }
        }
    });

    GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
    glfwSetWindowPos(window, (vidmode.width() - width) / 2, (vidmode.height() - height) / 2);
    glfwMakeContextCurrent(window);
    glfwSwapInterval(0);
    glfwShowWindow(window);
    caps = GL.createCapabilities();
    debugProc = GLUtil.setupDebugMessageCallback();

    /* Create all needed GL resources */
    createTexture();
    createVao();
    //        createRasterProgram();
    initProgram();
}

From source file:com.goosejs.tester.MandleBrot.java

License:Open Source License

public MandleBrot(long platform, CLCapabilities platformCaps, GLFWWindow window, int deviceType,
        boolean debugGL, int maxIterations) {
    this.platform = platform;

    this.window = window;
    this.maxIterations = maxIterations;

    IntBuffer size = BufferUtils.createIntBuffer(2);

    nglfwGetWindowSize(window.handle, memAddress(size), memAddress(size) + 4);
    ww = size.get(0);// w w w.  j  a  va  2  s .  c om
    wh = size.get(1);

    nglfwGetFramebufferSize(window.handle, memAddress(size), memAddress(size) + 4);
    fbw = size.get(0);
    fbh = size.get(1);

    glfwMakeContextCurrent(window.handle);
    GLCapabilities glCaps = GL.createCapabilities();
    if (!glCaps.OpenGL30)
        throw new RuntimeException("OpenGL 3.0 is required to run this demo.");

    debugProc = debugGL ? GLUtil.setupDebugMessageCallback() : null;

    glfwSwapInterval(0);

    errcode_ret = BufferUtils.createIntBuffer(1);

    try {
        // Find devices with GL sharing support
        {
            long device = getDevice(platform, platformCaps, deviceType);
            if (device == NULL)
                device = getDevice(platform, platformCaps, CL_DEVICE_TYPE_CPU);

            if (device == NULL)
                throw new RuntimeException("No OpenCL devices found with OpenGL sharing support.");

            this.device = device;
            this.deviceCaps = CL.createDeviceCapabilities(device, platformCaps);
        }

        // Create the context
        PointerBuffer ctxProps = BufferUtils.createPointerBuffer(7);
        switch (Platform.get()) {
        case WINDOWS:
            ctxProps.put(CL_GL_CONTEXT_KHR).put(glfwGetWGLContext(window.handle)).put(CL_WGL_HDC_KHR)
                    .put(wglGetCurrentDC());
            break;
        case LINUX:
            ctxProps.put(CL_GL_CONTEXT_KHR).put(glfwGetGLXContext(window.handle)).put(CL_GLX_DISPLAY_KHR)
                    .put(glfwGetX11Display());
            break;
        case MACOSX:
            ctxProps.put(APPLEGLSharing.CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE)
                    .put(CGLGetShareGroup(CGLGetCurrentContext()));
        }
        ctxProps.put(CL_CONTEXT_PLATFORM).put(platform).put(NULL).flip();
        clContext = clCreateContext(ctxProps, device,
                clContextCB = CLContextCallback.create((errinfo, private_info, cb,
                        user_data) -> log(String.format("cl_context_callback\n\tInfo: %s", memUTF8(errinfo)))),
                NULL, errcode_ret);
        checkCLError(errcode_ret);

        // create command queues for every GPU, setup colormap and init kernels

        IntBuffer colorMapBuffer = BufferUtils.createIntBuffer(32 * 2);
        initColorMap(colorMapBuffer, 32, Color.BLUE, Color.GREEN, Color.RED);

        clColorMap = clCreateBuffer(clContext, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, colorMapBuffer,
                errcode_ret);
        checkCLError(errcode_ret);

        // create command queue and upload color map buffer
        clQueue = clCreateCommandQueue(clContext, device, NULL, errcode_ret);
        checkCLError(errcode_ret);

        // load program(s)
        if (deviceType == CL_DEVICE_TYPE_GPU)
            log("OpenCL Device Type: GPU (Use -forceCPU to use CPU)");
        else
            log("OpenCL Device Type: CPU");

        log("Max Iterations: " + maxIterations + " (Use -iterations <count> to change)");
        log("Display resolution: " + ww + "x" + wh + " (Use -res <width> <height> to change)");

        log("OpenGL glCaps.GL_ARB_sync = " + glCaps.GL_ARB_sync);
        log("OpenGL glCaps.GL_ARB_cl_event = " + glCaps.GL_ARB_cl_event);

        buildProgram();

        // Detect GLtoCL synchronization method
        syncGLtoCL = !glCaps.GL_ARB_cl_event; // GL3.2 or ARB_sync implied
        log(syncGLtoCL ? "GL to CL sync: Using clFinish" : "GL to CL sync: Using OpenCL events");

        // Detect CLtoGL synchronization method
        syncCLtoGL = !deviceCaps.cl_khr_gl_event;
        log(syncCLtoGL ? "CL to GL sync: Using glFinish"
                : "CL to GL sync: Using implicit sync (cl_khr_gl_event)");

        vao = glGenVertexArrays();
        glBindVertexArray(vao);

        vbo = glGenBuffers();
        glBindBuffer(GL_ARRAY_BUFFER, vbo);

        glBufferData(GL_ARRAY_BUFFER, stackPush().floats(0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f,
                1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f), GL_STATIC_DRAW);
        stackPop();

        vsh = glCreateShader(GL_VERTEX_SHADER);
        glShaderSource(vsh,
                "#version 150\n" + "\n" + "uniform mat4 projection;\n" + "\n" + "uniform vec2 size;\n" + "\n"
                        + "in vec2 posIN;\n" + "in vec2 texIN;\n" + "\n" + "out vec2 texCoord;\n" + "\n"
                        + "void main(void) {\n" + "\tgl_Position = projection * vec4(posIN * size, 0.0, 1.0);\n"
                        + "\ttexCoord = texIN;\n" + "}");
        glCompileShader(vsh);
        String log = glGetShaderInfoLog(vsh, glGetShaderi(vsh, GL_INFO_LOG_LENGTH));
        if (!log.isEmpty())
            log(String.format("VERTEX SHADER LOG: %s", log));

        fsh = glCreateShader(GL_FRAGMENT_SHADER);
        glShaderSource(fsh,
                "#version 150\n" + "\n" + "uniform isampler2D mandelbrot;\n" + "\n" + "in vec2 texCoord;\n"
                        + "\n" + "out vec4 fragColor;\n" + "\n" + "void main(void) {\n"
                        + "\tfragColor = texture(mandelbrot, texCoord) / 255.0;\n" + "}");
        glCompileShader(fsh);
        log = glGetShaderInfoLog(fsh, glGetShaderi(fsh, GL_INFO_LOG_LENGTH));
        if (!log.isEmpty())
            log(String.format("FRAGMENT SHADER LOG: %s", log));

        glProgram = glCreateProgram();
        glAttachShader(glProgram, vsh);
        glAttachShader(glProgram, fsh);
        glLinkProgram(glProgram);
        log = glGetProgramInfoLog(glProgram, glGetProgrami(glProgram, GL_INFO_LOG_LENGTH));
        if (!log.isEmpty())
            log(String.format("PROGRAM LOG: %s", log));

        int posIN = glGetAttribLocation(glProgram, "posIN");
        int texIN = glGetAttribLocation(glProgram, "texIN");

        glVertexAttribPointer(posIN, 2, GL_FLOAT, false, 4 * 4, 0);
        glVertexAttribPointer(texIN, 2, GL_FLOAT, false, 4 * 4, 2 * 4);

        glEnableVertexAttribArray(posIN);
        glEnableVertexAttribArray(texIN);

        projectionUniform = glGetUniformLocation(glProgram, "projection");
        sizeUniform = glGetUniformLocation(glProgram, "size");

        glUseProgram(glProgram);

        glUniform1i(glGetUniformLocation(glProgram, "mandelbrot"), 0);
    } catch (Exception e) {
        // TODO: cleanup
        throw new RuntimeException(e);
    }

    glDisable(GL_DEPTH_TEST);
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

    initGLObjects();
    glFinish();

    setKernelConstants();

    glfwSetWindowSizeCallback(window.handle, (windowHandle, width, height) -> {
        if (width == 0 || height == 0)
            return;

        events.add(() -> {
            this.ww = width;
            this.wh = height;

            shouldInitBuffers = true;
        });
    });

    glfwSetFramebufferSizeCallback(window.handle, (windowHandle, width, height) -> {
        if (width == 0 || height == 0)
            return;

        events.add(() -> {
            this.fbw = width;
            this.fbh = height;

            shouldInitBuffers = true;
        });
    });

    glfwSetKeyCallback(window.handle, (windowHandle, key, scancode, action, mods) -> {
        switch (key) {
        case GLFW_KEY_LEFT_CONTROL:
        case GLFW_KEY_RIGHT_CONTROL:
            ctrlDown = action == GLFW_PRESS;
            return;
        }

        if (action != GLFW_PRESS)
            return;

        switch (key) {
        case GLFW_KEY_ESCAPE:
            glfwSetWindowShouldClose(windowHandle, true);
            break;
        case GLFW_KEY_D:
            events.offer(() -> {
                doublePrecision = !doublePrecision;
                log("DOUBLE PRECISION IS NOW: " + (doublePrecision ? "ON" : "OFF"));
                rebuild = true;
            });
            break;
        case GLFW_KEY_HOME:
            events.offer(() -> {
                offsetX = -0.5;
                offsetY = 0.0;
                zoom = 1.0;
            });
            break;
        }
    });

    glfwSetMouseButtonCallback(window.handle, (windowHandle, button, action, mods) -> {
        if (button != GLFW_MOUSE_BUTTON_LEFT)
            return;

        dragging = action == GLFW_PRESS;

        if (dragging) {
            dragging = true;

            dragX = mouseX;
            dragY = mouseY;

            dragOffsetX = offsetX;
            dragOffsetY = offsetY;
        }
    });

    glfwSetCursorPosCallback(window.handle, (windowHandle, xpos, ypos) -> {
        mouseX = xpos;
        mouseY = wh - ypos;

        if (dragging) {
            offsetX = dragOffsetX + transformX(dragX - mouseX);
            offsetY = dragOffsetY + transformY(dragY - mouseY);
        }
    });

    glfwSetScrollCallback(window.handle, (windowHandle, xoffset, yoffset) -> {
        if (yoffset == 0)
            return;

        double scrollX = mouseX - ww * 0.5;
        double scrollY = mouseY - wh * 0.5;

        double zoomX = transformX(scrollX);
        double zoomY = transformY(scrollY);

        zoom *= (1.0 - yoffset * (ctrlDown ? 0.25 : 0.05));

        offsetX += zoomX - transformX(scrollX);
        offsetY += zoomY - transformY(scrollY);
    });
}

From source file:com.swinggl.elements.GLFrame.java

License:Open Source License

/**
 * This method starts the both the render and update loops. The thread that this is called on will become the render loop and occupy that thread entirely.
 * All glfwWindowHint's must be called before this is called while all other window attributes can be altered while the loop is running including changing
 * the FPS and UPS./*  www  .j a v a 2  s . co  m*/
 */
public void run() {
    if (fullscreen) {
        window = glfwCreateWindow(windowWidth, windowHeight, title, glfwGetPrimaryMonitor(),
                secondWindowHandle);
        GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
        if (!(windowWidth == vidmode.width() && windowHeight == vidmode.height())) {
            Debug.println("GLFWVidMode [" + windowWidth + ", " + windowHeight
                    + "] not available, switching to GLFWVidMode [" + vidmode.width() + ", " + vidmode.height()
                    + "]", Debug.ANSI_YELLOW);
            windowWidth = vidmode.width();
            windowHeight = vidmode.height();
        }
    } else
        window = glfwCreateWindow(windowWidth, windowHeight, title, NULL, secondWindowHandle);
    if (window == NULL)
        throw new RuntimeException("Failed to create the GLFW window");

    if (windowPosition == WINDOW_POSITION_CUSTOM && !fullscreen)
        glfwSetWindowPos(window, windowX, windowY);
    else if (!fullscreen)
        updateWindowPosition();

    glfwSetKeyCallback(window, keyCallback);
    glfwSetCursorPosCallback(window, cursorPosCallback);
    glfwSetCursorEnterCallback(window, cursorEnterCallback);
    glfwSetMouseButtonCallback(window, mouseButtonCallback);
    glfwSetScrollCallback(window, scrollCallback);
    glfwSetWindowPosCallback(window, windowPosCallback);
    glfwSetWindowSizeCallback(window, windowSizeCallback);
    glfwSetWindowCloseCallback(window, windowCloseCallback);
    glfwSetWindowRefreshCallback(window, windowRefreshCallback);
    glfwSetWindowFocusCallback(window, windowFocusCallback);
    glfwSetWindowIconifyCallback(window, windowIconifyCallback);
    glfwSetDropCallback(window, dropCallback);

    if (mouseDisabled)
        glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    else if (mouseHidden)
        glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
    else
        glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);

    glfwMakeContextCurrent(window);
    glfwSwapInterval(1);

    GL.createCapabilities();
    GLUtil.setupDebugMessageCallback();
    GL11.glMatrixMode(GL11.GL_PROJECTION);
    GL11.glLoadIdentity();
    GL11.glOrtho(0, windowWidth, windowHeight, 0, 1, -1);
    GL11.glMatrixMode(GL11.GL_MODELVIEW);
    GL11.glEnable(GL11.GL_TEXTURE_2D);
    GL11.glClearColor(backgroundColor.getRed() / 255f, backgroundColor.getGreen() / 255f,
            backgroundColor.getBlue() / 255f, backgroundColor.getAlpha() / 255f);

    Debug.initialize();

    if (visible)
        glfwShowWindow(window);

    new Thread(new Update(), "SwingGL | update").start();
    long now = System.nanoTime();
    long lastTime = now;
    double deltaR = 0.0;
    long lastRender = now;

    running = true;

    while (running) {
        if (glfwWindowShouldClose(window) == GL_TRUE)
            running = false;

        now = System.nanoTime();
        deltaR += (now - lastTime) / renderNS;
        lastTime = now;

        if (deltaR >= 1.0) {
            renderDelta = (now - lastRender) / 1000000000.0f;
            render(renderDelta);
            lastRender = now;
            deltaR--;
        }
    }

    if (currentGameState != null)
        currentGameState.dispose();

    try {
        glfwDestroyWindow(window);
        keyCallback.release();
        cursorPosCallback.release();
        mouseButtonCallback.release();
        scrollCallback.release();
    } finally {
        glfwTerminate();
        errorCallback.release();
    }
}

From source file:com.valkrix.BasicApplication.java

License:Open Source License

@Override
protected void init() {
    assetLoader = new AssetLoader(Paths.get("assets"));
    callback = GLUtil.setupDebugMessageCallback();

    glClearColor(0, 0, 0, 1);//from w  w w.ja  va 2 s . c  o m

    modelLoader = new ModelLoader();
    vao = modelLoader.load(vertices, indices);

    simpleShader = new ShaderProgram(assetLoader);
    simpleShader.addShader(GL_VERTEX_SHADER, Paths.get("shaders", "simpleVertex.glsl"));
    simpleShader.addShader(GL_FRAGMENT_SHADER, Paths.get("shaders", "simpleFragment.glsl"));
    simpleShader.link();
}

From source file:engine.logic.Multiplayer.java

License:Open Source License

private void renderLoop() {
    glfwMakeContextCurrent(window);/*  ww  w.  j  a  va2s  . c o m*/

    GL.createCapabilities();

    glfwSwapInterval(0); //disable vsync
    debugProc = GLUtil.setupDebugMessageCallback();

    scene = new Scene();
    inputHandler = new InputHandler(window, scene);

    float deltaTime;
    long lastNanoTime = 0;

    long lastFpsNanoTime = 0;
    int fps = 0;
    long tempTime;

    while (!destroyed) {
        long time = System.nanoTime();
        deltaTime = (float) (time - lastNanoTime) * 1e-9f;
        lastNanoTime = time;

        inputHandler.updateInput(deltaTime);
        scene.update(deltaTime);
        scene.render(deltaTime);
        limitFps(30);

        fps++;
        tempTime = time - lastFpsNanoTime;
        if (tempTime > 1000000000) {
            glfwSetWindowTitle(window,
                    "FPS: " + fps + " Frametime: " + (float) ((tempTime / fps / 10000)) / 100 + "ms");
            lastFpsNanoTime = time;
            fps = 0;
        }

        synchronized (lock) {
            if (!destroyed) {
                glfwSwapBuffers(window);
            }
        }
    }
}

From source file:engine.logic.Singleplayer.java

License:Open Source License

private void renderLoop() {
    glfwMakeContextCurrent(window);/*w w  w .  j ava  2 s  .  c  om*/
    GL.createCapabilities();

    glfwSwapInterval(0); //disable vsync
    debugProc = GLUtil.setupDebugMessageCallback();

    scene = new Scene();
    inputHandler = new InputHandler(window, scene);

    float deltaTime;
    long lastNanoTime = 0;

    long lastFpsNanoTime = 0;
    int fps = 0;
    long tempTime;

    while (!glfwWindowShouldClose(window)) {
        long time = System.nanoTime();
        deltaTime = (float) (time - lastNanoTime) * 1e-9f;
        lastNanoTime = time;

        inputHandler.updateInput(deltaTime);
        scene.update(deltaTime);
        scene.render(deltaTime);
        limitFps(70);

        fps++;
        tempTime = time - lastFpsNanoTime;
        if (tempTime > 1000000000) {
            glfwSetWindowTitle(window,
                    "FPS: " + fps + " Frametime: " + (float) ((tempTime / fps / 10000)) / 100 + "ms");
            lastFpsNanoTime = time;
            fps = 0;
        }

        glfwSwapBuffers(window);
        glfwPollEvents();
    }
}