Skip to content

Commit

Permalink
Demonstrate how to use disposeCanvas override to implement a render t…
Browse files Browse the repository at this point in the history
…hread.
  • Loading branch information
OndrejSpanel authored and httpdigest committed Dec 6, 2019
1 parent 52219bf commit 4d4c75d
Showing 1 changed file with 96 additions and 0 deletions.
96 changes: 96 additions & 0 deletions test/org/lwjgl/opengl/awt/AWTThreadTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package org.lwjgl.opengl.awt;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

import static org.lwjgl.opengl.GL.*;
import static org.lwjgl.opengl.GL11.*;

import javax.swing.JFrame;

public class AWTThreadTest {
abstract static class AWTGLCanvasExplicitDispose extends AWTGLCanvas {
public AWTGLCanvasExplicitDispose(GLData data) {
super(data);
}

@Override
public void disposeCanvas() {
}

public void doDisposeCanvas() {
super.disposeCanvas();
}
}
public static void main(String[] args) {
Semaphore signalTerminate = new Semaphore(0);
Semaphore signalTerminated = new Semaphore(0);
JFrame frame = new JFrame("AWT test") {
@Override
public void dispose() {
// request the cleanup
signalTerminate.release();
try {
// wait until the thread is done with the cleanup
signalTerminated.acquire();
} catch (InterruptedException ignored) {
}
super.dispose();
}
};
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.setPreferredSize(new Dimension(600, 600));
GLData data = new GLData();
data.samples = 4;
data.swapInterval = 0;
AWTGLCanvasExplicitDispose canvas;
frame.add(canvas = new AWTGLCanvasExplicitDispose(data) {
private static final long serialVersionUID = 1L;
public void initGL() {
System.out.println("OpenGL version: " + effective.majorVersion + "." + effective.minorVersion + " (Profile: " + effective.profile + ")");
createCapabilities();
glClearColor(0.3f, 0.4f, 0.5f, 1);
}
public void paintGL() {
int w = getWidth();
int h = getHeight();
float aspect = (float) w / h;
glClear(GL_COLOR_BUFFER_BIT);
glViewport(0, 0, w, h);
glBegin(GL_QUADS);
glColor3f(0.4f, 0.6f, 0.8f);
glVertex2f(-0.75f / aspect, 0.0f);
glVertex2f(0, -0.75f);
glVertex2f(+0.75f / aspect, 0);
glVertex2f(0, +0.75f);
glEnd();
swapBuffers();
}

}, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
frame.transferFocus();

Runnable renderLoop = new Runnable() {
public void run() {
while (true) {
canvas.render();
try {
if (signalTerminate.tryAcquire(10, TimeUnit.MILLISECONDS)) {
canvas.doDisposeCanvas();
signalTerminated.release();
return;
}
} catch (InterruptedException ignored) {
}
}
}
};
Thread renderThread = new Thread(renderLoop);
renderThread.start();
}
}

0 comments on commit 4d4c75d

Please sign in to comment.