@Override public void enable() { if (pvs != null && pvs.singleOwner) pvs.tick(); if (pfs != null && pfs.singleOwner) pfs.tick(); if ((pvs != null && oldVGen != pvs.generator) || (pfs != null && oldFGen != pfs.generator)) { //TODO asserts? // asserts(); ShaderHandler np = newShaderProgram(); shaderState.deleteProgram(); shaderState = np; if (pvs != null) oldVGen = pvs.generator; if (pfs != null) oldFGen = pfs.generator; } shaderState.enable(); if (currentVBO != null) {//because we can use built in vertex attributes glBindBuffer(GL_ARRAY_BUFFER, currentVBO.bufferId); Util.checkGLError(); for (int i = 0; i < currentStructure.size(); i++) currentStructure.get(i).turnOn(); Util.checkGLError(); } }
public Simple3DWatch(int w, int h, boolean createThread) { this.w = w; this.h = h; // if (SIMPLE_AA) { simpleAA = new SimpleAntiAliasing2(); // } final Simple3DWatch THIS = this; cam.lookAt = new Vec3f(0, 0, 100); if (createThread) Threads.tick(new Threads.Tickable() { @Override public void tick(float dt) throws Exception { dt = fixedDt == null ? dt : fixedDt; commonTick(dt); THIS.tick(dt); Util.checkGLError(); if (SIMPLE_AA) simpleAA.renderFBO(); Display.update(); if (Keyboard.isKeyDown(Keyboard.KEY_ESCAPE) || Display.isCloseRequested()) exit = true; } }, 10); }
public Texture getTexture(int width, int height, int flags) { int textureID = glGenTextures(); Texture texture = new Texture(GL_TEXTURE_2D, textureID, width, height); GLCache.bindTexture(texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); GL11.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture.getWidth(), texture.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer) null); Util.checkGLError(); return texture; }
public static String gluErrorString(int error_code) { switch (error_code) { case GLU_INVALID_ENUM: return "Invalid enum (glu)"; case GLU_INVALID_VALUE: return "Invalid value (glu)"; case GLU_OUT_OF_MEMORY: return "Out of memory (glu)"; default: return Util.translateGLErrorString(error_code); } }
protected boolean checkGLError(){ try { Util.checkGLError(); } catch (OpenGLException ex){ listener.handleError("An OpenGL error has occured!", ex); } // NOTE: Always return true since this is used in an "assert" statement return true; }
/** * check GL errors. Log an error if one occurred */ public static boolean glCheckError() { try { Util.checkGLError(); return true; } catch (OpenGLException e) { logger.error("GL error [" + e.getClass().getSimpleName() + "] " + e.getMessage()); return false; } }
/** * check GL errors. Log an error if one occurred * * @return true if no error */ public static boolean glCheckError(String msg) { try { Util.checkGLError(); return true; } catch (OpenGLException e) { logger.error(msg + " GL error [" + e.getClass().getSimpleName() + "] " + e.getMessage()); Thread.dumpStack(); return false; } }
/**<br><br><b>Don't forget to remove shader after programs compilation*/ public void sendShaderToCard() { if (generator.shaderType.equals("vs")) shaderIndex = createVertexShader(stringToBuffer(generator.resultSrc)); else if (generator.shaderType.equals("fs")) shaderIndex = createFragmentShader(stringToBuffer(generator.resultSrc)); else BadException.die("unknown shader type: " + generator.shaderType); // printLogInfo(shaderIndex); Util.checkGLError(); }
public FrameBuffer initFBO(SomeTexture... tt) { // init our fbo if (textures != null) { for (SomeTexture texture : textures) texture.release(); } this.textures = al(tt); w = textures.car().width; h = textures.car().height; for (SomeTexture t : textures) if (t.width != w || t.height != h) BadException.die("all textures must be of same size"); framebufferID = glGenFramebuffers(); // create a new framebuffer depthRenderBufferID = glGenRenderbuffers(); // And finally a new depthbuffer glBindFramebuffer(GL_FRAMEBUFFER_EXT, framebufferID); // switch to the new framebuffer IntBuffer drawBufferParam; drawBufferParam = BufferUtils.createIntBuffer(tt.length); for (int i = 0; i < tt.length; i++) { drawBufferParam.put(GL_COLOR_ATTACHMENT0_EXT + i); glBindTexture(GL_TEXTURE_2D, tt[i].textureObjectId); glFramebufferTexture2D(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + i, GL_TEXTURE_2D, tt[i].textureObjectId, 0); // attach texture to the framebuffer } drawBufferParam.rewind(); GL20.glDrawBuffers(drawBufferParam); // initialize depth renderbuffer glBindRenderbuffer(GL_RENDERBUFFER_EXT, depthRenderBufferID); // bind the depth renderbuffer glRenderbufferStorage(GL_RENDERBUFFER_EXT, GL14.GL_DEPTH_COMPONENT32, tt[0].width, tt[0].height); // get the data space for it glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT,GL_DEPTH_ATTACHMENT_EXT,GL_RENDERBUFFER_EXT, depthRenderBufferID); // bind it to the renderbuffer int result = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (result != GL_FRAMEBUFFER_COMPLETE) BadException.die("Wrong FBO status: " + result); glBindFramebuffer(GL_FRAMEBUFFER_EXT, 0); // Swithch back to normal framebuffer rendering Util.checkGLError(); return this; }
int getUniformLocation(String loc_name, int programID) { byte[] bs = loc_name.getBytes(); ByteBuffer b = Utils.allocByteBuffer(bs.length+1); b.put(bs); b.put((byte)0); b.flip(); int ret = ARBShaderObjects.glGetUniformLocationARB(programID, b); if (ret == -1) { Logger.logWarning(this, " WARNING: Shader: "+programID+": could not get uniform location " + loc_name); } Util.checkGLError(); return ret; }
public Program(final String shaderName, final String[] uniformNames) { final int vsID = Program.loadShader(Program.class.getResourceAsStream("/shaders/" + shaderName + "/vertex.glsl"), GL20.GL_VERTEX_SHADER); final int fsID = Program.loadShader(Program.class.getResourceAsStream("/shaders/" + shaderName + "/fragment.glsl"), GL20.GL_FRAGMENT_SHADER); this.id = GL20.glCreateProgram(); GL20.glAttachShader(this.id, vsID); GL20.glAttachShader(this.id, fsID); GL20.glLinkProgram(this.id); Program.checkLinkage(this.id); //GL20.glValidateProgram(this.id); //Program.checkValidation(this.id); GL20.glDetachShader(this.id, vsID); GL20.glDetachShader(this.id, fsID); GL20.glDeleteShader(vsID); GL20.glDeleteShader(fsID); this.uniformLocations = new HashMap<>(uniformNames.length + 1, 1); for (final String name : uniformNames) { final int loc = GL20.glGetUniformLocation(this.id, name); this.uniformLocations.put(name, loc); System.out.println("UniformLoc for " + name + "=" + loc); } Util.checkGLError(); }
SpriteRendererDefault() { System.out.println("Shootout Implementation: OpenCL GPU animation"); final int vshID = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vshID, "#version 150\n" + "void main(void) {\n" + " gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n" + "}"); glCompileShader(vshID); if ( glGetShaderi(vshID, GL_COMPILE_STATUS) == GL_FALSE ) { System.out.println(glGetShaderInfoLog(vshID, glGetShaderi(vshID, GL_INFO_LOG_LENGTH))); throw new RuntimeException("Failed to compile vertex shader."); } createProgram(vshID); Util.checkGLError(); createKernel("kernel void animate(\n" + " const int WIDTH,\n" + " const int HEIGHT,\n" + " const float radius,\n" + " const int delta,\n" + " global float4 *balls\n" + ") {\n" + " unsigned int b = get_global_id(0);\n" + "\n" + " float4 anim = balls[b];\n" + " anim.xy = anim.xy + anim.zw * delta;\n" + " float2 animC = clamp(anim.xy, (float2)radius, (float2)(WIDTH - radius, HEIGHT - radius));\n" + " if ( anim.x != animC.x ) anim.z = -anim.z;\n" + " if ( anim.y != animC.y ) anim.w = -anim.w;\n" + "\n" + " balls[b] = (float4)(animC, anim.zw);\n" + "}"); updateBallSize(); }
/** * Create a runnable for the renderer. A renderer create a new image to draw * into. If cancel() is called, the rendering stops as soon as possible. * When finished, set the variable rendering to false. * * @return a new runnable * @see Runnable * @see #cancel() * @see #isRendering() */ @Override public final Runnable createRunnable() { // this runnable is not dedicated to be launched into a thread. // It should be launched by a SyncRenderingManager which calls the run() // method as a singular method return new Runnable() { @Override public void run() { LayerViewGLPanel vp = LwjglLayerRenderer.this.getLayerViewPanel(); try { // now, we are rendering and it's not finished yet LwjglLayerRenderer.this.setRendering(true); LwjglLayerRenderer.this.setRendered(false); // if the rendering is cancelled: stop if (LwjglLayerRenderer.this.isCancelled()) { return; } // if either the width or the height of the panel is lesser // than or equal to 0, stop if (Math.min(vp.getWidth(), vp.getHeight()) <= 1) { return; } // do the actual rendering try { LwjglLayerRenderer.this.renderHook(vp.getViewport().getEnvelopeInModelCoordinates()); GLTools.glCheckError("LWJGLLayerRenderer::renderHook()"); } catch (Throwable t) { logger.warn("LwJGL Rendering failed for layer '" + LwjglLayerRenderer.this.getLayer().getName() + "': " + t.getMessage() + " (" + t.getClass().getSimpleName() + ")"); logger.warn("GL Status is '" + Util.translateGLErrorString(GL11.glGetError()) + "'"); t.printStackTrace(); return; } } finally { // we are no more in rendering progress LwjglLayerRenderer.this.setRendering(false); } } }; }
public void removeShaderFromCard() { GL20.glDeleteShader(shaderIndex); shaderIndex = -1; Util.checkGLError(); }
public void start() throws Exception { Display.setDisplayMode(new DisplayMode(400, 400)); Display.create(); //shaders SpecularF fragmentShader = new SpecularF(); SpecularV vertexShader = new SpecularV(); GProgram shaderProgram = GProgram.initFromSrcMainJava(vertexShader, fragmentShader); //texture SomeTexture texture = new SomeTexture(readImage("jfdi.png")); //data ReflectionVBO vbo1 = new ReflectionVBO( new SpecularVi(v3(-5, -5, 0), v3(-1,-1, 1).normalized(), v2(0, 1)), new SpecularVi(v3( 5, -5, 0), v3( 1,-1, 1).normalized(), v2(1, 1)), new SpecularVi(v3( 5, 5, 0), v3( 1, 1, 1).normalized(), v2(1, 0)), new SpecularVi(v3(-5, 5, 0), v3(-1, 1, 1).normalized(), v2(0, 0))); vbo1.upload(); ShortBuffer indexBuffer = BufferUtils.createShortBuffer(6); indexBuffer.put(new short[]{0, 2, 1, 0, 3, 2}); indexBuffer.rewind(); while (!Display.isCloseRequested()) { Util.checkGLError(); glClearColor(1, 1, 1, 1); glClear(GL_COLOR_BUFFER_BIT); //prepare matrices, just raw math, no need of glMatrixMode, glMatrixPush, etc Matrix4 camModelViewMatrix = new Matrix4().setIdentity().translate(new Vec3f(0, 0, -12)); vertexShader.modelViewProjectionMatrix = camModelViewMatrix.multiply(perspective(45.0f, (float) 400 / 400, 1, 1000.0f)); vertexShader.normalMatrix = camModelViewMatrix.invert().transpose().get33(); //set uniforms and textures fragmentShader.shininess = 100; vertexShader.lightDir = new Vec3f(2, 1, 3).normalized(); shaderProgram.setInput(vbo1); texture.setSlot(0); texture.enable(0); fragmentShader.txt.set(texture); shaderProgram.enable(); glDrawRangeElements(GL_TRIANGLES, 0, indexBuffer.limit(), indexBuffer); shaderProgram.disable(); texture.disable(); Display.update(); } Display.destroy(); }
public void onTick(float dt) { Util.checkGLError(); Display.update(); checkExit(); }
@Override public String apply(Integer input) { return Util.translateGLErrorString(input); }
@SubscribeEvent public void onFrameImport(FrameImportEvent e) { CaptureFrame frame = e.frame; // check if the dimensions are still the same frame.checkWindowSize(); if (usePBO) { glBindBufferARB(PBO_TARGET, frontName); } // read pixels frame.readPixels(useFBO, usePBO); ByteBuffer buffer = e.frame.buffer; if (usePBO) { // copy back buffer glBindBufferARB(PBO_TARGET, backName); bufferPBO = glMapBufferARB(PBO_TARGET, PBO_ACCESS, buffer.capacity(), bufferPBO); bufferPBO.rewind(); buffer.rewind(); buffer.put(bufferPBO); glUnmapBufferARB(PBO_TARGET); glBindBufferARB(PBO_TARGET, 0); // If mapping threw an error -> crash immediately please Util.checkGLError(); // swap PBOs int swapName = frontName; frontName = backName; backName = swapName; } buffer.rewind(); // first frame is empty in PBO mode, don't export it if (usePBO && firstFrame) { firstFrame = false; return; } // send frame export event Minema.EVENT_BUS.post(new FrameExportEvent(e.frame, e.time, e.movieDir)); e.time.nextFrame(); }
private void initGL() throws LWJGLException { Display.setLocation((Display.getDisplayMode().getWidth() - SCREEN_WIDTH) / 2, (Display.getDisplayMode().getHeight() - SCREEN_HEIGHT) / 2); Display.setDisplayMode(new DisplayMode(SCREEN_WIDTH, SCREEN_HEIGHT)); Display.setTitle("Sprite Shootout - CL"); Display.create(); if ( !GLContext.getCapabilities().OpenGL20 ) throw new RuntimeException("OpenGL 2.0 is required for this demo."); // Setup viewport glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT, -1.0, 1.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); glClearColor(1.0f, 1.0f, 1.0f, 0.0f); // Create textures try { texSmallID = createTexture("res/ball_sm.png"); texBigID = createTexture("res/ball.png"); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } texID = texBigID; // Setup rendering state glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.0f); glColorMask(colorMask, colorMask, colorMask, false); glDepthMask(false); glDisable(GL_DEPTH_TEST); // Setup geometry Util.checkGLError(); }
private static void checkCLError(IntBuffer buffer) { org.lwjgl.opencl.Util.checkCLError(buffer.get(0)); }
@SuppressWarnings("null") public static String errorsToString(Iterable<Integer> errors) { return Joiner.on(',').join(Iterables.transform(errors, Util::translateGLErrorString)); }
public void createDisplay() { if (Display.isCreated()) return; init = true; try { Display.create(); Keyboard.create(); Mouse.create(); // Controllers.create(); registControls(); } catch (LWJGLException e) { Logger.log(Graphics.class, Logger.CRIT_ERROR, e); } // Hintergrundfarbe: Schwarz glClearColor(0f, 0f, 0f, 1f); // Setze Flags glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); // glEnable(GL_CULL_FACE); // Setze Funktionen glAlphaFunc(GL_GREATER, 0f); glDepthFunc(GL_LEQUAL); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // GL14.glBlendEquation(GL14.GL_FUNC_ADD); // glLightModeli(GL12.GL_LIGHT_MODEL_COLOR_CONTROL, // GL12.GL_SEPARATE_SPECULAR_COLOR ); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Wir brauchen eine initiale Matrix. GLCache.setMatrix(GL_PROJECTION); // glViewport(0, 0, width, height); // System.out.println("Multitexturen: " + GL11.glGetInteger(ARBMultitexture.GL_MAX_TEXTURE_UNITS_ARB)); //XXX: Definition der Kamera. In GraphicsUtil steht auch noch ein Part zur Kamera. // camera = new Camera(); // camera.fromZ = 15; // camera.fromY = 20; VIEWS.add(new View(width, height)); Util.checkGLError(); Logger.log(Graphics.class, Logger.INFO, "Setup complete."); }
/** * Ladet eine Textur zum angegebenen BufferedImage. * @param bufferedImage Image mit den Bildinformationen. * @return die geladene Textur. */ private Texture getTexture(BufferedImage bufferedImage, int flags) { int textureID = glGenTextures(); int srcWidth = bufferedImage.getWidth(); int srcHeight = bufferedImage.getHeight(); boolean alpha = bufferedImage.getColorModel().hasAlpha(); ColorSpace colorSpace = bufferedImage.getColorModel().getColorSpace(); switch(colorSpace.getType()) { case ColorSpace.TYPE_RGB: break; default: throw new IllegalArgumentException("unsupported color-format: " + getColorFormat(colorSpace)); } int colorFormat = alpha ? GL_RGBA : GL_RGB; Texture texture = new Texture(GL_TEXTURE_2D, textureID, srcWidth, srcHeight); byte[] data = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData(); convertColorFormat(data, alpha); ByteBuffer buffer = ByteBuffer.allocateDirect(data.length); buffer.order(ByteOrder.nativeOrder()); buffer.put(data, 0, data.length); buffer.flip(); GLCache.bindTexture(texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); if ((flags & ANIOTROPIC) != 0) { // Due to LWJGL buffer check, you can't use smaller sized buffers (min_size = 16 for glGetFloat()). FloatBuffer max_a = BufferUtils.createFloatBuffer(16); // Grab the maximum anisotropic filter. GL11.glGetFloat(EXTTextureFilterAnisotropic.GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, max_a); System.out.println(max_a.get(0)); // Set up the anisotropic filter. GL11.glTexParameterf(GL11.GL_TEXTURE_2D, EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT, max_a.get(0)); } if (texture.getWidth() != srcWidth || texture.getHeight() != srcHeight) { GL11.glTexImage2D(GL_TEXTURE_2D, 0, colorFormat, texture.getWidth(), texture.getHeight(), 0, colorFormat, GL_UNSIGNED_BYTE, (ByteBuffer) null); GL11.glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, srcWidth, srcHeight, colorFormat, GL_UNSIGNED_BYTE, buffer); } else { GL11.glTexImage2D(GL_TEXTURE_2D, 0, colorFormat, texture.getWidth(), texture.getHeight(), 0, colorFormat, GL_UNSIGNED_BYTE, buffer); } Util.checkGLError(); return texture; }
public boolean update(Texture texture) { synchronized(this) { if(buffer == null) { return false; } buffer.rewind(); if(initAndScaleTexture) { scaleTexture(texture); } GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture.getTextureId()); GL11.glTexSubImage2D(GL11.GL_TEXTURE_2D, 0, 0, 0, videowidth, videoheight, pixelformat, dataformat, buffer); try { Util.checkGLError(); } catch (OpenGLException e) { log.info("Error rendering video to texture. No glTexSubImage2D/OpenGL 1.2 support?"); System.err.println(e.getMessage()); } lastupdated = framecounter; return true; } }