Example usage for org.lwjgl.opengl GL createCapabilities

List of usage examples for org.lwjgl.opengl GL createCapabilities

Introduction

In this page you can find the example usage for org.lwjgl.opengl GL createCapabilities.

Prototype

public static GLCapabilities createCapabilities() 

Source Link

Document

Creates a new GLCapabilities instance for the OpenGL context that is current in the current thread.

Usage

From source file:org.lwjgl.demo.util.nfd.HelloNFD.java

License:Open Source License

public static void main(String[] args) {
    int mod;//from  w  w w.  ja  va2  s.c  o m
    String modDescr;
    if (Platform.get() == Platform.MACOSX) {
        mod = GLFW_MOD_SUPER;
        modDescr = "Cmd";
    } else {
        mod = GLFW_MOD_CONTROL;
        modDescr = "Ctrl";
    }

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

    long window = glfwCreateWindow(300, 300, "Hello NativeFileDialog!", NULL, NULL);
    if (window == NULL) {
        throw new RuntimeException("Failed to create the GLFW window");
    }

    glfwSetKeyCallback(window, (windowHnd, key, scancode, action, mods) -> {
        if (action == GLFW_RELEASE) {
            return;
        }

        switch (key) {
        case GLFW_KEY_ESCAPE:
            glfwSetWindowShouldClose(windowHnd, true);
            break;
        case GLFW_KEY_O:
            if ((mods & mod) != 0) {
                if ((mods & GLFW_MOD_SHIFT) != 0) {
                    openMulti();
                } else if ((mods & GLFW_MOD_ALT) != 0) {
                    openFolder();
                } else {
                    openSingle();
                }
            }
            break;
        case GLFW_KEY_S:
            if ((mods & mod) != 0) {
                save();
            }
            break;
        }
    });

    // Center window
    GLFWVidMode vidmode = Objects.requireNonNull(glfwGetVideoMode(glfwGetPrimaryMonitor()));
    glfwSetWindowPos(window, (vidmode.width() - 300) / 2, (vidmode.height() - 300) / 2);

    glfwMakeContextCurrent(window);
    GL.createCapabilities();

    glfwSwapInterval(1);

    System.out.println("Press " + modDescr + "+O to launch the single file open dialog.");
    System.out.println("Press " + modDescr + "+Shift+O to launch the multi file open dialog.");
    System.out.println("Press " + modDescr + "+Alt+O to launch the folder select dialog.");
    System.out.println("Press " + modDescr + "+S to launch the file save dialog.");
    while (!glfwWindowShouldClose(window)) {
        glfwPollEvents();

        glClear(GL_COLOR_BUFFER_BIT);
        glfwSwapBuffers(window);
    }

    glfwFreeCallbacks(window);
    glfwDestroyWindow(window);
    glfwTerminate();

    Objects.requireNonNull(glfwSetErrorCallback(null)).free();
}

From source file:org.lwjgl.demo.util.par.ParShapesDemo.java

License:Open Source License

