Processing weird Null Pointer Exception (something with PGraphics) - processing

For whatever reason when I run my program I get a NullPointerException. Here is the crash log:
java.lang.NullPointerException
at processing.awt.PGraphicsJava2D.getRaster(PGraphicsJava2D.java:2727)
at processing.awt.PGraphicsJava2D.loadPixels(PGraphicsJava2D.java:2751)
at processing.opengl.PGraphicsOpenGL.initCache(PGraphicsOpenGL.java:6471)
at processing.opengl.PGraphicsOpenGL.getTexture(PGraphicsOpenGL.java:6424)
at processing.opengl.PGraphicsOpenGL$TexCache.getTexture(PGraphicsOpenGL.java:7464)
at processing.opengl.PGraphicsOpenGL.flushPolys(PGraphicsOpenGL.java:2430)
at processing.opengl.PGraphicsOpenGL.flush(PGraphicsOpenGL.java:2371)
at processing.opengl.PGraphicsOpenGL.endDraw(PGraphicsOpenGL.java:1540)
at processing.core.PApplet.handleDraw(PApplet.java:2436)
at processing.opengl.PSurfaceJOGL$DrawListener.display(PSurfaceJOGL.java:884)
at jogamp.opengl.GLDrawableHelper.displayImpl(GLDrawableHelper.java:692)
at jogamp.opengl.GLDrawableHelper.display(GLDrawableHelper.java:674)
at jogamp.opengl.GLAutoDrawableBase$2.run(GLAutoDrawableBase.java:443)
at jogamp.opengl.GLDrawableHelper.invokeGLImpl(GLDrawableHelper.java:1293)
at jogamp.opengl.GLDrawableHelper.invokeGL(GLDrawableHelper.java:1147)
at com.jogamp.newt.opengl.GLWindow.display(GLWindow.java:759)
at com.jogamp.opengl.util.AWTAnimatorImpl.display(AWTAnimatorImpl.java:81)
at com.jogamp.opengl.util.AnimatorBase.display(AnimatorBase.java:452)
at com.jogamp.opengl.util.FPSAnimator$MainTask.run(FPSAnimator.java:178)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
Could not run the sketch (Target VM failed to initialize).
For more information, read revisions.txt and Help ? Troubleshooting.
This only happens when I use P2D/P3D. JAVA2D works just fine, but I want to use P2D because otherwise the program is laggy as heck.

Please double check you're using an explicit renderer for both your sketch and the PGraphics, especially for GL renderers (e.g. P2D/P3D).
For example:
PGraphics buffer;
void setup(){
size(400,400,P3D);
buffer = createGraphics(width,height,P3D);
buffer.beginDraw();
buffer.background(0);
buffer.sphereDetail(4);
buffer.noFill();
buffer.endDraw();
}
void draw(){
float size = map(sin(frameCount * .01),-1.0,1.0,0.0,100.0);
buffer.beginDraw();
buffer.stroke(255,size * 0.5);
buffer.translate(mouseX,mouseY,0);
buffer.rotate(frameCount * 0.01,0.5,0.5,1.0);
buffer.sphere(size);
buffer.endDraw();
image(buffer,0,0);
}

Related

Why does this Processing program starting with PVector cause an error?

