ofFbo doesn't draw properly while depthTest enabled


#1

Hi, I’m trying to achieve a FBO trail effect with 3d shapes but I found out it doesn’t draw properly when the depth test is enabled.

Please look at my test code below. it’s pretty simple.

//--------------------------------------------------------------
void ofApp::setup(){

    ofSetBackgroundColor(100, 100, 100);
    
    /* allocate and clear fbo */
    fbo.allocate(ofGetWidth(), ofGetHeight(), GL_RGBA, 4);
    fbo.begin();
    ofClear(100,100,100,0);
    fbo.end();
}

//--------------------------------------------------------------
void ofApp::draw(){
    
    fbo.begin();
    
    /* draw a semi-transparent rectangle for a trail effect */
    ofSetColor(100,100,100,30);
    ofDrawRectangle(0, 0, ofGetWidth(), ofGetHeight());
    
    /* draw an unfilled rotating white box */
    ofNoFill();
    ofSetColor(255,255,255,255);
    ofTranslate(ofGetWidth()/2, ofGetHeight()/2);
    ofRotate(ofGetElapsedTimeMillis()*0.1, 1, 1, 1);
    ofDrawBox(200);
    
    fbo.end();
 
    /* draw fbo */
    fbo.draw(0, 0);
}

//--------------------------------------------------------------
void ofApp::keyPressed(int key){

    if (key == '1')
        ofEnableDepthTest();
    else if (key == '2')
        ofDisableDepthTest();
}

And this screenshot is before the depth test enabled.

And this one is after the depth test enabled.

As you can see, it seems alpha doesn’t seem to fade out while the depth test is enabled. Is this natural?
How can I achieve a trail effect with any 3d shape while the depth test is enabled?


#2

yes that’s normal, you are drawing the rectangle at z 0 while the box goes nearer than that so it get’s drawn and not affected by the rectangle. you can enable and disable depth testing as much as you want though so you can draw the box with depth test enabled and then disable it to draw the rectangle that clears the screen


#3

Do you mean like this?

ofEnableDepthTest();
ofDrawBox(200);
ofDisableDepthTest();

I tried it, but it only works for a few seconds then it fades out slowly in a weird manner.


#4

oh yes, on each frame you need to clear the depth buffer otherwise you are accumulating on the depth buffer too and the depth test fails cause if finds the previous geometry. you can clear the depth bufffer using:

fbo.begin();
glClear(GL_DEPTH_BUFFER_BIT);
 /* draw a semi-transparent rectangle for a trail effect */
ofSetColor(100,100,100,30);
ofDrawRectangle(0, 0, ofGetWidth(), ofGetHeight());
...