private void init() {
    GLFWErrorCallback.createPrint().set();
    if (!glfwInit()) {
        throw new IllegalStateException("Unable to initialize GLFW");
    }//  ww  w.  j  a  v a  2 s.  com

    glfwDefaultWindowHints();
    glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
    glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
    glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);

    window = glfwCreateWindow(width, height, "par_shapes demo", NULL, NULL);
    if (window == NULL) {
        throw new RuntimeException("Failed to create the GLFW window");
    }

    glfwMakeContextCurrent(window);
    GL.createCapabilities();
    debugCB = GLUtil.setupDebugMessageCallback();
    if (debugCB != null && GL.getCapabilities().OpenGL43) {
        glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_OTHER, GL_DEBUG_SEVERITY_NOTIFICATION,
                (IntBuffer) null, false);
    }

    glfwSetKeyCallback(window, (window, key, scancode, action, mods) -> {
        if (action != GLFW_RELEASE) {
            return;
        }

        int scale;
        if ((mods & GLFW_MOD_CONTROL) != 0) {
            scale = 100;
        } else if ((mods & GLFW_MOD_SHIFT) != 0) {
            scale = 10;
        } else {
            scale = 1;
        }
        switch (key) {
        case GLFW_KEY_DOWN:
            if (slices > 3) {
                slices -= scale;
                if (slices < 3) {
                    slices = 3;
                }
                updateMesh();
            }
            break;
        case GLFW_KEY_UP:
            slices += scale;
            updateMesh();
            break;
        case GLFW_KEY_LEFT:
            if (stacks > 1) {
                stacks -= scale;
                if (stacks < 1) {
                    stacks = 1;
                }
                updateMesh();
            }
            break;
        case GLFW_KEY_RIGHT:
            stacks += scale;
            updateMesh();
            break;
        case GLFW_KEY_PAGE_DOWN:
            seed--;
            updateMesh();
            break;
        case GLFW_KEY_PAGE_UP:
            seed++;
            updateMesh();
            break;
        case GLFW_KEY_KP_SUBTRACT:
            if (subdivisions > 1) {
                subdivisions--;
                updateMesh();
            }
            break;
        case GLFW_KEY_KP_ADD:
            subdivisions++;
            updateMesh();
            break;
        case GLFW_KEY_1:
        case GLFW_KEY_2:
        case GLFW_KEY_3:
        case GLFW_KEY_4:
        case GLFW_KEY_5:
        case GLFW_KEY_6:
        case GLFW_KEY_7:
        case GLFW_KEY_8:
            updateMesh(key);
            break;
        case GLFW_KEY_E:
            if (mesh != null) {
                exportMesh();
            }
            break;
        case GLFW_KEY_W:
            wireframe = !wireframe;
            updateHUD();
            break;
        case GLFW_KEY_ESCAPE:
            glfwSetWindowShouldClose(window, true);
            break;
        }
    });

    glfwSetFramebufferSizeCallback(window, (window, width, height) -> {
        this.width = width;
        this.height = height;
        updateViewport(width, height);
    });

    // center window
    GLFWVidMode vidmode = Objects.requireNonNull(glfwGetVideoMode(glfwGetPrimaryMonitor()));
    glfwSetWindowPos(window, (vidmode.width() - width) / 2, (vidmode.height() - height) / 2);

    glfwShowWindow(window);

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    glDisable(GL_CULL_FACE);

    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);

    updateViewport(width, height);

    glLoadIdentity();
    glTranslatef(0.0f, 0.0f, -3.0f);
    glRotatef(45.0f, 1.0f, 0.0f, 0.0f);

    vbo = glGenBuffers();
    ibo = glGenBuffers();
    hudVBO = glGenBuffers();

    updateMesh(GLFW_KEY_1);

    int vshader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vshader,
            "#version 110\n" + "\n" + "attribute vec3 position;\n" + "attribute vec3 normal;\n" + "\n"
                    + "varying vec3 viewNormal;\n" + "\n" + "void main(void) {\n"
                    + "  viewNormal = gl_NormalMatrix * normal;\n"
                    + "  gl_Position = gl_ModelViewProjectionMatrix * vec4(position, 1.0);\n" + "}\n");
    glCompileShader(vshader);
    if (glGetShaderi(vshader, GL_COMPILE_STATUS) == GL_FALSE) {
        throw new IllegalStateException(glGetShaderInfoLog(vshader));
    }

    int fshader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fshader, "#version 110\n" + "\n" + "varying vec3 viewNormal;\n" + "\n"
            + "void main(void) {\n" + "  gl_FragColor = vec4(normalize(viewNormal), 1.0);\n" + "}\n");
    glCompileShader(fshader);
    if (glGetShaderi(fshader, GL_COMPILE_STATUS) == GL_FALSE) {
        throw new IllegalStateException(glGetShaderInfoLog(fshader));
    }

    program = glCreateProgram();
    glAttachShader(program, vshader);
    glAttachShader(program, fshader);
    glBindAttribLocation(program, 0, "position");
    glBindAttribLocation(program, 1, "normal");
    glLinkProgram(program);
    if (glGetProgrami(program, GL_LINK_STATUS) == GL_FALSE) {
        throw new IllegalStateException(glGetProgramInfoLog(program));
    }

    glDeleteShader(fshader);
    glDeleteShader(vshader);
}

From source file:org.lwjgl.demo.util.tinyfd.HelloTinyFD.java

License:Open Source License