PVector m3()
{
return null;
}
(yup, that's the whole program) gives
Error on "PVector"
Why? It looks legal to me.
The same fail occurs with a different Processing-specific type e.g. color but not with a native type e.g. float.
Workaround:
This is because PVector is a class, not a method. I think if you want to make it return null, you have to add void in the front.
void PVector m3() {
return null;
}
Unless you want to create a PVector, you simply type it like creating a new object. Here are some examples:
PVector m3 = null;
PVector m1 = new PVector();
PVector m2 = new PVector(2, 3);
For more information on how to use PVector, I suggest you to look at the information posted on the official Processing website. Here is the link: https://processing.org/reference/PVector.html
I hope this answers your question, good luck!
Processing works in two modes:
Static mode is just a bunch of function calls. In this mode, Processing just draws a single image and then stops. Here's an example:
background(32);
ellipse(10, 20, 50, 50);
Active mode is a sketch that contains functions like setup() and draw(). In this mode, Processing continues executing code after the program starts: for example it executes draw() 60 times per second, or mousePressed() when the user presses the mouse. Here's an example:
void draw(){
background(32);
ellipse(mouseX, mouseY, 25, 25);
}
The problem with your sketch is that Processing doesn't know which mode you're trying to use. It sees that you don't have a setup() or draw() function (or any other Processing callback function), so it thinks you're trying to use static mode. But then it sees you've defined a non-callback function, so it doesn't know how to work.
Like you've discovered, the solution to your problem is to add other functions, so Processing can know what mode you want to be in. Also note that none of your code makes a ton of sense by itself, because Processing has no way of accessing it. My guess is you're planning on adding setup() and draw() functions eventually, so just add them now to get rid of your error.
For more info:
See George's answer here.
See my answer here.
See this GitHub issue where the creator of Processing explains all of the above.

How to DEBUG OpenGL a gray/black texture box?

I'm altering someone else's code. They used PNG's which are loaded via BufferedImage. I need to load a TGA instead, which is just simply a 18 byte header and BGR codes. I have the textures loaded and running, but I get a gray box instead of the texture. I don't even know how to DEBUG this.
Textures are loaded in a ByteBuffer:
final static int datasize = (WIDTH*HEIGHT*3) *2; // Double buffer size for OpenGL // not +18 no header
static ByteBuffer buffer = ByteBuffer.allocateDirect(datasize);
FileInputStream fin = new FileInputStream("/Volumes/RAMDisk/shot00021.tga");
FileChannel inc = fin.getChannel();
inc.position(18); // skip header
buffer.clear(); // prepare for read
int ret = inc.read(buffer);
fin.close();
I've followed this: [how-to-manage-memory-with-texture-in-opengl][1] ... because I am updating the texture once per frame, like video.
Called once:
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGB, width, height, 0, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, (ByteBuffer) null);
assert(GL11.GL_NO_ERROR == GL11.glGetError());
Called repeatedly:
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID);
GL11.glTexSubImage2D(GL11.GL_TEXTURE_2D, 0, 0, 0, width, height, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, byteBuffer);
assert(GL11.GL_NO_ERROR == GL11.glGetError());
return textureID;
The render code hasn't changed and is based on:
GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, this.vertexCount);
Make sure you set the texture sampling mode. Especially min filter: glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR). The default setting is mip mapped (GL_NEAREST_MIPMAP_LINEAR) so unless you upload mip maps you will get a white read result.
So either set the texture to no mip or generate them. One way to do that is to call glGenerateMipmap after the tex img call.
(see https://www.khronos.org/opengles/sdk/docs/man/xhtml/glTexParameter.xml).
It's a very common gl pitfall and something people just tend to know after getting bitten by it a few times.
There is no easy way to debug stuff like this. There are good gl debugging tools in for example xcode but they will not tell you about this case.
Debugging GPU code is always a hassle. I would bet my money on a big industry progress in this area as more companies discover the power of GPU. Until then; I'll share my two best GPU debugging friends:
1) Define a function to print OGL errors:
int printOglError(const char *file, int line)
{
/* Returns 1 if an OpenGL error occurred, 0 otherwise. */
GLenum glErr;
int retCode = 0;
glErr = glGetError();
while (glErr != GL_NO_ERROR) {
printf("glError in file %s # line %d: %s\n", file, line, gluErrorString(glErr));
retCode = 1;
glErr = glGetError();
}
return retCode;
}
#define printOpenGLError() printOglError(__FILE__, __LINE__)
And call it after your render draw calls (possible earlier errors will also show up):
GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, this.vertexCount);
printOpenGLError();
This alerts if you make some invalid operations (which might just be your case) but you usually have to find where the error occurs by trial and error.
2) Check out gDEBugger, free software with tons of GPU memory information.
[Edit]:
I would also recommend using the opensource lib DevIL - its quite competent in loading various image formats.
Thanks to Felix, by not calling glTexSubImage2D (leaving the memory valid, but uninitialized) I noticed a remnant pattern left by the default memory. This indicated that the texture is being displayed, but the load is most likely the problem.
**UPDATE:
The, problem with the code above is essentially the buffer. The buffer is 1024*1024, but it is only partially filled in by the read, leaving the limit marker of the ByteBuffer at 2359296(1024*768*3) instead of 3145728(1024*1024*3). This gives the error:
Number of remaining buffer elements is must be ... at least ...
I thought that OpenGL needed space to return data, so I doubled the size of the buffer.
The buffer size is doubled to compensate for the error.
final static int datasize = (WIDTH*HEIGHT*3) *2; // Double buffer size for OpenGL // not +18 no header
This is wrong, what is needed is the flip() function (Big THANKS to Reto Koradi for the small hint to the buffer rewind) to put the ByteBuffer in read mode. Since the buffer is only semi-full, the OpenGL buffer check gives an error. The correct thing to do is not double the buffer size; use buffer.position(buffer.capacity()) to fill the buffer before doing a flip().
final static int datasize = (WIDTH*HEIGHT*3); // not +18 no header
buffer.clear(); // prepare for read
int ret = inc.read(buffer);
fin.close();
buffer.position(buffer.capacity()); // make sure buffer is completely FILLED!
buffer.flip(); // flip buffer to read mode
To figure this out, it is helpful to hardcode the memory of the buffer to make sure the OpenGL calls are working, isolating the load problem. Then when the OpenGL calls are correct, concentrate on the loading of the buffer. As suggested by Felix K, it is good to make sure one texture has been drawn correctly before calling glTexSubImage2D repeatedly.
Some ideas which might cause the issue:
Your texture is disposed somewhere. I don't know the whole code but I guess somewhere there is a glDeleteTextures and this could cause some issues if called at the wrong time.
Are the texture width and height powers of two? If not this might be an issue depending on your hardware. Old hardware sometimes won't support non-power of two images.
The texture parameters changed between the draw calls at some other point ( Make a debug check of the parameters with glGetTexParameter ).
There could be a loading issue when loading the next image ( edit: or even the first image ). Check if the first image is displayed without loading the next images. If so it must be one of the cases above.

