use of org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT in project legui by SpinyOwl.
the class Example method main.
// private static String json =
// IOUtil.loadResourceAsString("com/spinyowl/legui/demo/json.json", 1024);
public static void main(String[] args) {
System.setProperty("joml.nounsafe", Boolean.TRUE.toString());
System.setProperty("java.awt.headless", Boolean.TRUE.toString());
if (!glfwInit()) {
throw new RuntimeException("Can't initialize GLFW");
}
// create glfw window
long window = glfwCreateWindow(WIDTH, HEIGHT, "Example", NULL, NULL);
// show window
glfwShowWindow(window);
// make window current on thread
glfwMakeContextCurrent(window);
GL.createCapabilities();
glfwSwapInterval(0);
// read monitors
PointerBuffer pointerBuffer = glfwGetMonitors();
int remaining = pointerBuffer.remaining();
monitors = new long[remaining];
for (int i = 0; i < remaining; i++) {
monitors[i] = pointerBuffer.get(i);
}
// create LEGUI theme and set it as default
// Themes.setDefaultTheme(new FlatColoredTheme(
// rgba(255, 255, 255, 1), // backgroundColor
// rgba(176, 190, 197, 1), // borderColor
// rgba(176, 190, 197, 1), // sliderColor
// rgba(100, 181, 246, 1), // strokeColor
// rgba(194, 219, 245, 1), // allowColor
// rgba(239, 154, 154, 1), // denyColor
// ColorConstants.transparent(), // shadowColor
// ColorConstants.darkGray(), // text color
// FontRegistry.getDefaultFont(), // font
// FlatColoredTheme.FONT_SIZE
// ));
// Firstly we need to create frame component for window.
// new Frame(WIDTH, HEIGHT);
Frame frame = new Frame(WIDTH, HEIGHT);
createGuiElements(frame, WIDTH, HEIGHT);
// also we can create frame for example just by unmarshal it
// frame = GsonMarshalUtil.unmarshal(json);
// frame.setSize(WIDTH, HEIGHT);
// We need to create legui instance one for window
// which hold all necessary library components
// or if you want some customizations you can do it by yourself.
DefaultInitializer initializer = new DefaultInitializer(window, frame);
GLFWKeyCallbackI exitOnEscCallback = (w1, key, code, action, mods) -> running = !(key == GLFW_KEY_ESCAPE && action != GLFW_RELEASE);
GLFWKeyCallbackI toggleFullscreenCallback = (w1, key, code, action, mods) -> toggleFullscreen = (key == GLFW_KEY_F && action == GLFW_RELEASE && (mods & GLFW_MOD_CONTROL) != 0);
GLFWWindowCloseCallbackI glfwWindowCloseCallbackI = w -> running = false;
// if we want to create some callbacks for system events you should create and put them to
// keeper
//
// Wrong:
// glfwSetKeyCallback(window, exitOnEscCallback);
// glfwSetWindowCloseCallback(window, glfwWindowCloseCallbackI);
//
// Right:
initializer.getCallbackKeeper().getChainKeyCallback().add(exitOnEscCallback);
initializer.getCallbackKeeper().getChainKeyCallback().add(toggleFullscreenCallback);
initializer.getCallbackKeeper().getChainWindowCloseCallback().add(glfwWindowCloseCallbackI);
// Initialization finished, so we can start render loop.
running = true;
// Everything can be done in one thread as well as in separated threads.
// Here is one-thread example.
// before render loop we need to initialize renderer
Renderer renderer = initializer.getRenderer();
Animator animator = AnimatorProvider.getAnimator();
renderer.initialize();
long time = System.currentTimeMillis();
int updCntr = 0;
context = initializer.getContext();
// context.setDebugEnabled(true);
while (running) {
// Before rendering we need to update context with window size and window framebuffer size
// {
// int[] windowWidth = {0}, windowHeight = {0};
// GLFW.glfwGetWindowSize(window, windowWidth, windowHeight);
// int[] frameBufferWidth = {0}, frameBufferHeight = {0};
// GLFW.glfwGetFramebufferSize(window, frameBufferWidth, frameBufferHeight);
// int[] xpos = {0}, ypos = {0};
// GLFW.glfwGetWindowPos(window, xpos, ypos);
// double[] mx = {0}, my = {0};
// GLFW.glfwGetCursorPos(window, mx, my);
//
// context.update(windowWidth[0], windowHeight[0],
// frameBufferWidth[0], frameBufferHeight[0],
// xpos[0], ypos[0],
// mx[0], my[0]
// );
// }
// Also we can do it in one line
context.updateGlfwWindow();
Vector2i windowSize = context.getFramebufferSize();
glClearColor(1, 1, 1, 1);
// Set viewport size
glViewport(0, 0, windowSize.x, windowSize.y);
// Clear screen
glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
// We need to relayout components.
if (gui.getGenerateEventsByLayoutManager().isChecked()) {
LayoutManager.getInstance().layout(frame, context);
} else {
LayoutManager.getInstance().layout(frame);
}
// render frame
renderer.render(frame, context);
// poll events to callbacks
glfwPollEvents();
glfwSwapBuffers(window);
animator.runAnimations();
// Now we need to handle events. Firstly we need to handle system events.
// And we need to know to which frame they should be passed.
initializer.getSystemEventProcessor().processEvents(frame, context);
// When system events are translated to GUI events we need to handle them.
// This event processor calls listeners added to ui components
initializer.getGuiEventProcessor().processEvents();
// check toggle fullscreen flag and execute.
if (toggleFullscreen) {
if (fullscreen) {
glfwSetWindowMonitor(window, NULL, 100, 100, WIDTH, HEIGHT, GLFW_DONT_CARE);
} else {
GLFWVidMode glfwVidMode = glfwGetVideoMode(monitors[0]);
glfwSetWindowMonitor(window, monitors[0], 0, 0, glfwVidMode.width(), glfwVidMode.height(), glfwVidMode.refreshRate());
}
fullscreen = !fullscreen;
toggleFullscreen = false;
}
update();
updCntr++;
if (System.currentTimeMillis() >= time + 1000) {
time += 1000;
glfwSetWindowTitle(window, "LEGUI Example. Updates per second: " + updCntr);
updCntr = 0;
}
}
// And when rendering is ended we need to destroy renderer
renderer.destroy();
glfwDestroyWindow(window);
glfwTerminate();
}
use of org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT in project runelite by runelite.
the class ModelViewer method main.
public static void main(String[] args) throws Exception {
Options options = new Options();
options.addOption(null, "npcdir", true, "npc directory");
options.addOption(null, "mapdir", true, "maps directory");
options.addOption(null, "objectdir", true, "objects directory");
options.addOption(null, "npc", true, "npc to render");
options.addOption(null, "object", true, "object to render");
options.addOption(null, "model", true, "model to render");
options.addOption(null, "map", true, "map region to render");
options.addOption(null, "kits", true, "kits to render");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
String npcdir = cmd.getOptionValue("npcdir");
String mapdir = cmd.getOptionValue("mapdir");
String objectdir = cmd.getOptionValue("objectdir");
NpcDefinition npcdef = null;
ObjectDefinition objdef = null;
List<ModelDefinition> models = new ArrayList<>();
Region region = null;
if (cmd.hasOption("model")) {
// render model
String model = cmd.getOptionValue("model");
ModelDefinition md = ModelManager.getModel(Integer.parseInt(model), null, null);
models.add(md);
}
if (cmd.hasOption("npc")) {
String npc = cmd.getOptionValue("npc");
try (FileInputStream fin = new FileInputStream(npcdir + "/" + npc + ".json")) {
npcdef = new Gson().fromJson(new InputStreamReader(fin), NpcDefinition.class);
}
for (int model : npcdef.models) {
ModelDefinition md = ModelManager.getModel(model, null, null);
models.add(md);
}
}
if (cmd.hasOption("object")) {
String obj = cmd.getOptionValue("object");
try (FileInputStream fin = new FileInputStream(objectdir + "/" + obj + ".json")) {
objdef = new Gson().fromJson(new InputStreamReader(fin), ObjectDefinition.class);
}
for (int model : objdef.getObjectModels()) {
ModelDefinition md = ModelManager.getModel(model, null, null);
models.add(md);
}
}
if (cmd.hasOption("map")) {
String map = cmd.getOptionValue("map");
String[] s = map.split(",");
int x = Integer.parseInt(s[0]), y = Integer.parseInt(s[1]);
region = new Region(x, y);
MapLoader mapLoader = new MapLoader();
LocationsLoader locationsLoader = new LocationsLoader();
try (FileInputStream fin = new FileInputStream(mapdir + "/m" + x + "_" + y + ".dat")) {
byte[] b = IOUtils.toByteArray(fin);
MapDefinition mapDef = mapLoader.load(x, y, b);
region.loadTerrain(mapDef);
}
try (FileInputStream fin = new FileInputStream(mapdir + "/l" + x + "_" + y + ".dat")) {
byte[] b = IOUtils.toByteArray(fin);
LocationsDefinition locDef = locationsLoader.load(x, y, b);
region.loadLocations(locDef);
} catch (FileNotFoundException ex) {
logger.info("No landscape file for {},{}", x, y);
}
loadUnderlays();
loadOverlays();
}
if (cmd.hasOption("kits")) {
String kits = cmd.getOptionValue("kits");
Integer[] kitIds = Arrays.stream(kits.split(",")).map(s -> Integer.parseInt(s)).toArray(Integer[]::new);
for (int kitId : kitIds) {
KitDefinition kit = KitManager.getKit(kitId);
for (int model : kit.modelIds) {
ModelDefinition md = ModelManager.getModel(model, null, null);
models.add(md);
}
}
}
Display.setDisplayMode(new DisplayMode(800, 600));
Display.setTitle("Model Viewer");
Display.setInitialBackground((float) Color.gray.getRed() / 255f, (float) Color.gray.getGreen() / 255f, (float) Color.gray.getBlue() / 255f);
Display.create();
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
double aspect = 1;
// near should be chosen as far into the scene as possible
double near = 1;
double far = 10000;
// 1 gives you a 90° field of view. It's tan(fov_angle)/2.
double fov = 1;
GL11.glFrustum(-aspect * near * fov, aspect * near * fov, -fov, fov, near, far);
GL11.glPopMatrix();
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glCullFace(GL11.GL_BACK);
GL11.glEnable(GL11.GL_CULL_FACE);
long last = 0;
Camera camera = new Camera();
while (!Display.isCloseRequested()) {
// Clear the screen and depth buffer
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
for (ModelDefinition def : models) {
short[] recolourToFind = null, recolourToReplace = null;
if (npcdef != null) {
recolourToFind = npcdef.recolorToFind;
recolourToReplace = npcdef.recolorToReplace;
}
if (objdef != null) {
recolourToFind = objdef.getRecolorToFind();
recolourToReplace = objdef.getRecolorToReplace();
}
drawModel(def, recolourToFind, recolourToReplace);
}
drawRegion(region);
Display.update();
// fps
Display.sync(50);
long delta = System.currentTimeMillis() - last;
last = System.currentTimeMillis();
camera.acceptInput(delta);
camera.apply();
}
Display.destroy();
}
use of org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT in project chunkstories by Hugobros3.
the class GLFWGameWindow method displaySplashScreen.
@SuppressWarnings("unused")
private void displaySplashScreen() throws IOException {
int texture = glGenTextures();
InputStream is = getClass().getResourceAsStream("/splash.png");
PNGDecoder decoder = new PNGDecoder(is);
int width = decoder.getWidth();
int height = decoder.getHeight();
ByteBuffer temp = ByteBuffer.allocateDirect(4 * width * height);
decoder.decode(temp, width * 4, Format.RGBA);
is.close();
// ChunkStoriesLogger.getInstance().log("decoded " + width + " by " + height + " pixels (" + name + ")", ChunkStoriesLogger.LogType.RENDERING, ChunkStoriesLogger.LogLevel.DEBUG);
temp.flip();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer) temp);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
int shaderProgramId = glCreateProgram();
int vertexShaderId = glCreateShader(GL_VERTEX_SHADER);
int fragShaderId = glCreateShader(GL_FRAGMENT_SHADER);
String vertexSource = "#version 330\n\n\nin vec3 vertexIn;\nout vec2 texCoord;\nuniform float ratio;\n\nvoid main()\n{\ngl_Position = vec4(vertexIn.x*ratio, vertexIn.y, 0.0, 1.0);\ntexCoord = vertexIn.xy*0.5+0.5;\n}";
String fragSource = "#version 330\nuniform sampler2D diffuseTexture;\n\nin vec2 texCoord;\nout vec4 fragColor;\n\nvoid main()\n{\nfragColor = texture(diffuseTexture, vec2(texCoord.x, 1.0-texCoord.y));\n}\n";
// System.out.println(vertexSource);
// System.out.println(fragSource);
glShaderSource(vertexShaderId, vertexSource);
glCompileShader(vertexShaderId);
glBindFragDataLocation(shaderProgramId, 0, "fragColor");
glShaderSource(fragShaderId, fragSource);
glCompileShader(fragShaderId);
glAttachShader(shaderProgramId, vertexShaderId);
glAttachShader(shaderProgramId, fragShaderId);
glLinkProgram(shaderProgramId);
glUseProgram(shaderProgramId);
int uniformLocation = glGetUniformLocation(shaderProgramId, "diffuseTexture");
// glUniform2f(uniformLocation, ((Vector2fc)uniformData).x(), ((Vector2fc)uniformData).y());
glUniform1i(uniformLocation, (Integer) 0);
float ratio = (float) windowHeight / windowWidth;
uniformLocation = glGetUniformLocation(shaderProgramId, "ratio");
glUniform1f(uniformLocation, ratio);
glValidateProgram(shaderProgramId);
FloatBuffer fsQuadBuffer = BufferUtils.createFloatBuffer(6 * 2);
fsQuadBuffer.put(new float[] { 1f, 1f, -1f, -1f, 1f, -1f, 1f, 1f, -1f, 1f, -1f, -1f });
fsQuadBuffer.flip();
int vertexBuffer = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, (FloatBuffer) fsQuadBuffer, GL_STATIC_DRAW);
int location = glGetAttribLocation(shaderProgramId, "vertexIn");
glEnableVertexAttribArray(location);
glVertexAttribPointer(location, 2, GL_FLOAT, false, 0, 0L);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// while(1 - Math.floor(1) == 0 && !glfwWindowShouldClose(glfwWindowHandle))
{
glClearColor(0.25f, 0.25f, 0.25f, 1f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Draw happens here
glDrawArrays(GL_TRIANGLES, 0, 6);
glfwSwapBuffers(glfwWindowHandle);
glfwPollEvents();
}
glDisable(GL_BLEND);
glDisableVertexAttribArray(location);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glDeleteBuffers(vertexBuffer);
glBindTexture(GL_TEXTURE_2D, 0);
glDeleteTextures(texture);
glUseProgram(0);
glDeleteProgram(shaderProgramId);
glDeleteShader(vertexShaderId);
glDeleteShader(fragShaderId);
glClearColor(0.0f, 0.0f, 0.0f, 1f);
}
use of org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT in project legui by SpinyOwl.
the class MultipleWindowsExample method main.
public static void main(String[] args) {
System.setProperty("joml.nounsafe", Boolean.TRUE.toString());
System.setProperty("java.awt.headless", Boolean.TRUE.toString());
if (!GLFW.glfwInit()) {
throw new RuntimeException("Can't initialize GLFW");
}
glfwSetErrorCallback(GLFWErrorCallback.createPrint(System.err));
int N = 3;
long[] windows = new long[N];
Renderer[] renderers = new NvgRenderer[N];
Context[] contexts = new Context[N];
Frame[] frames = new Frame[N];
CallbackKeeper[] keepers = new DefaultCallbackKeeper[N];
SystemEventProcessor[] systemEventProcessors = new SystemEventProcessor[N];
GLFWKeyCallbackI glfwKeyCallbackI = (w1, key, code, action, mods) -> running = !(key == GLFW_KEY_ESCAPE && action != GLFW_RELEASE);
GLFWWindowCloseCallbackI glfwWindowCloseCallbackI = w -> running = false;
for (int i = 0; i < N; i++) {
windows[i] = glfwCreateWindow(WIDTH, HEIGHT, "Multiple Windows Example " + (i + 1), NULL, NULL);
glfwShowWindow(windows[i]);
glfwMakeContextCurrent(windows[i]);
GL.createCapabilities();
glfwSwapInterval(0);
glfwSetWindowPos(windows[i], 50, 50 + (HEIGHT + 50) * i);
// Renderer which will render our ui components.
renderers[i] = new NvgRenderer();
renderers[i].initialize();
createGuiElements(frames[i] = new Frame(WIDTH, HEIGHT));
contexts[i] = new Context(windows[i]);
keepers[i] = new DefaultCallbackKeeper();
CallbackKeeper.registerCallbacks(windows[i], keepers[i]);
keepers[i].getChainKeyCallback().add(glfwKeyCallbackI);
keepers[i].getChainWindowCloseCallback().add(glfwWindowCloseCallbackI);
systemEventProcessors[i] = new SystemEventProcessorImpl();
SystemEventProcessor.addDefaultCallbacks(keepers[i], systemEventProcessors[i]);
}
running = true;
while (running) {
for (int i = 0; i < N; i++) {
glfwMakeContextCurrent(windows[i]);
GL.getCapabilities();
glfwSwapInterval(0);
contexts[i].updateGlfwWindow();
Vector2i windowSize = contexts[i].getFramebufferSize();
glClearColor(1, 1, 1, 1);
glViewport(0, 0, windowSize.x, windowSize.y);
glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
renderers[i].render(frames[i], contexts[i]);
glfwPollEvents();
glfwSwapBuffers(windows[i]);
systemEventProcessors[i].processEvents(frames[i], contexts[i]);
EventProcessorProvider.getInstance().processEvents();
// When everything done we need to relayout components.
LayoutManager.getInstance().layout(frames[i]);
}
}
for (int i = 0; i < N; i++) {
renderers[i].destroy();
glfwDestroyWindow(windows[i]);
}
glfwTerminate();
}
use of org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT in project legui by SpinyOwl.
the class SingleClassExample2 method main.
public static void main(String[] args) throws IOException {
System.setProperty("joml.nounsafe", Boolean.TRUE.toString());
System.setProperty("java.awt.headless", Boolean.TRUE.toString());
if (!GLFW.glfwInit()) {
throw new RuntimeException("Can't initialize GLFW");
}
long window = glfwCreateWindow(WIDTH, HEIGHT, "Legui", NULL, NULL);
glfwShowWindow(window);
glfwMakeContextCurrent(window);
GL.createCapabilities();
glfwSwapInterval(0);
// Firstly we need to create frame component for window.
Frame frame = new Frame(WIDTH, HEIGHT);
// we can add elements here or on the fly
// We need to create legui context which shared by renderer and event processor.
// Also we need to pass event processor for ui events such as click on component, key typing and
// etc.
Context context = new Context(window);
// We need to create callback keeper which will hold all of callbacks.
// These callbacks will be used in initialization of system event processor
// (will be added callbacks which will push system events to event queue and after that
// processed by SystemEventProcessor)
CallbackKeeper keeper = new DefaultCallbackKeeper();
// register callbacks for window. Note: all previously binded callbacks will be unbinded.
CallbackKeeper.registerCallbacks(window, keeper);
GLFWKeyCallbackI glfwKeyCallbackI = (w1, key, code, action, mods) -> running = !(key == GLFW_KEY_ESCAPE && action != GLFW_RELEASE);
GLFWWindowCloseCallbackI glfwWindowCloseCallbackI = w -> running = false;
// if we want to create some callbacks for system events you should create and put them to
// keeper
//
// Wrong:
// glfwSetKeyCallback(window, glfwKeyCallbackI);
// glfwSetWindowCloseCallback(window, glfwWindowCloseCallbackI);
//
// Right:
keeper.getChainKeyCallback().add(glfwKeyCallbackI);
keeper.getChainWindowCloseCallback().add(glfwWindowCloseCallbackI);
// Event processor for system events. System events should be processed and translated to gui
// events.
SystemEventProcessor systemEventProcessor = new SystemEventProcessorImpl();
SystemEventProcessor.addDefaultCallbacks(keeper, systemEventProcessor);
// Also we need to create renderer provider
// and create renderer which will render our ui components.
Renderer renderer = new NvgRenderer();
// Initialization finished, so we can start render loop.
running = true;
// Everything can be done in one thread as well as in separated threads.
// Here is one-thread example.
// before render loop we need to initialize renderer
renderer.initialize();
AtomicBoolean needToUpdate = new AtomicBoolean(true);
keeper.getChainKeyCallback().add((w, key, scancode, action, mods) -> {
if (key == GLFW_KEY_F1 && action == GLFW_RELEASE)
needToUpdate.set(true);
});
// createUI(frame);
while (running) {
if (needToUpdate.getAndSet(false))
createUI(frame);
// Before rendering we need to update context with window size and window framebuffer size
// {
// int[] windowWidth = {0}, windowHeight = {0};
// GLFW.glfwGetWindowSize(window, windowWidth, windowHeight);
// int[] frameBufferWidth = {0}, frameBufferHeight = {0};
// GLFW.glfwGetFramebufferSize(window, frameBufferWidth, frameBufferHeight);
// int[] xpos = {0}, ypos = {0};
// GLFW.glfwGetWindowPos(window, xpos, ypos);
// double[] mx = {0}, my = {0};
// GLFW.glfwGetCursorPos(window, mx, my);
//
// context.update(windowWidth[0], windowHeight[0],
// frameBufferWidth[0], frameBufferHeight[0],
// xpos[0], ypos[0],
// mx[0], my[0]
// );
// }
// Also we can do it in one line
context.updateGlfwWindow();
Vector2i windowSize = context.getFramebufferSize();
glClearColor(1, 1, 1, 1);
// Set viewport size
glViewport(0, 0, windowSize.x, windowSize.y);
// Clear screen
glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
// render frame
renderer.render(frame, context);
// poll events to callbacks
glfwPollEvents();
glfwSwapBuffers(window);
// Now we need to process events. Firstly we need to process system events.
systemEventProcessor.processEvents(frame, context);
// When system events are translated to GUI events we need to process them.
// This event processor calls listeners added to ui components
EventProcessorProvider.getInstance().processEvents();
// When everything done we need to relayout components.
LayoutManager.getInstance().layout(frame);
// Run animations. Should be also called cause some components use animations for updating
// state.
AnimatorProvider.getAnimator().runAnimations();
}
// And when rendering is ended we need to destroy renderer
renderer.destroy();
glfwDestroyWindow(window);
glfwTerminate();
}
Aggregations