public static void main(String[] args) {
    GLFWErrorCallback.createPrint().set();
    if (!glfwInit()) {
        throw new IllegalStateException("Unable to initialize GLFW");
    }/*from   w  w  w. j  av a  2  s .co m*/

    long window = glfwCreateWindow(300, 300, "Hello tiny file dialogs!", NULL, NULL);
    if (window == NULL) {
        throw new RuntimeException("Failed to create the GLFW window");
    }

    glfwSetKeyCallback(window, (windowHnd, key, scancode, action, mods) -> {
        if (action == GLFW_RELEASE) {
            return;
        }

        switch (key) {
        case GLFW_KEY_ESCAPE:
            glfwSetWindowShouldClose(windowHnd, true);
            break;
        case GLFW_KEY_B:
            tinyfd_beep();
            break;
        case GLFW_KEY_N:
            System.out.println("\nOpening notification popup...");
            System.out.println(tinyfd_notifyPopup("Please read...", "...this message.", "info"));
            break;
        case GLFW_KEY_1:
            System.out.println("\nOpening message dialog...");
            System.out.println(
                    tinyfd_messageBox("Please read...", "...this message.", "okcancel", "info", true) ? "OK"
                            : "Cancel");
            break;
        case GLFW_KEY_2:
            System.out.println("\nOpening input box dialog...");
            System.out.println(tinyfd_inputBox("Input Value", "How old are you?", "30"));
            break;
        case GLFW_KEY_3:
            System.out.println("\nOpening file open dialog...");
            System.out.println(tinyfd_openFileDialog("Open File(s)", "", null, null, true));
            break;
        case GLFW_KEY_4:
            try (MemoryStack stack = stackPush()) {
                PointerBuffer aFilterPatterns = stack.mallocPointer(2);

                aFilterPatterns.put(stack.UTF8("*.jpg"));
                aFilterPatterns.put(stack.UTF8("*.png"));

                aFilterPatterns.flip();

                System.out.println("\nOpening file save dialog...");
                System.out.println(
                        tinyfd_saveFileDialog("Save Image", "", aFilterPatterns, "Image files (*.jpg, *.png)"));
            }
            break;
        case GLFW_KEY_5:
            System.out.println("\nOpening folder select dialog...");
            System.out.println(tinyfd_selectFolderDialog("Select Folder", ""));
            break;
        case GLFW_KEY_6:
            System.out.println("\nOpening color chooser dialog...");
            try (MemoryStack stack = stackPush()) {
                ByteBuffer color = stack.malloc(3);
                String hex = tinyfd_colorChooser("Choose Color", "#FF00FF", null, color);
                System.out.println(hex);
                if (hex != null) {
                    System.out.println("\tR: " + (color.get(0) & 0xFF));
                    System.out.println("\tG: " + (color.get(1) & 0xFF));
                    System.out.println("\tB: " + (color.get(2) & 0xFF));
                }
            }
            break;
        }
    });

    // Center window
    GLFWVidMode vidmode = Objects.requireNonNull(glfwGetVideoMode(glfwGetPrimaryMonitor()));
    glfwSetWindowPos(window, (vidmode.width() - 300) / 2, (vidmode.height() - 300) / 2);

    glfwMakeContextCurrent(window);
    GL.createCapabilities();

    glfwSwapInterval(1);

    tinyfd_messageBox("tinyfd_query", "", "ok", "info", true);
    System.out.println("tiny file dialogs " + tinyfd_version + " (" + tinyfd_response() + ")");
    System.out.println();
    System.out.println(tinyfd_needs);
    System.out.println();
    System.out.println("Press 1 to launch a message dialog.");
    System.out.println("Press 2 to launch an input box fialog.");
    System.out.println("Press 3 to launch a file open dialog.");
    System.out.println("Press 4 to launch a file save dialog.");
    System.out.println("Press 5 to launch a folder select dialog.");
    System.out.println("Press 6 to launch a color chooser dialog.");
    while (!glfwWindowShouldClose(window)) {
        glfwPollEvents();

        glClear(GL_COLOR_BUFFER_BIT);
        glfwSwapBuffers(window);
    }

    glfwFreeCallbacks(window);
    glfwDestroyWindow(window);
    glfwTerminate();

    Objects.requireNonNull(glfwSetErrorCallback(null)).free();
}

From source file:org.lwjgl.demo.util.tootle.HelloTootle.java

License:Open Source License

