javaopengllwjgljava-2d

How can I fill a java Shape in OpenGL


Well, lets say I have the Shape of an O and I want to render it. enter image description here

Now my current rendering code is this:

public void fill(Shape shape, float xOffset, float yOffset) {
        AffineTransform transform = new AffineTransform();
        transform.translate(xOffset, yOffset);
        PathIterator pi = shape.getPathIterator(transform, 1);
        int winding = pi.getWindingRule();
        ShapeRenderer r = getInstance();
        float[] coords = new float[6];
        boolean drawing = false;
        while (!pi.isDone()) {
            int segment = pi.currentSegment(coords);
            switch (segment) {
            case PathIterator.SEG_CLOSE:
                if (drawing) {
                    r.endPoly();
                }
                break;
            case PathIterator.SEG_LINETO:
                r.lineTo(coords);
                break;
            case PathIterator.SEG_MOVETO:
                if (drawing) {
                    r.endPoly();
                }
                drawing = true;
                r.beginPoly(winding);
                r.moveTo(coords);
                break;
            default:
                throw new IllegalArgumentException("Unexpected value: " + segment);
            }
            pi.next();
        }
    }

ShapeRenderer:

private final Deque<Queue<Float>> vertices = new ConcurrentLinkedDeque<>();

    @Override
    public void beginPoly(int windingRule) {
    }

    @Override
    public void endPoly() {
        Queue<Float> q;
        GL11.glBegin(GL11.GL_LINE_LOOP);
        while ((q = vertices.poll()) != null) {
            Float x, y;
            while ((x = q.poll()) != null && (y = q.poll()) != null) {
                GL11.glVertex2f(x, y);
            }
        }
        GL11.glEnd();
    }

    @Override
    public void moveTo(float[] vertex) {
        Queue<Float> q = new ConcurrentLinkedQueue<>();
        vertices.offer(q);
        lineTo(vertex);
    }

    @Override
    public void lineTo(float[] vertex) {
        Queue<Float> q = vertices.peekLast();
        q.offer(vertex[0]);
        q.offer(vertex[1]);
    }

So lets say I want to fill that Shape, just like java awt does, successfully... How would I do that? (Already tried using GL_POLYGON, but it just fills the entire O and I have a filled circle, not an O. Also tried using parts of jogamp glu but it just rendered nothing, no clue why)


Solution

  • Already tried using GL_POLYGON, but it just fills the entire O and I have a filled circle, "

    Yes of course. GL_POLYGON is for Convex shapes and fills the entire area enclosed by the polygon.

    You have 2 options:

    1. Use GL_POLYGON twice to draw a white shape and then a red shape inside the white shape.

    2. Use GL_TRIANGLE_STRIP and form a shape that just draws the outline. The primitive can be formed by alternately specifying a point on the outer outline and on the inner outline.