Android5.0 Bitmap.copyPixelsFromBuffer crash, "call to OpenGL ES API with no current context"

I want to save a view's snapshot to a file, but comes the error.
My code is as following:
View decor = ***; //
int width = decor.getWidth();
int height = decor.getHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
decor.draw(canvas);
int bytes = bitmap.getByteCount() + 8;
ByteBuffer buffer = ByteBuffer.allocate(bytes);
buffer.putInt(width);
buffer.putInt(height);
bitmap.copyPixelsToBuffer(buffer);
byte[] array = buffer.array();
but bitmap.copyPixelsToBuffer(buffer); will crash.
the error is like this:
12-09 08:36:43.107: E/libEGL(14642): call to OpenGL ES API with no current context (logged once per thread)
This error only happens on Android 5.0, are there any changes in the new platform? I know android 5.0 use a ThreadedRender to render a surface, how can I handle this problem? Thanks very much!!!
Even i am facing the same problem! It seems like in pre-lollipop version the context was leaking and is being used by default (I assume). But with lollipop it is strictly needed to create or pass the context explicitly!
hope these helps!
https://stackoverflow.com/a/27092070

Creative Gesture Camera in Processing

I'm trying to use the creative gesture camera in Processing. I started with the Intel Perceptual Computing SDK, and ran into an issue.
I want to get the hand openness, and I am running into some issues - no matter what, the hand.openness returns 0. It otherwise runs quite well...
Some Sample code I'm trying to get to work: If you open your hand it starts printing to the console, close it and it stops.
import intel.pcsdk.*;
PXCUPipeline session;
PXCMGesture.GeoNode hand = new PXCMGesture.GeoNode();
void setup()
{
session = new PXCUPipeline(this);
if(!session.Init(PXCUPipeline.GESTURE))
exit();
}
void draw()
{
background(0);
if(session.AcquireFrame(false))
{
if(session.QueryGeoNode(PXCMGesture.GeoNode.LABEL_BODY_HAND_PRIMARY|PXCMGesture.GeoNode.LABEL_OPEN, hand)) //Only when primary hand is open
{
rect(0, 0, 10, 10);
println(hand.openness + " : " + frameCount); //Openness should be from 0 to 100
}
session.ReleaseFrame();
}
}
Using the current version of Processing (2.0.3), Perceptual Computing SDK Version 7383.
Try updating the version of the SDK you're using if your project will allow it, there were quite a few bugs with getting attributes such as openess, openessState, radius, to name a few with the processing library (some attributes would even throw a null pointer exception when trying to retrieve them). I believe these have all been fixed in the recent versions, along with the inclusion of 64 bit processing support.