private HelloTootle() {
    GLFWErrorCallback.createPrint().set();
    if (!glfwInit()) {
        throw new IllegalStateException("Unable to initialize GLFW");
    }//from   ww  w.  ja v a2 s.  c o  m

    glfwDefaultWindowHints();
    glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
    glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
    if (Platform.get() == Platform.MACOSX) {
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
        glfwWindowHint(GLFW_COCOA_RETINA_FRAMEBUFFER, GLFW_FALSE);
    }
    glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);

    window = glfwCreateWindow(width, height, "AMD Tootle demo", NULL, NULL);
    if (window == NULL) {
        throw new RuntimeException("Failed to create the GLFW window");
    }

    glfwMakeContextCurrent(window);
    GLCapabilities caps = GL.createCapabilities();
    if (!caps.OpenGL33) {
        throw new IllegalStateException("OpenGL 3.3 is required to run this demo.");
    }
    debugCB = GLUtil.setupDebugMessageCallback();
    if (debugCB != null) {
        if (caps.OpenGL43) {
            glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_OTHER, GL_DEBUG_SEVERITY_NOTIFICATION,
                    (IntBuffer) null, false);
        } else if (caps.GL_KHR_debug) {
            KHRDebug.glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_OTHER,
                    GL_DEBUG_SEVERITY_NOTIFICATION, (IntBuffer) null, false);
        }
    }

    glfwSwapInterval(0);

    glfwSetKeyCallback(window, (window, key, scancode, action, mods) -> {
        if (action != GLFW_RELEASE) {
            return;
        }

        int scale;
        if ((mods & GLFW_MOD_CONTROL) != 0) {
            scale = 100;
        } else if ((mods & GLFW_MOD_SHIFT) != 0) {
            scale = 10;
        } else {
            scale = 1;
        }
        switch (key) {
        case GLFW_KEY_DOWN:
            if (slices > 3) {
                slices -= scale;
                if (slices < 3) {
                    slices = 3;
                }
                updateMesh();
            }
            break;
        case GLFW_KEY_UP:
            slices += scale;
            updateMesh();
            break;
        case GLFW_KEY_LEFT:
            if (stacks > 1) {
                stacks -= scale;
                if (stacks < 1) {
                    stacks = 1;
                }
                updateMesh();
            }
            break;
        case GLFW_KEY_RIGHT:
            stacks += scale;
            updateMesh();
            break;
        case GLFW_KEY_PAGE_DOWN:
            if (meshKey != GLFW_KEY_8) {
                seed--;
                updateMesh();
            } else {
                if (subdivisions > 1) {
                    subdivisions--;
                    updateMesh();
                }
            }
            break;
        case GLFW_KEY_PAGE_UP:
            if (meshKey != GLFW_KEY_8) {
                seed++;
                updateMesh();
            } else {
                subdivisions++;
                updateMesh();
            }
            break;
        case GLFW_KEY_KP_SUBTRACT:
            if ((mods & GLFW_MOD_CONTROL) != 0) {
                if (1 < cubeSize) {
                    setCubeSize(cubeSize - 1);
                }
            } else if (16 < vcacheSize) {
                vcacheSize -= 8;
                setMesh(mesh);
            }
            break;
        case GLFW_KEY_KP_ADD:
            if ((mods & GLFW_MOD_CONTROL) != 0) {
                setCubeSize(cubeSize + 1);
            } else if (vcacheSize < 32) {
                vcacheSize += 8;
                setMesh(mesh);
            }
            break;
        case GLFW_KEY_1:
        case GLFW_KEY_2:
        case GLFW_KEY_3:
        case GLFW_KEY_4:
        case GLFW_KEY_5:
        case GLFW_KEY_6:
        case GLFW_KEY_7:
        case GLFW_KEY_8:
            updateMesh(key);
            break;
        case GLFW_KEY_F1:
        case GLFW_KEY_F2:
        case GLFW_KEY_F3:
            vcacheMethod = key - GLFW_KEY_F1;
            setMesh(mesh);
            break;
        case GLFW_KEY_F4:
            optimizeVertexMemory = !optimizeVertexMemory;
            setMesh(mesh);
            break;
        case GLFW_KEY_F:
            fragmentShader = !fragmentShader;
            updateHUD();
            break;
        case GLFW_KEY_O:
            if ((mods & GLFW_MOD_CONTROL) != 0) {
                meshKey = -1;
                importMesh();
            } else {
                optimized = !optimized;
                if (mesh != null) {
                    updateMeshGPU();
                }
                updateHUD();
            }
            break;
        case GLFW_KEY_W:
            wireframe = !wireframe;
            updateHUD();
            break;
        case GLFW_KEY_ESCAPE:
            glfwSetWindowShouldClose(window, true);
            break;
        case GLFW_KEY_SPACE:
            if (mesh != null) {
                shuffleMesh();
            }
            break;
        }
    });

    glfwSetFramebufferSizeCallback(window, (window, width, height) -> {
        this.width = width;
        this.height = height;
        updateViewport(width, height);
    });

    // center window
    GLFWVidMode vidmode = Objects.requireNonNull(glfwGetVideoMode(glfwGetPrimaryMonitor()));
    glfwSetWindowPos(window, (vidmode.width() - width) / 2, (vidmode.height() - height) / 2);

    glfwShowWindow(window);

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    glEnable(GL_CULL_FACE);

    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);

    updateViewport(width, height);

    vao = glGenVertexArrays();
    glBindVertexArray(vao); // bind and ignore

    vboMesh = glGenBuffers();
    iboMesh = glGenBuffers();
    vboHUD = glGenBuffers();
    vboPerf = glGenBuffers();

    glBindBuffer(GL_ARRAY_BUFFER, vboPerf);
    glBufferData(GL_ARRAY_BUFFER, 4 * 1024, GL_DYNAMIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    updateMesh(GLFW_KEY_1);
    setCubeSize(8);

    programMesh = buildShaderProgram("#version 330\n" + "\n" + "uniform mat4 mMVP;\n"
            + "uniform mat3 mNORMAL;\n" + "uniform int cubeSize;\n" + "\n"
            + "layout(location = 0) in vec3 iPosition;\n" + "layout(location = 1) in vec3 iNormal;\n" + "\n"
            + "out vec3 vNormal;\n" + "\n" + "void main(void) {\n"
            + "  int x = gl_InstanceID / (cubeSize * cubeSize);\n"
            + "  int y = (gl_InstanceID / cubeSize) % cubeSize;\n" + "  int z = gl_InstanceID % cubeSize;\n"
            + "  float offset = -(cubeSize / 2);\n" + "  if (cubeSize + offset * 2 == 0) {\n"
            + "    offset += 0.5;" + "  }\n"
            + "  gl_Position = mMVP * vec4(iPosition + vec3(offset + float(x), offset + float(y), offset + float(z)), 1.0);\n"
            + "  vNormal = mNORMAL * iNormal;\n" + "}\n",
            "#version 330\n" + "\n" + "in vec3 vNormal;\n" + "\n" + "layout(location = 0) out vec4 oColor;\n"
                    + "\n" + "void main(void) {\n" + "  oColor = vec4(normalize(vNormal), 1.0);\n" + "}\n");
    uniformModelViewProjectionMatrix = glGetUniformLocation(programMesh, "mMVP");
    uniformNormalMatrix = glGetUniformLocation(programMesh, "mNORMAL");
    uniformCubeSize = glGetUniformLocation(programMesh, "cubeSize");

    programHUD = buildShaderProgram(
            "#version 330\n" + "\n" + "uniform mat4 mMVP;\n" + "\n"
                    + "layout(location = 0) in vec2 iPosition;\n" + "layout(location = 1) in vec4 iColor;\n"
                    + "\n" + "out vec4 vColor;\n" + "\n" + "void main(void) {\n"
                    + "  gl_Position = mMVP * vec4(iPosition, 0.0, 1.0);\n" + "  vColor = iColor;\n" + "}\n",
            "#version 330\n" + "\n" + "in vec4 vColor;\n" + "\n" + "layout(location = 0) out vec4 oColor;\n"
                    + "\n" + "void main(void) {\n" + "  oColor = vColor;\n" + "}\n");
    uniformModelViewProjectionMatrixHUD = glGetUniformLocation(programHUD, "mMVP");

    gpuGraph = new PerfGraph();
    gpuTimer = new GPUTimer();

    propertyStore = aiCreatePropertyStore();
    if (propertyStore == null) {
        throw new OutOfMemoryError();
    }
    aiSetImportPropertyInteger(propertyStore, AI_CONFIG_PP_PTV_NORMALIZE, 1);
}

