List of usage examples for org.lwjgl.opengl GL createCapabilities
public static GLCapabilities createCapabilities()
From source file:org.lwjgl.demo.glfw.MultipleWindows.java
License:Open Source License
private static void demo() { glfwDefaultWindowHints();//from ww w . j a va 2 s .co m glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); Window[] windows = new Window[4]; AtomicInteger latch = new AtomicInteger(windows.length); for (int i = 0; i < windows.length; i++) { int windowIndex = i + 1; long handle = glfwCreateWindow(300, 200, "GLFW Demo - " + windowIndex, NULL, NULL); if (handle == NULL) { throw new IllegalStateException("Failed to create GLFW window"); } Window window = new Window(handle); glfwSetCursorEnterCallback(handle, (windowHnd, entered) -> { if (entered) { System.out.println("Mouse entered window: " + windowIndex); } }); glfwSetKeyCallback(handle, (windowHnd, key, scancode, action, mods) -> { if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE) { Arrays.stream(windows).filter(Objects::nonNull) .forEach(w -> glfwSetWindowShouldClose(w.handle, true)); } }); glfwMakeContextCurrent(handle); window.capabilities = GL.createCapabilities(); glClearColor((i & 1), (i >> 1), (i == 1) ? 0.f : 1.f, 0.f); glfwShowWindow(handle); glfwSetWindowPos(handle, 100 + (i & 1) * 400, 100 + (i >> 1) * 400); windows[i] = window; } while (latch.get() != 0) { glfwPollEvents(); for (int i = 0; i < 4; i++) { Window window = windows[i]; if (window == null) { continue; } glfwMakeContextCurrent(window.handle); GL.setCapabilities(window.capabilities); glClear(GL_COLOR_BUFFER_BIT); glfwSwapBuffers(window.handle); if (glfwWindowShouldClose(window.handle)) { glfwFreeCallbacks(window.handle); glfwDestroyWindow(window.handle); windows[i] = null; latch.decrementAndGet(); } } } }
From source file:org.lwjgl.demo.nanovg.ExampleFBO.java
License:Open Source License
public static void main(String[] args) { GLFWErrorCallback.createPrint().set(); if (!glfwInit()) { throw new RuntimeException("Failed to init GLFW."); }/*www . j ava 2 s .co m*/ GPUtimer gpuTimer = new GPUtimer(); PerfGraph fps = new PerfGraph(); PerfGraph cpuGraph = new PerfGraph(); PerfGraph gpuGraph = new PerfGraph(); initGraph(fps, GRAPH_RENDER_FPS, "Frame Time"); initGraph(cpuGraph, GRAPH_RENDER_MS, "CPU Time"); initGraph(gpuGraph, GRAPH_RENDER_MS, "GPU Time"); if (Platform.get() == Platform.MACOSX) { glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); } boolean DEMO_MSAA = args.length != 0 && "msaa".equalsIgnoreCase(args[0]); if (DEMO_MSAA) { glfwWindowHint(GLFW_SAMPLES, 8); } long window = glfwCreateWindow(1000, 600, "NanoVG", NULL, NULL); //window = glfwCreateWindow(1000, 600, "NanoVG", glfwGetPrimaryMonitor(), NULL); if (window == NULL) { glfwTerminate(); throw new RuntimeException(); } glfwSetKeyCallback(window, (windowHandle, keyCode, scancode, action, mods) -> { if (keyCode == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { glfwSetWindowShouldClose(windowHandle, true); } }); glfwMakeContextCurrent(window); GL.createCapabilities(); long vg = nvgCreate(DEMO_MSAA ? 0 : NVG_ANTIALIAS); if (vg == NULL) { throw new RuntimeException("Could not init nanovg."); } // Create hi-dpi FBO for hi-dpi screens. glfwGetWindowSize(window, winWidth, winHeight); glfwGetFramebufferSize(window, fbWidth, fbHeight); // Calculate pixel ration for hi-dpi devices. float pxRatio = (float) fbWidth.get(0) / (float) winWidth.get(0); // The image pattern is tiled, set repeat on x and y. NVGLUFramebuffer fb = nvgluCreateFramebuffer(vg, (int) (100 * pxRatio), (int) (100 * pxRatio), NVG_IMAGE_REPEATX | NVG_IMAGE_REPEATY); if (fb == null) { throw new RuntimeException("Could not create FBO."); } loadFonts(vg); glfwSwapInterval(0); initGPUTimer(gpuTimer); glfwSetTime(0); double prevt = glfwGetTime(); while (!glfwWindowShouldClose(window)) { double t = glfwGetTime(); double dt = t - prevt; prevt = t; startGPUTimer(gpuTimer); glfwGetCursorPos(window, mx, my); glfwGetWindowSize(window, winWidth, winHeight); glfwGetFramebufferSize(window, fbWidth, fbHeight); // Calculate pixel ration for hi-dpi devices. pxRatio = (float) fbWidth.get(0) / (float) winWidth.get(0); renderPattern(vg, fb, (float) t, pxRatio); // Update and render glViewport(0, 0, fbWidth.get(0), fbHeight.get(0)); glClearColor(0.3f, 0.3f, 0.32f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); nvgBeginFrame(vg, winWidth.get(0), winHeight.get(0), pxRatio); // Use the FBO as image pattern. NVGPaint img = paintA; nvgImagePattern(vg, 0, 0, 100, 100, 0, fb.image(), 1.0f, img); nvgSave(vg); for (int i = 0; i < 20; i++) { nvgBeginPath(vg); nvgRect(vg, 10 + i * 30, 10, 10, winHeight.get(0) - 20); nvgHSLA(i / 19.0f, 0.5f, 0.5f, (byte) 255, colorA); nvgFillColor(vg, colorA); nvgFill(vg); } nvgBeginPath(vg); nvgRoundedRect(vg, 140 + (float) Math.sin(t * 1.3f) * 100, 140 + (float) Math.cos(t * 1.71244f) * 100, 250, 250, 20); nvgFillPaint(vg, img); nvgFill(vg); nvgStrokeColor(vg, rgba(220, 160, 0, 255, colorA)); nvgStrokeWidth(vg, 3.0f); nvgStroke(vg); nvgRestore(vg); renderGraph(vg, 5, 5, fps); renderGraph(vg, 5 + 200 + 5, 5, cpuGraph); if (gpuTimer.supported) { renderGraph(vg, 5 + 200 + 5 + 200 + 5, 5, gpuGraph); } nvgEndFrame(vg); // Measure the CPU time taken excluding swap buffers (as the swap may wait for GPU) double cpuTime = glfwGetTime() - t; updateGraph(fps, (float) dt); updateGraph(cpuGraph, (float) cpuTime); // We may get multiple results. int n = stopGPUTimer(gpuTimer, gpuTimes, 3); for (int i = 0; i < n; i++) { updateGraph(gpuGraph, gpuTimes.get(i)); } glfwSwapBuffers(window); glfwPollEvents(); } nvgluDeleteFramebuffer(vg, fb); nvgDelete(vg); System.out.format("Average Frame Time: %.2f ms\n", getGraphAverage(fps) * 1000.0f); System.out.format(" CPU Time: %.2f ms\n", getGraphAverage(cpuGraph) * 1000.0f); System.out.format(" GPU Time: %.2f ms\n", getGraphAverage(gpuGraph) * 1000.0f); glfwFreeCallbacks(window); glfwTerminate(); Objects.requireNonNull(glfwSetErrorCallback(null)).free(); }
From source file:org.lwjgl.demo.nanovg.ExampleGL2.java
License:Open Source License
public static void main(String[] args) { GLFWErrorCallback.createPrint().set(); if (!glfwInit()) { throw new RuntimeException("Failed to init GLFW."); }//from ww w. j a va 2 s. c o m DemoData data = new DemoData(); PerfGraph fps = new PerfGraph(); initGraph(fps, GRAPH_RENDER_FPS, "Frame Time"); boolean DEMO_MSAA = args.length != 0 && "msaa".equalsIgnoreCase(args[0]); if (DEMO_MSAA) { glfwWindowHint(GLFW_SAMPLES, 8); } long window = glfwCreateWindow(1000, 600, "NanoVG", NULL, NULL); //window = glfwCreateWindow(1000, 600, "NanoVG", glfwGetPrimaryMonitor(), NULL); if (window == NULL) { glfwTerminate(); throw new RuntimeException(); } glfwSetKeyCallback(window, (windowHandle, keyCode, scancode, action, mods) -> { if (keyCode == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { glfwSetWindowShouldClose(windowHandle, true); } if (keyCode == GLFW_KEY_SPACE && action == GLFW_PRESS) { blowup = !blowup; } if (keyCode == GLFW_KEY_S && action == GLFW_PRESS) { screenshot = true; } if (keyCode == GLFW_KEY_P && action == GLFW_PRESS) { premult = !premult; } }); glfwMakeContextCurrent(window); GL.createCapabilities(); long vg = nvgCreate(DEMO_MSAA ? 0 : NVG_ANTIALIAS); if (vg == NULL) { throw new RuntimeException("Could not init nanovg."); } if (loadDemoData(vg, data) == -1) { throw new RuntimeException(); } glfwSwapInterval(0); glfwSetTime(0); double prevt = glfwGetTime(); while (!glfwWindowShouldClose(window)) { double t = glfwGetTime(); double dt = t - prevt; prevt = t; updateGraph(fps, (float) dt); glfwGetCursorPos(window, mx, my); glfwGetWindowSize(window, winWidth, winHeight); glfwGetFramebufferSize(window, fbWidth, fbHeight); // Calculate pixel ration for hi-dpi devices. float pxRatio = (float) fbWidth.get(0) / (float) winWidth.get(0); // Update and render glViewport(0, 0, fbWidth.get(0), fbHeight.get(0)); if (premult) { glClearColor(0, 0, 0, 0); } else { glClearColor(0.3f, 0.3f, 0.32f, 1.0f); } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); nvgBeginFrame(vg, winWidth.get(0), winHeight.get(0), pxRatio); renderDemo(vg, (float) mx.get(0), (float) my.get(0), winWidth.get(0), winHeight.get(0), (float) t, blowup, data); renderGraph(vg, 5, 5, fps); nvgEndFrame(vg); if (screenshot) { screenshot = false; saveScreenShot(fbWidth.get(0), fbHeight.get(0), premult, "dump.png"); } glfwSwapBuffers(window); glfwPollEvents(); } freeDemoData(vg, data); nvgDelete(vg); glfwFreeCallbacks(window); glfwTerminate(); Objects.requireNonNull(glfwSetErrorCallback(null)).free(); }
From source file:org.lwjgl.demo.nanovg.ExampleGL3.java
License:Open Source License
public static void main(String[] args) { GLFWErrorCallback.createPrint().set(); if (!glfwInit()) { throw new RuntimeException("Failed to init GLFW."); }/*from www.java 2 s. c om*/ DemoData data = new DemoData(); GPUtimer gpuTimer = new GPUtimer(); PerfGraph fps = new PerfGraph(); PerfGraph cpuGraph = new PerfGraph(); PerfGraph gpuGraph = new PerfGraph(); initGraph(fps, GRAPH_RENDER_FPS, "Frame Time"); initGraph(cpuGraph, GRAPH_RENDER_MS, "CPU Time"); initGraph(gpuGraph, GRAPH_RENDER_MS, "GPU Time"); if (Platform.get() == Platform.MACOSX) { glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); } boolean DEMO_MSAA = args.length != 0 && "msaa".equalsIgnoreCase(args[0]); if (DEMO_MSAA) { glfwWindowHint(GLFW_SAMPLES, 8); } long window = glfwCreateWindow(1000, 600, "NanoVG", NULL, NULL); //window = glfwCreateWindow(1000, 600, "NanoVG", glfwGetPrimaryMonitor(), NULL); if (window == NULL) { glfwTerminate(); throw new RuntimeException(); } glfwSetKeyCallback(window, (windowHandle, keyCode, scancode, action, mods) -> { if (keyCode == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { glfwSetWindowShouldClose(windowHandle, true); } if (keyCode == GLFW_KEY_SPACE && action == GLFW_PRESS) { blowup = !blowup; } if (keyCode == GLFW_KEY_S && action == GLFW_PRESS) { screenshot = true; } if (keyCode == GLFW_KEY_P && action == GLFW_PRESS) { premult = !premult; } }); glfwMakeContextCurrent(window); GL.createCapabilities(); long vg = nvgCreate(DEMO_MSAA ? 0 : NVG_ANTIALIAS); if (vg == NULL) { throw new RuntimeException("Could not init nanovg."); } if (loadDemoData(vg, data) == -1) { throw new RuntimeException(); } glfwSwapInterval(0); initGPUTimer(gpuTimer); glfwSetTime(0); double prevt = glfwGetTime(); while (!glfwWindowShouldClose(window)) { double t, dt; float pxRatio; t = glfwGetTime(); dt = t - prevt; prevt = t; updateGraph(fps, (float) dt); startGPUTimer(gpuTimer); glfwGetCursorPos(window, mx, my); glfwGetWindowSize(window, winWidth, winHeight); glfwGetFramebufferSize(window, fbWidth, fbHeight); // Calculate pixel ration for hi-dpi devices. pxRatio = (float) fbWidth.get(0) / (float) winWidth.get(0); // Update and render glViewport(0, 0, fbWidth.get(0), fbHeight.get(0)); if (premult) { glClearColor(0, 0, 0, 0); } else { glClearColor(0.3f, 0.3f, 0.32f, 1.0f); } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); nvgBeginFrame(vg, winWidth.get(0), winHeight.get(0), pxRatio); renderDemo(vg, (float) mx.get(0), (float) my.get(0), winWidth.get(0), winHeight.get(0), (float) t, blowup, data); renderGraph(vg, 5, 5, fps); renderGraph(vg, 5 + 200 + 5, 5, cpuGraph); if (gpuTimer.supported) { renderGraph(vg, 5 + 200 + 5 + 200 + 5, 5, gpuGraph); } nvgEndFrame(vg); // Measure the CPU time taken excluding swap buffers (as the swap may wait for GPU) double cpuTime = glfwGetTime() - t; updateGraph(fps, (float) dt); updateGraph(cpuGraph, (float) cpuTime); // We may get multiple results. int n = stopGPUTimer(gpuTimer, gpuTimes, 3); for (int i = 0; i < n; i++) { updateGraph(gpuGraph, gpuTimes.get(i)); } if (screenshot) { screenshot = false; saveScreenShot(fbWidth.get(0), fbHeight.get(0), premult, "dump.png"); } glfwSwapBuffers(window); glfwPollEvents(); } freeDemoData(vg, data); nvgDelete(vg); System.out.printf("Average Frame Time: %.2f ms\n", getGraphAverage(fps) * 1000.0f); System.out.printf(" CPU Time: %.2f ms\n", getGraphAverage(cpuGraph) * 1000.0f); System.out.printf(" GPU Time: %.2f ms\n", getGraphAverage(gpuGraph) * 1000.0f); glfwFreeCallbacks(window); glfwTerminate(); Objects.requireNonNull(glfwSetErrorCallback(null)).free(); }
From source file:org.lwjgl.demo.nanovg.SVGDemo.java
License:Open Source License
private void init() { System.out.print("Creating window..."); long t = System.nanoTime(); GLFWErrorCallback.createPrint().set(); if (!glfwInit()) { throw new IllegalStateException("Unable to initialize GLFW"); }/* w w w . jav a2s. c o m*/ glfwDefaultWindowHints(); glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); GLFWVidMode vidmode = Objects.requireNonNull(glfwGetVideoMode(glfwGetPrimaryMonitor())); ww = max(800, min(w, vidmode.width() - 160)); wh = max(600, min(h, vidmode.height() - 120)); this.window = glfwCreateWindow(ww, wh, "NanoSVG Demo", NULL, NULL); if (window == NULL) { throw new RuntimeException("Failed to create the GLFW window"); } // Center window glfwSetWindowPos(window, (vidmode.width() - ww) / 2, (vidmode.height() - wh) / 2); glfwSetWindowRefreshCallback(window, window -> render()); glfwSetWindowSizeCallback(window, this::windowSizeChanged); glfwSetFramebufferSizeCallback(window, SVGDemo::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); } }); // Create context glfwMakeContextCurrent(window); GL.createCapabilities(); debugProc = GLUtil.setupDebugMessageCallback(); glfwSwapInterval(1); glfwShowWindow(window); glfwInvoke(window, this::windowSizeChanged, SVGDemo::framebufferSizeChanged); t = System.nanoTime() - t; System.out.format("%dms\n", t / 1000 / 1000); }
From source file:org.lwjgl.demo.nuklear.GLFWDemo.java
License:Open Source License
private void run() { GLFWErrorCallback.createPrint().set(); if (!glfwInit()) { throw new IllegalStateException("Unable to initialize glfw"); }// w w w. ja v a2s.co m glfwDefaultWindowHints(); glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); if (Platform.get() == Platform.MACOSX) { glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE); } glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE); int WINDOW_WIDTH = 640; int WINDOW_HEIGHT = 640; win = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "GLFW Nuklear Demo", NULL, NULL); if (win == NULL) { throw new RuntimeException("Failed to create the GLFW window"); } glfwMakeContextCurrent(win); GLCapabilities caps = GL.createCapabilities(); Callback debugProc = GLUtil.setupDebugMessageCallback(); 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(KHRDebug.GL_DEBUG_SOURCE_API, KHRDebug.GL_DEBUG_TYPE_OTHER, KHRDebug.GL_DEBUG_SEVERITY_NOTIFICATION, (IntBuffer) null, false); } else if (caps.GL_ARB_debug_output) { glDebugMessageControlARB(GL_DEBUG_SOURCE_API_ARB, GL_DEBUG_TYPE_OTHER_ARB, GL_DEBUG_SEVERITY_LOW_ARB, (IntBuffer) null, false); } NkContext ctx = setupWindow(win); int BITMAP_W = 1024; int BITMAP_H = 1024; int FONT_HEIGHT = 18; int fontTexID = glGenTextures(); STBTTFontinfo fontInfo = STBTTFontinfo.create(); STBTTPackedchar.Buffer cdata = STBTTPackedchar.create(95); float scale; float descent; try (MemoryStack stack = stackPush()) { stbtt_InitFont(fontInfo, ttf); scale = stbtt_ScaleForPixelHeight(fontInfo, FONT_HEIGHT); IntBuffer d = stack.mallocInt(1); stbtt_GetFontVMetrics(fontInfo, null, d, null); descent = d.get(0) * scale; ByteBuffer bitmap = memAlloc(BITMAP_W * BITMAP_H); STBTTPackContext pc = STBTTPackContext.mallocStack(stack); stbtt_PackBegin(pc, bitmap, BITMAP_W, BITMAP_H, 0, 1, NULL); stbtt_PackSetOversampling(pc, 4, 4); stbtt_PackFontRange(pc, ttf, 0, FONT_HEIGHT, 32, cdata); stbtt_PackEnd(pc); // Convert R8 to RGBA8 ByteBuffer texture = memAlloc(BITMAP_W * BITMAP_H * 4); for (int i = 0; i < bitmap.capacity(); i++) { texture.putInt((bitmap.get(i) << 24) | 0x00FFFFFF); } texture.flip(); glBindTexture(GL_TEXTURE_2D, fontTexID); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, BITMAP_W, BITMAP_H, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); memFree(texture); memFree(bitmap); } default_font.width((handle, h, text, len) -> { float text_width = 0; try (MemoryStack stack = stackPush()) { IntBuffer unicode = stack.mallocInt(1); int glyph_len = nnk_utf_decode(text, memAddress(unicode), len); int text_len = glyph_len; if (glyph_len == 0) { return 0; } IntBuffer advance = stack.mallocInt(1); while (text_len <= len && glyph_len != 0) { if (unicode.get(0) == NK_UTF_INVALID) { break; } /* query currently drawn glyph information */ stbtt_GetCodepointHMetrics(fontInfo, unicode.get(0), advance, null); text_width += advance.get(0) * scale; /* offset next glyph */ glyph_len = nnk_utf_decode(text + text_len, memAddress(unicode), len - text_len); text_len += glyph_len; } } return text_width; }).height(FONT_HEIGHT).query((handle, font_height, glyph, codepoint, next_codepoint) -> { try (MemoryStack stack = stackPush()) { FloatBuffer x = stack.floats(0.0f); FloatBuffer y = stack.floats(0.0f); STBTTAlignedQuad q = STBTTAlignedQuad.mallocStack(stack); IntBuffer advance = stack.mallocInt(1); stbtt_GetPackedQuad(cdata, BITMAP_W, BITMAP_H, codepoint - 32, x, y, q, false); stbtt_GetCodepointHMetrics(fontInfo, codepoint, advance, null); NkUserFontGlyph ufg = NkUserFontGlyph.create(glyph); ufg.width(q.x1() - q.x0()); ufg.height(q.y1() - q.y0()); ufg.offset().set(q.x0(), q.y0() + (FONT_HEIGHT + descent)); ufg.xadvance(advance.get(0) * scale); ufg.uv(0).set(q.s0(), q.t0()); ufg.uv(1).set(q.s1(), q.t1()); } }).texture().id(fontTexID); nk_style_set_font(ctx, default_font); glfwShowWindow(win); while (!glfwWindowShouldClose(win)) { /* Input */ newFrame(); demo.layout(ctx, 50, 50); calc.layout(ctx, 300, 50); try (MemoryStack stack = stackPush()) { IntBuffer width = stack.mallocInt(1); IntBuffer height = stack.mallocInt(1); glfwGetWindowSize(win, width, height); glViewport(0, 0, width.get(0), height.get(0)); NkColorf bg = demo.background; glClearColor(bg.r(), bg.g(), bg.b(), bg.a()); } glClear(GL_COLOR_BUFFER_BIT); /* * IMPORTANT: `nk_glfw_render` modifies some global OpenGL state * with blending, scissor, face culling, depth test and viewport and * defaults everything back into a default state. * Make sure to either a.) save and restore or b.) reset your own state after * rendering the UI. */ render(NK_ANTI_ALIASING_ON, MAX_VERTEX_BUFFER, MAX_ELEMENT_BUFFER); glfwSwapBuffers(win); } shutdown(); glfwFreeCallbacks(win); if (debugProc != null) { debugProc.free(); } glfwTerminate(); Objects.requireNonNull(glfwSetErrorCallback(null)).free(); }
From source file:org.lwjgl.demo.opencl.CLGLInteropDemo.java
License:Open Source License
private static String getOpenGLVendor() { long window = glfwCreateWindow(100, 100, "dummy", NULL, NULL); try {//w w w . j a va2 s . co m glfwMakeContextCurrent(window); GL.createCapabilities(); return glGetString(GL_VENDOR); } finally { glfwDestroyWindow(window); } }
From source file:org.lwjgl.demo.opencl.Mandelbrot.java
License:Open Source License
public Mandelbrot(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 ww . j a va 2s . c o 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 { 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); try (MemoryStack stack = stackPush()) { glBufferData(GL_ARRAY_BUFFER, stack.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); } 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:org.lwjgl.demo.opengl.fbo.DepthEdgeShaderDemo20.java
License:Open Source License
void init() throws IOException { glfwSetErrorCallback(errCallback = new GLFWErrorCallback() { GLFWErrorCallback delegate = GLFWErrorCallback.createPrint(System.err); @Override/*from w w w . j a va2s.c om*/ public void invoke(int error, long description) { if (error == GLFW_VERSION_UNAVAILABLE) System.err.println("This demo requires OpenGL 2.0 or higher."); delegate.invoke(error, description); } @Override public void free() { delegate.free(); } }); if (!glfwInit()) throw new IllegalStateException("Unable to initialize GLFW"); glfwDefaultWindowHints(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); window = glfwCreateWindow(width, height, "Silhouette rendering with edge detection shader", NULL, NULL); if (window == NULL) { throw new AssertionError("Failed to create the GLFW window"); } System.out.println("Press spacebar to show/hide edges."); glfwSetFramebufferSizeCallback(window, fbCallback = new GLFWFramebufferSizeCallback() { @Override public void invoke(long window, int width, int height) { if (width > 0 && height > 0 && (DepthEdgeShaderDemo20.this.width != width || DepthEdgeShaderDemo20.this.height != height)) { DepthEdgeShaderDemo20.this.width = width; DepthEdgeShaderDemo20.this.height = height; DepthEdgeShaderDemo20.this.resize = true; } } }); 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); } else if (key == GLFW_KEY_SPACE) { showEdge = !showEdge; } } }); GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor()); glfwSetWindowPos(window, (vidmode.width() - width) / 2, (vidmode.height() - height) / 2); glfwMakeContextCurrent(window); glfwSwapInterval(0); glfwShowWindow(window); caps = GL.createCapabilities(); if (!caps.GL_EXT_framebuffer_object) { throw new AssertionError("This demo requires the EXT_framebuffer_object extension"); } if (!caps.GL_ARB_texture_float) { throw new AssertionError("This demo requires the ARB_texture_float extension"); } debugProc = GLUtil.setupDebugMessageCallback(); glClearColor(0.0f, 0.0f, 1.0f, 0.0f); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); /* Create all needed GL resources */ createCube(); createQuad(); createNormalProgram(); createEdgeProgram(); createTex(); createFbo(); }
From source file:org.lwjgl.demo.opengl.fbo.EdgeShaderDemo20.java
License:Open Source License
void init() throws IOException { glfwSetErrorCallback(errCallback = new GLFWErrorCallback() { GLFWErrorCallback delegate = GLFWErrorCallback.createPrint(System.err); @Override//www . jav a 2 s .c o m public void invoke(int error, long description) { if (error == GLFW_VERSION_UNAVAILABLE) System.err.println("This demo requires OpenGL 2.0 or higher."); delegate.invoke(error, description); } @Override public void free() { delegate.free(); } }); if (!glfwInit()) throw new IllegalStateException("Unable to initialize GLFW"); glfwDefaultWindowHints(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); window = glfwCreateWindow(width, height, "Silhouette rendering with Sobel edge detection shader", NULL, NULL); if (window == NULL) { throw new AssertionError("Failed to create the GLFW window"); } System.out.println("Press letter 'O' to toggle between outline/edges."); System.out.println("Press spacebar to show/hide edges."); glfwSetFramebufferSizeCallback(window, fbCallback = new GLFWFramebufferSizeCallback() { @Override public void invoke(long window, int width, int height) { if (width > 0 && height > 0 && (EdgeShaderDemo20.this.width != width || EdgeShaderDemo20.this.height != height)) { EdgeShaderDemo20.this.width = width; EdgeShaderDemo20.this.height = height; EdgeShaderDemo20.this.resize = true; } } }); 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); } else if (key == GLFW_KEY_O) { outlineOnly = !outlineOnly; } else if (key == GLFW_KEY_SPACE) { showEdge = !showEdge; } } }); GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor()); glfwSetWindowPos(window, (vidmode.width() - width) / 2, (vidmode.height() - height) / 2); glfwMakeContextCurrent(window); glfwSwapInterval(0); glfwShowWindow(window); caps = GL.createCapabilities(); if (!caps.GL_EXT_framebuffer_object) { throw new AssertionError("This demo requires the EXT_framebuffer_object extension"); } debugProc = GLUtil.setupDebugMessageCallback(); glClearColor(1.0f, 1.0f, 1.0f, 0.0f); // using alpha = 0.0 is important here for the outline to work! glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); /* Create all needed GL resources */ createCube(); createQuad(); createNormalProgram(); createEdgeProgram(); createOutlineProgram(); createTex(); createFbo(); }