c++3ddepth-bufferzbuffer3d-engine

Z Buffer Not Working Correctly (Not Displaying Anything)


Here is the code for my Z Buffer, it returns a black screen when I draw it.

sf::VertexArray ZOrder(sf::VertexArray verticies, std::vector<float> z_buffer) {
    std::vector<float> order;
    for (int i = 0; i < verticies.getVertexCount(); i++) {
        order.push_back(i); // {1, 2, 3, 4 ...
    }

    for (int i = 0; i < z_buffer.size(); i++) {
        for (int i = 0; i < z_buffer.size(); i++) {
            if (z_buffer[i] < z_buffer[i + 1]) {
                std::iter_swap(z_buffer.begin() + i, z_buffer.begin() + i + 1);
                std::iter_swap(order.begin() + i, order.begin() + i + 1);
            }
        }
    }

    sf::VertexArray darray(verticies.getPrimitiveType());

    for (int i = 0; i < order.size(); i++) {
        darray.append(verticies[order[i]]);
    }

    return darray;
}

// Draw Code:

dvertexa = ZOrder(dvertexa, z_buffer);

window.draw(dvertexa);

Without "dvertexa = ZOrder(dvertexa, z_buffer);" it acts like normal just without depth testing. Honestly im really tired right now so i'm probably just being an idiot but im stuck


Solution

  • FIXED:

    sf::VertexArray ZOrder(sf::VertexArray verticies, std::vector<float> z_buffer) {
        std::vector<float> order;
        for (int i = 0; i < verticies.getVertexCount(); i++) {
            order.push_back(i);
        }
    
        for (int i = 0; i < z_buffer.size(); i += 3) {
            for (int i = 0; i < z_buffer.size(); i += 3) {
                if (z_buffer[i] + z_buffer[i + 1] + z_buffer[i + 2] < z_buffer[i + 3] + z_buffer[i + 1 + 3] + z_buffer[i + 2 + 3]) {
                    std::iter_swap(z_buffer.begin() + i, z_buffer.begin() + i + 3);
                    std::iter_swap(z_buffer.begin() + i + 1, z_buffer.begin() + i + 1 + 3);
                    std::iter_swap(z_buffer.begin() + i + 2, z_buffer.begin() + i + 2 + 3);
    
                    std::iter_swap(order.begin() + i, order.begin() + i + 3);
                    std::iter_swap(order.begin() + i + 1, order.begin() + i + 1 + 3);
                    std::iter_swap(order.begin() + i + 2, order.begin() + i + 2 + 3);
                }
            }
        }
    
        sf::VertexArray darray(verticies.getPrimitiveType());
    
        for (int i = 0; i < order.size(); i++) {
            darray.append(verticies[order[i]]);
        }
    
        return darray;
    }