/** * Loads a texture from a file at the specified path. * * @param path - File path of the texture file. * * @return A Texture built from the specified file. */ public static Texture loadTexture(String path) { ByteBuffer image; int width; int height; try (MemoryStack stack = MemoryStack.stackPush()) { IntBuffer w = stack.mallocInt(1); IntBuffer h = stack.mallocInt(1); IntBuffer comp = stack.mallocInt(1); // Load image using the STB library stbi_set_flip_vertically_on_load(false); image = stbi_load(path, w, h, comp, 4); if (image == null) { throw new RuntimeException("Failed to load a texture file! " + stbi_failure_reason()); } width = w.get(); height = h.get(); } return createTexture(width, height, image); }
private void updateViewPort(ViewPort viewport) { if (viewport == this.defaultViewPort) { //FIXME: This is a fix (hack?) for Mac's weird hack to scale windows for compatibility try (MemoryStack stack = MemoryStack.stackPush()) { IntBuffer pWidth = stack.mallocInt(1); IntBuffer pHeight = stack.mallocInt(1); GLFW.glfwGetFramebufferSize(this.window.handle(), pWidth, pHeight); GL11.glViewport(0, 0, pWidth.get(0), pHeight.get(0)); } } else { GL11.glViewport(viewport.getX(), viewport.getY(), viewport.getWidth(), viewport.getHeight()); } }
public void makeWindowCentered() { // Get the thread stack and push a new frame try (MemoryStack stack = MemoryStack.stackPush()) { IntBuffer pWidth = stack.mallocInt(1); // int* IntBuffer pHeight = stack.mallocInt(1); // int* // Get the window size passed to glfwCreateWindow GLFW.glfwGetWindowSize(this.handle, pWidth, pHeight); this.width = pWidth.get(0); this.height = pHeight.get(0); // Get the resolution of the primary monitor GLFWVidMode vidmode = getCurrentVideoMode(); // Center the window GLFW.glfwSetWindowPos( this.handle, this.x = ((vidmode.width() - this.width) / 2), this.y = ((vidmode.height() - this.height) / 2) ); } // the stack frame is popped automatically }
private ShortBuffer readVorbis(String resource, int bufferSize, STBVorbisInfo info) throws Exception { try (MemoryStack stack = MemoryStack.stackPush()) { vorbis = Utils.ioResourceToByteBuffer(resource, bufferSize); IntBuffer error = stack.mallocInt(1); long decoder = stb_vorbis_open_memory(vorbis, error, null); if (decoder == NULL) { throw new RuntimeException("Failed to open Ogg Vorbis file. Error: " + error.get(0)); } stb_vorbis_get_info(decoder, info); int channels = info.channels(); int lengthSamples = stb_vorbis_stream_length_in_samples(decoder); pcm = MemoryUtil.memAllocShort(lengthSamples); pcm.limit(stb_vorbis_get_samples_short_interleaved(decoder, channels, pcm) * channels); stb_vorbis_close(decoder); return pcm; } }
public Texture(ByteBuffer image) { try (MemoryStack stack = MemoryStack.stackPush()) { IntBuffer w = stack.mallocInt(1); IntBuffer h = stack.mallocInt(1); IntBuffer avChannels = stack.mallocInt(1); ByteBuffer decodedImage = stbi_load_from_memory(image, w, h, avChannels, 4); this.width = w.get(); this.height = h.get(); this.id = glGenTextures(); Loader.textures.add(id); glBindTexture(GL_TEXTURE_2D, this.id); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, this.width, this.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, decodedImage); glGenerateMipmap(GL_TEXTURE_2D); } }
public long create(GLCanvas canvas, GLData attribs, GLData effective) { Canvas dummycanvas = new Canvas(canvas.getParent(), checkStyle(canvas.getParent(), canvas.getStyle())); long context = 0L; MemoryStack stack = MemoryStack.stackGet(); int ptr = stack.getPointer(); try { context = create(canvas.handle, dummycanvas.handle, attribs, effective); } catch (SWTException e) { stack.setPointer(ptr); SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH, e); } final long finalContext = context; dummycanvas.dispose(); Listener listener = new Listener() { public void handleEvent(Event event) { switch (event.type) { case SWT.Dispose: deleteContext(finalContext); break; } } }; canvas.addListener(SWT.Dispose, listener); return context; }
/** * Loads an image from a file. Supported formats are * <ul> * <li>JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib</li> * <li>PNG 1/2/4/8-bit-per-channel (16 bpc not supported)</li> * <li>TGA (not sure what subset, if a subset)</li> * <li>BMP non-1bpp, non-RLE</li> * <li>PSD (composited view only, no extra channels, 8/16 bit-per-channel)</li> * <li>GIF (*comp always reports as 4-channel)</li> * <li>HDR (radiance rgbE format)</li> * <li>PIC (Softimage PIC)</li> * <li>PNM (PPM and PGM binary only)</li> * </ul> * @param path path to the file * @return {@link ImageData} with info about the image * @see org.lwjgl.stb.STBImage STBImage, image decoder */ public static ImageData loadImage(final File path) { ImageData data = new ImageData(); try(MemoryStack stack = MemoryStack.stackPush()) { IntBuffer x = stack.ints(0), y = stack.ints(0), comp = stack.ints(0); data.data = org.lwjgl.stb.STBImage.stbi_load(path.getAbsolutePath(), x, y, comp, 0); if(data.data == null) throw new RuntimeException(org.lwjgl.stb.STBImage.stbi_failure_reason()); data.width = x.get(); data.height = y.get(); data.components = comp.get(); data.clear = o -> { org.lwjgl.stb.STBImage.stbi_image_free(o.data); return null; }; } return data; }
/** * Loads an image from a chunk of memory. Supported formats are * <ul> * <li>JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib</li> * <li>PNG 1/2/4/8-bit-per-channel (16 bpc not supported)</li> * <li>TGA (not sure what subset, if a subset)</li> * <li>BMP non-1bpp, non-RLE</li> * <li>PSD (composited view only, no extra channels, 8/16 bit-per-channel)</li> * <li>GIF (*comp always reports as 4-channel)</li> * <li>HDR (radiance rgbE format)</li> * <li>PIC (Softimage PIC)</li> * <li>PNM (PPM and PGM binary only)</li> * </ul> * @param buff the chunk of memory * @return {@link ImageData} with info about the image * @see org.lwjgl.stb.STBImage STBImage, image decoder */ public static ImageData loadImageFromMemory(final ByteBuffer buff) { ImageData data = new ImageData(); try(MemoryStack stack = MemoryStack.stackPush()) { IntBuffer x = stack.ints(0), y = stack.ints(0), comp = stack.ints(0); data.data = org.lwjgl.stb.STBImage.stbi_load_from_memory(buff, x, y, comp, 0); if(data.data == null) throw new RuntimeException(org.lwjgl.stb.STBImage.stbi_failure_reason()); data.width = x.get(); data.height = y.get(); data.components = comp.get(); data.clear = o -> { org.lwjgl.stb.STBImage.stbi_image_free(o.data); return null; }; } return data; }
/** * Load texture from file. * * @param path File path of the texture * * @return Texture from specified file */ public static Texture loadTexture(String path) { ByteBuffer image; int width, height; try (MemoryStack stack = MemoryStack.stackPush()) { /* Prepare image buffers */ IntBuffer w = stack.mallocInt(1); IntBuffer h = stack.mallocInt(1); IntBuffer comp = stack.mallocInt(1); /* Load image */ stbi_set_flip_vertically_on_load(true); image = stbi_load(path, w, h, comp, 4); if (image == null) { throw new RuntimeException("Failed to load a texture file!" + System.lineSeparator() + stbi_failure_reason()); } /* Get width and height of image */ width = w.get(); height = h.get(); } return createTexture(width, height, image); }
/** * Sets the uniform variable at the specified location. * * @param location - Uniform location. * @param value - Value to set at the specified location. */ public void setUniform(String location, Matrix4f value) { try (MemoryStack stack = MemoryStack.stackPush()) { FloatBuffer floatBuffer = stack.mallocFloat(4*4); value.get(floatBuffer); glUniformMatrix4fv(uniformLocations.get(location), false, floatBuffer); } }
public void setUniform(String uniformName, Matrix4fc matrix) { try (MemoryStack stack = MemoryStack.stackPush()) { FloatBuffer fb = stack.mallocFloat(16); matrix.get(fb); GL20.glUniformMatrix4fv(this.findUniformLocation(uniformName), false, fb); } }
@Override public void apply(Program program, Matrix4fc value) { int location = program.findUniformLocation(this.getName()); try (MemoryStack stack = MemoryStack.stackPush()) { FloatBuffer fb = stack.mallocFloat(16); value.get(fb); GL20.glUniformMatrix4fv(location, false, fb); } }
public void setUniform(String uniformName, Matrix4f value) { try (MemoryStack stack = MemoryStack.stackPush()) { // Dump the matrix into a float buffer FloatBuffer fb = stack.mallocFloat(16); value.get(fb); glUniformMatrix4fv(uniforms.get(uniformName), false, fb); } }
public void setUniform(String uniformName, Matrix4f[] matrices) { try (MemoryStack stack = MemoryStack.stackPush()) { int length = matrices != null ? matrices.length : 0; FloatBuffer fb = stack.mallocFloat(16 * length); for (int i = 0; i < length; i++) { matrices[i].get(16 * i, fb); } glUniformMatrix4fv(uniforms.get(uniformName), false, fb); } }
public long create(Canvas canvas, VKData data) throws AWTException { MemoryStack stack = MemoryStack.stackGet(); int ptr = stack.getPointer(); JAWTDrawingSurface ds = JAWT_GetDrawingSurface(awt.GetDrawingSurface(), canvas); try { int lock = JAWT_DrawingSurface_Lock(ds.Lock(), ds); if ((lock & JAWT_LOCK_ERROR) != 0) throw new AWTException("JAWT_DrawingSurface_Lock() failed"); try { JAWTDrawingSurfaceInfo dsi = JAWT_DrawingSurface_GetDrawingSurfaceInfo(ds.GetDrawingSurfaceInfo(), ds); try { JAWTWin32DrawingSurfaceInfo dsiWin = JAWTWin32DrawingSurfaceInfo.create(dsi.platformInfo()); long hwnd = dsiWin.hwnd(); VkWin32SurfaceCreateInfoKHR sci = VkWin32SurfaceCreateInfoKHR.callocStack(stack) .sType(VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR) .hinstance(WinBase.GetModuleHandle((ByteBuffer) null)) .hwnd(hwnd); long surfaceAddr = stack.nmalloc(8, 8); int err = nvkCreateWin32SurfaceKHR(data.instance, sci.address(), 0L, surfaceAddr); long surface = MemoryUtil.memGetLong(surfaceAddr); stack.setPointer(ptr); if (err != VK_SUCCESS) { throw new AWTException("Calling vkCreateWin32SurfaceKHR failed with error: " + err); } return surface; } finally { JAWT_DrawingSurface_FreeDrawingSurfaceInfo(ds.FreeDrawingSurfaceInfo(), dsi); } } finally { JAWT_DrawingSurface_Unlock(ds.Unlock(), ds); } } finally { JAWT_FreeDrawingSurface(awt.FreeDrawingSurface(), ds); } }
@Override public List<File> openMultipleDialog(String title, String defaultPath, String[] filterPatterns, String filterDescription) { String result = null; //fix file path characters if (Utils.isWindows()) { defaultPath = defaultPath.replace("/", "\\"); } else { defaultPath = defaultPath.replace("\\", "/"); } if (filterPatterns != null && filterPatterns.length > 0) { try (MemoryStack stack = stackPush()) { PointerBuffer pointerBuffer = stack.mallocPointer(filterPatterns.length); for (String filterPattern : filterPatterns) { pointerBuffer.put(stack.UTF8(filterPattern)); } pointerBuffer.flip(); result = org.lwjgl.util.tinyfd.TinyFileDialogs.tinyfd_openFileDialog(title, defaultPath, pointerBuffer, filterDescription, true); } } else { result = org.lwjgl.util.tinyfd.TinyFileDialogs.tinyfd_openFileDialog(title, defaultPath, null, filterDescription, true); } if (result != null) { String[] paths = result.split("\\|"); ArrayList<File> returnValue = new ArrayList<>(); for (String path : paths) { returnValue.add(new File(path)); } return returnValue; } else { return null; } }
@Override public File openDialog(String title, String defaultPath, String[] filterPatterns, String filterDescription) { String result = null; //fix file path characters if (Utils.isWindows()) { defaultPath = defaultPath.replace("/", "\\"); } else { defaultPath = defaultPath.replace("\\", "/"); } if (filterPatterns != null && filterPatterns.length > 0) { try (MemoryStack stack = stackPush()) { PointerBuffer pointerBuffer = stack.mallocPointer(filterPatterns.length); for (String filterPattern : filterPatterns) { pointerBuffer.put(stack.UTF8(filterPattern)); } pointerBuffer.flip(); result = org.lwjgl.util.tinyfd.TinyFileDialogs.tinyfd_openFileDialog(title, defaultPath, pointerBuffer, filterDescription, false); } } else { result = org.lwjgl.util.tinyfd.TinyFileDialogs.tinyfd_openFileDialog(title, defaultPath, null, filterDescription, false); } if (result != null) { return new File(result); } else { return null; } }
@Override public File saveDialog(String title, String defaultPath, String[] filterPatterns, String filterDescription) { String result = null; //fix file path characters if (Utils.isWindows()) { defaultPath = defaultPath.replace("/", "\\"); } else { defaultPath = defaultPath.replace("\\", "/"); } if (filterPatterns != null && filterPatterns.length > 0) { try (MemoryStack stack = stackPush()) { PointerBuffer pointerBuffer = null; pointerBuffer = stack.mallocPointer(filterPatterns.length); for (String filterPattern : filterPatterns) { pointerBuffer.put(stack.UTF8(filterPattern)); } pointerBuffer.flip(); result = org.lwjgl.util.tinyfd.TinyFileDialogs.tinyfd_saveFileDialog(title, defaultPath, pointerBuffer, filterDescription); } } else { result = org.lwjgl.util.tinyfd.TinyFileDialogs.tinyfd_saveFileDialog(title, defaultPath, null, filterDescription); } if (result != null) { return new File(result); } else { return null; } }
@Override public void drawText(float x, float y, @NonNull String string) { try (MemoryStack stack = MemoryStack.stackPush()) { ByteBuffer utf8 = stack.UTF8(string); nvgText(ctx, x, y, utf8, 0); } }
/** * A Terrain is composed by blocks, each block is a GameItem constructed * from a HeightMap. * * @param terrainSize The number of blocks will be terrainSize * terrainSize * @param scale The scale to be applied to each terrain block * @param minY The minimum y value, before scaling, of each terrain block * @param maxY The maximum y value, before scaling, of each terrain block * @param heightMapFile * @param textureFile * @param textInc * @throws Exception */ public Terrain(int terrainSize, float scale, float minY, float maxY, String heightMapFile, String textureFile, int textInc) throws Exception { this.terrainSize = terrainSize; gameItems = new GameItem[terrainSize * terrainSize]; try (MemoryStack stack = stackPush()) { IntBuffer w = stack.mallocInt(1); IntBuffer h = stack.mallocInt(1); IntBuffer avChannels = stack.mallocInt(1); // Load image data ByteBuffer imageData = Utils.ioResourceToByteBuffer(heightMapFile, 1024); // Decode texture image into a byte buffer ByteBuffer decodedImage = stbi_load_from_memory(imageData, w, h, avChannels, 4); int width = w.get(); int height = h.get(); // The number of vertices per column and row verticesPerCol = width - 1; verticesPerRow = height - 1; heightMapMesh = new HeightMapMesh(minY, maxY, decodedImage, width, height, textureFile, textInc); boundingBoxes = new Box2D[terrainSize][terrainSize]; for (int row = 0; row < terrainSize; row++) { for (int col = 0; col < terrainSize; col++) { float xDisplacement = (col - ((float) terrainSize - 1) / (float) 2) * scale * HeightMapMesh.getXLength(); float zDisplacement = (row - ((float) terrainSize - 1) / (float) 2) * scale * HeightMapMesh.getZLength(); GameItem terrainBlock = new GameItem(heightMapMesh.getMesh()); terrainBlock.setScale(scale); terrainBlock.setPosition(xDisplacement, 0, zDisplacement); gameItems[row * terrainSize + col] = terrainBlock; boundingBoxes[row][col] = getBoundingBox(terrainBlock); } } } }
public Texture(ByteBuffer imageData) { try (MemoryStack stack = stackPush()) { IntBuffer w = stack.mallocInt(1); IntBuffer h = stack.mallocInt(1); IntBuffer avChannels = stack.mallocInt(1); // Decode texture image into a byte buffer ByteBuffer decodedImage = stbi_load_from_memory(imageData, w, h, avChannels, 4); this.width = w.get(); this.height = h.get(); // Create a new OpenGL texture this.id = glGenTextures(); // Bind the texture glBindTexture(GL_TEXTURE_2D, this.id); // Tell OpenGL how to unpack the RGBA bytes. Each component is 1 byte size glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // Upload the texture data glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, this.width, this.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, decodedImage); // Generate Mip Map glGenerateMipmap(GL_TEXTURE_2D); } }