From source file:org.lwjgl.demo.util.yoga.HolyGrail.java

License:Open Source License

private HolyGrail() {
    // ----------------------
    //          GLFW
    // ----------------------
    GLFWErrorCallback.createPrint().set();
    if (!glfwInit()) {
        throw new IllegalStateException("Unable to initialize glfw");
    }/*from   w w w. j a v  a  2 s  .c o  m*/

    glfwDefaultWindowHints();
    glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
    glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
    glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);
    if (Platform.get() == Platform.MACOSX) {
        glfwWindowHint(GLFW_COCOA_RETINA_FRAMEBUFFER, GLFW_FALSE);
    }

    long window = glfwCreateWindow(width, height, "Holy Grail layout with Yoga", NULL, NULL);
    if (window == NULL) {
        throw new RuntimeException("Failed to create the GLFW window");
    }

    // Center window
    GLFWVidMode vidmode = Objects.requireNonNull(glfwGetVideoMode(glfwGetPrimaryMonitor()));
    glfwSetWindowPos(window, (vidmode.width() - width) / 2, (vidmode.height() - height) / 2);

    glfwSetKeyCallback(window, this::keyTriggered);

    glfwSetWindowSizeCallback(window, this::windowSizeChanged);

    glfwSetWindowRefreshCallback(window, windowHnd -> {
        renderLoop();
        glfwSwapBuffers(windowHnd);
    });

    // ----------------------
    //          OpenGL
    // ----------------------

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

    glfwSwapInterval(1);

    charBuffer = BufferUtils.createByteBuffer(256 * 270);

    glEnableClientState(GL_VERTEX_ARRAY);
    glVertexPointer(2, GL_FLOAT, 16, charBuffer);

    // ----------------------
    //          Yoga
    // ----------------------

    root = YGNodeNew();
    YGNodeStyleSetFlexDirection(root, YGFlexDirectionColumn);

    header = YGNodeNew();
    container = YGNodeNew();
    footer = YGNodeNew();

    YGNodeStyleSetHeight(header, 100.0f);
    YGNodeStyleSetFlex(container, 1.0f);
    YGNodeStyleSetHeight(footer, 40.0f);

    YGNodeInsertChild(root, header, 0);
    YGNodeInsertChild(root, container, 1);
    YGNodeInsertChild(root, footer, 2);

    navbar = YGNodeNew();
    article = YGNodeNew();
    sidebar = YGNodeNew();

    YGNodeStyleSetFlex(navbar, 1.0f);
    YGNodeStyleSetFlex(article, 3.0f);
    YGNodeStyleSetFlex(sidebar, 1.0f);

    YGNodeInsertChild(container, navbar, 0);
    YGNodeInsertChild(container, article, 1);
    YGNodeInsertChild(container, sidebar, 2);

    // Show window
    windowSizeChanged(window, width, height);
    glfwShowWindow(window);
    this.window = window;
}

From source file:raytracer.Renderer.java

License:Open Source License

