moon-miner/ImguiWindow.py

80 lines
2.4 KiB
Python

# -*- coding: utf-8 -*-
import glfw
import OpenGL.GL as gl
import imgui as im
from imgui.integrations.glfw import GlfwRenderer
from PIL import Image
import numpy as np
def load_texture(filename):
image = Image.open(filename)
width, height = image.size
texture_id = gl.glGenTextures(1)
gl.glBindTexture(gl.GL_TEXTURE_2D, texture_id)
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR)
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR)
gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, width, height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, np.array(image.convert("RGBA")).flatten())
return texture_id
class ImguiWindow():
def impl_glfw_init(self, w, h):
window_name = "minimal Imgui/GLFW3 example"
if not glfw.init():
print("Could not initialize OpenGL context")
exit(1)
# OS X supports only forward-compatible core profiles from 3.2
glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, gl.GL_TRUE)
# Create a windowed mode window and its OpenGL context
window = glfw.create_window(
int(w), int(h), window_name, None, None
)
glfw.make_context_current(window)
if not window:
glfw.terminate()
print("Could not initialize Window")
exit(1)
return window
def __init__(self, init_fn, draw_fn, window_name, width, height):
im.create_context()
self.window = self.impl_glfw_init(width, height)
impl = GlfwRenderer(self.window)
# Load a new font
io = im.get_io()
new_font = io.fonts.add_font_from_file_ttf("/usr/share/fonts/TTF/RobotoMono-Regular.ttf", 24)
impl.refresh_font_texture()
init_fn()
while not glfw.window_should_close(self.window):
glfw.poll_events()
impl.process_inputs()
im.new_frame()
with im.font(new_font):
draw_fn()
gl.glClearColor(1., 1., 1., 1)
gl.glClear(gl.GL_COLOR_BUFFER_BIT)
im.render()
impl.render(im.get_draw_data())
glfw.swap_buffers(self.window)
impl.shutdown()
glfw.terminate()