OutOfMemoryException in Image Resizing

We are using a .net dll (http://imageresizing.net/download) for imageresizing on runtime. It works perfectly. However, it happen after some time (between 1-7 days) that system started to raise exception in the even viewer:
Exception information:
Exception type: OutOfMemoryException
Exception message: Insufficient memory to continue the execution of the program.
And after that exception the website usually stop working with the error throwing "System.OutOfMemoryException".
And if we "recycle" the application pool in which the website is running, it clears the problem and website get back to normal immediately without any code change.
Before imagereiszing dll, we were using our custom code and same problem happen with that too. Following is the code.
private Bitmap ConvertImage(Bitmap input, int width, int height, bool arc)
{
if (input.PixelFormat == PixelFormat.Format1bppIndexed ||
input.PixelFormat == PixelFormat.Format4bppIndexed ||
input.PixelFormat == PixelFormat.Format8bppIndexed)
{
Bitmap unpackedBitmap = new Bitmap(input.Width, input.Height);
Graphics g = Graphics.FromImage(unpackedBitmap);
g.Clear(Color.White);
g.DrawImage(input, new Rectangle(0,0,input.Width, input.Height));
g.Dispose();
input = unpackedBitmap;
}
double aspectRatio = (double)input.Height / (double)input.Width;
int actualHeight = CommonMethods.GetIntValue(Math.Round(aspectRatio * width, 0));
Bitmap _imgOut;
if (actualHeight > height)
{
ResizeImage resizeImage = new ResizeImage(width, actualHeight, InterpolationMethod.Bicubic);
Bitmap _tempBitmap = resizeImage.Apply(input);
Bitmap _croppedBitmap = new Bitmap(width, height);
Graphics _crop = Graphics.FromImage(_croppedBitmap);
_crop.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
_crop.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
_crop.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
_crop.DrawImageUnscaledAndClipped(_tempBitmap, new Rectangle(0, 0, width, height));
_crop.Dispose();
_imgOut = _croppedBitmap;
}
else
{
ResizeImage resizeImage = new ResizeImage(width, height, InterpolationMethod.Bicubic);
_imgOut = resizeImage.Apply(input);
}
// Draw the arc if it has been requested
if (arc)
{
Graphics _arc = Graphics.FromImage(_imgOut);
_arc.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
_arc.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
_arc.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
_arc.DrawArc(new Pen(Color.White, 24), new Rectangle(-13, -13, 50, 50), 180, 90);
_arc.Dispose();
}
// job done
return _imgOut;
}
We are resizing image like: www.mysite.com/images/myimage.jpg?width=196&height=131
Looking forward.
Farrukh
When you encounter an OutOfMemoryException (regardless of where it occurs), it can be caused by a memory leak anywhere in the application. Having debugged dozens of these instances with WinDbg, I've never found any that ended up being due to a bug in http://imageresizing.net.
That said, there's an easy way to determine whether it is a problem with http://imageresizing.net or not; create a separate application pool and subfolder application in IIS for your images and image resizing. Install nothing there except the image resizer. Next time you encounter the error, log on to the server and find out which w3wp.exe instance is responsible for the massive memory usage.
If it's in the ImageResizer app pool, go collect your $20-$50 bug bounty from http://imageresizing.net/support. If not, you need to figure out where you're leaking stuff in your main application.
If you're working with System.Drawing anywhere else in the app, that's the first place to look. Check your code against this list of pitfalls.
If you're positive you're disposing of every System.Drawing.* instance in a using or finally clause, then read this excellent article a few times to make sure you're not failing on any of the basics, then dig in with DebugDiag and/or WinDBG (see bottom of article).

Resources