public Renderer(CLPlatform platform, GLFWWindow window, int deviceType, boolean debugGL) {
    this.platform = platform;

    this.window = window;

    IntBuffer size = BufferUtils.createIntBuffer(2);

    nglfwGetWindowSize(window.handle, memAddress(size), memAddress(size) + 4);
    ww = size.get(0);//w ww .  jav  a 2 s  . co  m
    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
        Filter<CLDevice> glSharingFilter = new Filter<CLDevice>() {
            @Override
            public boolean accept(CLDevice device) {
                CLCapabilities caps = device.getCapabilities();
                return caps.cl_khr_gl_sharing || caps.cl_APPLE_gl_sharing;
            }
        };
        List<CLDevice> devices = platform.getDevices(deviceType, glSharingFilter);
        if (devices == null) {
            devices = platform.getDevices(CL_DEVICE_TYPE_CPU, glSharingFilter);
            if (devices == null)
                throw new RuntimeException("No OpenCL devices found with KHR_gl_sharing support.");
        }
        this.device = devices.get(0);

        // 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.address(), clContextCB = new CLContextCallback() {
            @Override
            public void invoke(long errinfo, long private_info, long cb, long user_data) {
                System.err.println("[LWJGL] cl_context_callback");
                System.err.println("\tInfo: " + memDecodeUTF8(errinfo));
            }
        }, NULL, errcode_ret);
        checkCLError(errcode_ret);

        // create command queues for every GPU and init kernels

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

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

        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 = !device.getCapabilities().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);

        FloatBuffer quad = BufferUtils.createFloatBuffer(4 * 4).put(new float[] { 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 });
        quad.flip();
        glBufferData(GL_ARRAY_BUFFER, quad, GL_STATIC_DRAW);

        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())
            System.err.println("VERTEX SHADER LOG: " + log);

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

        glProgram = glCreateProgram();
        glAttachShader(glProgram, vsh);
        glAttachShader(glProgram, fsh);
        glLinkProgram(glProgram);
        log = glGetProgramInfoLog(glProgram, glGetProgrami(glProgram, GL_INFO_LOG_LENGTH));
        if (!log.isEmpty())
            System.err.println("PROGRAM LOG: " + 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, "tex"), 0);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

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

    initGLObjects();
    glFinish();

    setKernelConstants();

    glfwSetWindowSizeCallback(window.handle, window.windowsizefun = new GLFWWindowSizeCallback() {
        @Override
        public void invoke(long window, final int width, final int height) {
            if (width == 0 || height == 0)
                return;

            events.add(new Runnable() {
                @Override
                public void run() {
                    Renderer.this.ww = width;
                    Renderer.this.wh = height;

                    shouldInitBuffers = true;
                }
            });
        }
    });

    glfwSetFramebufferSizeCallback(window.handle,
            window.framebuffersizefun = new GLFWFramebufferSizeCallback() {
                @Override
                public void invoke(long window, final int width, final int height) {
                    if (width == 0 || height == 0)
                        return;

                    events.add(new Runnable() {
                        @Override
                        public void run() {
                            Renderer.this.fbw = width;
                            Renderer.this.fbh = height;

                            shouldInitBuffers = true;
                        }
                    });
                }
            });

    glfwSetKeyCallback(window.handle, window.keyfun = new GLFWKeyCallback() {
        @Override
        public void invoke(long window, int key, int scancode, int action, int mods) {

        }
    });

    glfwSetMouseButtonCallback(window.handle, window.mousebuttonfun = new GLFWMouseButtonCallback() {
        @Override
        public void invoke(long window, int button, int action, int mods) {

        }
    });

    glfwSetCursorPosCallback(window.handle, window.cursorposfun = new GLFWCursorPosCallback() {
        @Override
        public void invoke(long window, double xpos, double ypos) {

        }
    });

    glfwSetScrollCallback(window.handle, window.scrollfun = new GLFWScrollCallback() {
        @Override
        public void invoke(long window, double xoffset, double yoffset) {

        }
    });
}

From source file:robot.animation.RobotAnimation.java

private void init() {
    GLFW.glfwInit();// ww w .j av a 2s  .co  m
    robot1 = new Robot(0.5f);
    robot2 = new Robot(0.4f);
    selectedRobot = robot1;
    window = GLFW.glfwCreateWindow(800, 800, "Robot Animation", 0, 0);
    GLFW.glfwMakeContextCurrent(window);
    GL.createCapabilities();
    GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
    GLFW.glfwSwapBuffers(window);

    GLFW.glfwSetKeyCallback(window, new GLFWKeyCallback() {
        @Override
        public void invoke(long window, int key, int scancode, int action, int mods) {
            if (key == GLFW.GLFW_KEY_1)
                selectedRobot = robot1;
            if (key == GLFW.GLFW_KEY_2)
                selectedRobot = robot2;
            if (key == GLFW.GLFW_KEY_LEFT_SHIFT)
                leftShiftPressed = true;
            if (key == GLFW.GLFW_KEY_RIGHT_SHIFT)
                rightShiftPressed = true;
            if (key == GLFW.GLFW_KEY_U && mods == GLFW.GLFW_MOD_SHIFT) {
                if (leftShiftPressed)
                    selectedBodyPart = BodyPart.LEFT_UPPER_ARM;
                if (rightShiftPressed)
                    selectedBodyPart = BodyPart.RIGHT_UPPER_ARM;
                leftShiftPressed = false;
                rightShiftPressed = false;
            }
            if (key == GLFW.GLFW_KEY_F && mods == GLFW.GLFW_MOD_SHIFT) {
                if (leftShiftPressed)
                    selectedBodyPart = BodyPart.LEFT_FOREARM;
                if (rightShiftPressed)
                    selectedBodyPart = BodyPart.RIGHT_FOREARM;
                leftShiftPressed = false;
                rightShiftPressed = false;
            }
            if (key == GLFW.GLFW_KEY_ESCAPE) {
                GLFW.glfwSetWindowShouldClose(window, true);
            } else if (key == GLFW.GLFW_KEY_RIGHT) {
                switch (selectedBodyPart) {
                case LEFT_UPPER_ARM:
                    selectedRobot.decreaseLeftUpperArmTiltAngle();
                    break;
                case RIGHT_UPPER_ARM:
                    break;
                case LEFT_FOREARM:
                    break;
                case RIGHT_FOREARM:
                    break;
                case NONE:
                    selectedRobot.moveRight();
                    break;
                default:
                    break;
                }
            } else if (key == GLFW.GLFW_KEY_LEFT) {
                switch (selectedBodyPart) {
                case LEFT_UPPER_ARM:
                    selectedRobot.increaseLeftUpperArmTiltAngle();
                    break;
                case RIGHT_UPPER_ARM:
                    break;
                case LEFT_FOREARM:
                    break;
                case RIGHT_FOREARM:
                    break;
                case NONE:
                    selectedRobot.moveLeft();
                    break;
                default:
                    break;
                }
            }

            System.out.println("Selected body part " + selectedBodyPart);
        }
    });
}

From source file:sgl.opengl.OpenGL.java

License:Open Source License

/**
 * Depending on the calling method and what methods will be used in OpenGL specifically, this will initialize the {@link GLCapabilities} features.
 *///from   w w w  .  j  av  a 2 s  .c  om
public static void initialize() {
    GL.createCapabilities();
}

From source file:si.jernejp.org.Initialize.java

private void initOpenGL() throws IOException {
    glfwSetErrorCallback(GLFWErrorCallback.createPrint(System.err));
    if (!glfwInit()) {
        throw new IllegalStateException("Unable to initialize GLFW");
    }//  www.  j av  a 2 s .  c  o  m
    glfwDefaultWindowHints();
    glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
    glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
    //glfwWindowHint(GLFW_SAMPLES, 4);

    long monitor = glfwGetPrimaryMonitor();
    GLFWVidMode vidmode = glfwGetVideoMode(monitor);
    if (!configuration.get(Boolean.class, "windowed")) {
        windowDevice.width = vidmode.width();
        windowDevice.height = vidmode.height();
    }
    window = glfwCreateWindow(windowDevice.width, windowDevice.height, configuration.get(String.class, "title"),
            !configuration.get(Boolean.class, "windowed") ? monitor : 0L, NULL);
    windowDevice.windowId = window;
    if (window == NULL) {
        throw new RuntimeException("Failed to create the GLFW window");
    }
    glfwSetCursor(window, glfwCreateStandardCursor(configuration.get(Integer.class, "cursorType")));
    glfwSetFramebufferSizeCallback(window, windowDevice::windowCallback);
    glfwSetKeyCallback(window, keyboardDevice::keyboardCallback);
    glfwSetCursorPosCallback(window, inputDevice::cursorCallback);
    glfwSetMouseButtonCallback(window, inputDevice::mouseCallback);
    glfwMakeContextCurrent(window);
    glfwSwapInterval(0);
    glfwShowWindow(window);
    IntBuffer framebufferSize = BufferUtils.createIntBuffer(2);
    nglfwGetFramebufferSize(window, memAddress(framebufferSize), memAddress(framebufferSize) + 4);
    //width = framebufferSize.get(0);
    //height = framebufferSize.get(1);
    GLCapabilities caps = GL.createCapabilities();
    if (!caps.OpenGL20) {
        throw new AssertionError("This demo requires OpenGL 2.0.");
    }
    debugProc = (GLDebugMessageCallback) GLUtil.setupDebugMessageCallback();
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE);
}

From source file:vendalenger.kondion.Kondion.java

License:Apache License

public static void run(String identifier) {
    new Thread(new Runnable() {
        @Override/*from  w  ww . j a va2  s. com*/
        public void run() {
            /*loadingScreen = new JFrame("KONDION Game Engine");
            loadingScreen.setLayout(new BorderLayout());
            loadingScreen.setUndecorated(false);
            loadingScreen
                  .setIconImage(VD_FlConsole.consoleWindow.consoleWindow
                .getIconImage());
            loadingScreen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    
            ImageIcon img = new ImageIcon(Kondion.class
                  .getResource("kondion.png"));
            final JLabel imgl = new JLabel(img);
            imgl.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
            imgl.setOpaque(true);
            imgl.setBackground(java.awt.Color.decode("#080808"));
            imgl.setPreferredSize(new Dimension(800, 600));
                    
            loadingScreen.add(imgl);
            loadingScreen.pack();
            loadingScreen.setLocationRelativeTo(null);
            loadingScreen.setVisible(true);*/
        }

    }).start();

    gameThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Window.setNatives();

                if (width * height == 0) {
                    // No width or height has been specified
                    //width = 1280;
                    //height = 720;
                    width = 800;
                    height = 600;
                }

                Window.initGL(width, height, false, false, KLoader.getKResource(identifier).getNeatName());
                GL.createCapabilities();
                GLDrawing.setup();
                ///FlatDrawing.
                jsEngine = new ScriptEngineManager().getEngineByName("nashorn");

                System.out.println("Loading Javascript...");

                //((ScriptObjectMirror) jsEngine.get("Math")).setMember("sign", );

                //System.out.println((((ScriptObjectMirror) jsEngine.get("wurla")).get("eggs").getClass()));
                jsEngine.eval(new BufferedReader(
                        new InputStreamReader(getClass().getResourceAsStream("kondiondefault.js"))));

                System.out.print("Parsing game information...");
                JsonRootNode rootNode = KLoader.getKResource(identifier).getConfig();

                // reusable variable
                List<JsonNode> array;

                // Buttons

                System.out.println("Loading buttons...");

                JsonNode node = rootNode.getNode("Buttons");
                for (int i = 0; i < node.getFieldList().size(); i++) {
                    array = node.getFieldList().get(i).getValue().getArrayNode();
                    KInput.regButton(node.getFieldList().get(i).getName().getStringValue(),
                            array.get(0).getStringValue(),
                            (array.get(1).getStringValue().equals("key")) ? (0) : (1),
                            KInput.toGLFWCode(array.get(2).getStringValue().charAt(0)));
                }

                // Graphics

                node = rootNode.getNode("Graphics");

                System.out.println("Loading textures (" + node.getFieldList().size() + ")");

                try {
                    for (int i = 0; i < node.getFieldList().size(); i++) {
                        array = node.getFieldList().get(i).getValue().getArrayNode();

                        System.out.println("TEXTURE: " + node.getFieldList().get(i).getName().getStringValue());

                        KLoader.registerTexture(identifier + ":" + array.get(0).getStringValue(),
                                node.getFieldList().get(i).getName().getStringValue(),
                                GL11.class.getField(array.get(1).getStringValue()).getInt(0),
                                GL11.class.getField(array.get(2).getStringValue()).getInt(0),
                                GL11.class.getField(array.get(3).getStringValue()).getInt(0),
                                GL11.class.getField(array.get(4).getStringValue()).getInt(0), true);
                    }
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (SecurityException e) {
                    e.printStackTrace();
                }

                // OBJ

                node = rootNode.getNode("OBJ");

                System.out.println("Loading OBJ models (" + node.getFieldList().size() + ")");

                try {
                    for (int i = 0; i < node.getFieldList().size(); i++) {
                        array = node.getFieldList().get(i).getValue().getArrayNode();

                        KLoader.registerObj(identifier + ":" + array.get(0).getStringValue(),
                                node.getFieldList().get(i).getName().getStringValue(),
                                array.get(1).getStringValue(), true);
                    }
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                }

                // Audio

                node = rootNode.getNode("Audio");

                System.out.println("Loading Audio (" + node.getFieldList().size() + ")");

                try {
                    for (int i = 0; i < node.getFieldList().size(); i++) {
                        array = node.getFieldList().get(i).getValue().getArrayNode();
                        if (array.get(0).getStringValue().startsWith("ol:"))
                            KLoader.registerAudio(array.get(0).getStringValue(),
                                    node.getFieldList().get(i).getName().getStringValue(), true);
                        else
                            KLoader.registerAudio(identifier + ":" + array.get(0).getStringValue(),
                                    node.getFieldList().get(i).getName().getStringValue(), true);

                        //KLoader.registerObj(identifier + ":" + array.get(0).getStringValue(),
                        //      node.getFieldList().get(i).getName().getStringValue(),
                        //      array.get(1).getStringValue(), true);
                    }
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                }

                System.out.println("Doing other stuff...");

                GLDrawing.setup();

                System.out.print("Loading game scripts...");

                jsEngine.eval(new InputStreamReader(KLoader.get(identifier + ":masterjs")));

                dummyCamera = new OKO_Camera_();
                dummyCamera.look(0, 0, 5, 0, 0, 0);
                //dummyCamera.setFreeMode(true);

                kjs = new KJS();
                jsEngine.put("KJS", kjs);
                ((Invocable) jsEngine).invokeFunction("init");
                Window.update();
                KLoader.load();

                //loadingScreen.setVisible(false);
                //loadingScreen.dispose();

                gameLoop();
            } catch (ScriptException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
    });
    gameThread.start();
}