Example usage for java.nio FloatBuffer rewind

List of usage examples for java.nio FloatBuffer rewind

Introduction

In this page you can find the example usage for java.nio FloatBuffer rewind.

Prototype

public final Buffer rewind() 

Source Link

Document

Rewinds this buffer.

Usage

From source file:Main.java

public static FloatBuffer ensureLargeEnough(FloatBuffer buffer, final int required) {
    if (buffer == null || (buffer.remaining() < required)) {
        final int position = (buffer != null ? buffer.position() : 0);
        final FloatBuffer newVerts = createFloatBuffer(position + required);
        if (buffer != null) {
            buffer.rewind();
            newVerts.put(buffer);/* w  ww .  ja v a  2 s . c  o  m*/
            newVerts.position(position);
        }
        buffer = newVerts;
    }
    return buffer;
}

From source file:Main.java

public static FloatBuffer clone(final FloatBuffer buf) {
    if (buf == null) {
        return null;
    }/*w w  w . j  a  v a  2s  . c om*/
    buf.rewind();
    final FloatBuffer copy;
    if (buf.isDirect()) {
        copy = createFloatBuffer(buf.limit());
    } else {
        copy = createFloatBufferOnHeap(buf.limit());
    }
    copy.put(buf);

    return copy;
}

From source file:Main.java

private static final FloatBuffer createDebugColors(int drawMode, int size) {
    ByteBuffer bb = ByteBuffer.allocateDirect(size * 4 * 4);
    bb.order(ByteOrder.nativeOrder());
    FloatBuffer colors = bb.asFloatBuffer();
    if (drawMode == GL10.GL_TRIANGLES) {
        for (int i = 0; i < size * 4; i++) {
            colors.put(triangleColors[i % triangleColors.length]);
        }/*from ww  w. j a va2 s .  c om*/
    } else {
        for (int i = 0; i < size; i++) {
            colors.put(1f);
            colors.put(0f);
            colors.put(1f);
            colors.put(1f);
        }
    }
    colors.rewind();
    return colors;
}

From source file:org.deegree.tools.rendering.manager.buildings.PrototypeManager.java

/**
 * @param rqm//w w  w  . j a v a2  s  .co  m
 */
private RenderableQualityModel createScaledQualityModel(RenderableQualityModel rqm) {
    float minX = Float.MAX_VALUE;
    float minY = Float.MAX_VALUE;
    float minZ = Float.MAX_VALUE;
    float maxX = Float.MIN_VALUE;
    float maxY = Float.MIN_VALUE;
    float maxZ = Float.MIN_VALUE;
    ArrayList<RenderableQualityModelPart> qualityModelParts = rqm.getQualityModelParts();
    for (RenderableQualityModelPart rqmp : qualityModelParts) {
        if (rqmp != null) {
            RenderableGeometry geom = (RenderableGeometry) rqmp;
            FloatBuffer fb = geom.getCoordBuffer();
            fb.rewind();
            int position = fb.position();
            while (position < fb.capacity()) {
                float x = fb.get();
                float y = fb.get();
                float z = fb.get();

                minX = Math.min(minX, x);
                minY = Math.min(minY, y);
                minZ = Math.min(minZ, z);

                maxX = Math.max(maxX, x);
                maxY = Math.max(maxY, y);
                maxZ = Math.max(maxZ, z);
                position = fb.position();
            }
        }
    }

    double scaleX = 1d / (maxX - minX);
    double scaleY = 1d / (maxY - minY);
    double scaleZ = 1d / (maxZ - minZ);

    for (RenderableQualityModelPart rqmp : qualityModelParts) {
        if (rqmp != null) {
            RenderableGeometry geom = (RenderableGeometry) rqmp;
            FloatBuffer fb = geom.getCoordBuffer();
            fb.rewind();
            int i = 0;
            while ((i + 3) <= fb.capacity()) {
                float x = fb.get(i);
                x -= minX;
                x *= scaleX;
                fb.put(i, x);

                float y = fb.get(i + 1);
                y -= minY;
                y *= scaleY;
                fb.put(i + 1, y);

                float z = fb.get(i + 2);
                z -= minZ;
                z *= scaleZ;
                fb.put(i + 2, z);
                i += 3;
            }
        }
    }
    return rqm;

}

From source file:haven.Utils.java

public static FloatBuffer bufcp(FloatBuffer a) {
    a.rewind();
    FloatBuffer ret = mkfbuf(a.remaining());
    ret.put(a).rewind();//  w ww . j a  va 2  s. c  o  m
    return (ret);
}

From source file:haven.Utils.java

public static FloatBuffer bufcp(float[] a) {
    FloatBuffer b = mkfbuf(a.length);
    b.put(a);/*from  ww  w.ja  va  2  s  . c o  m*/
    b.rewind();
    return (b);
}

From source file:org.shaman.terrain.vegetation.ImpositorCreator.java

public TreeInfo createTree(Biome biome, String treeName, int variation, float prob) throws IOException {
    LOG.info("create tree from " + treeName);

    File folder = new File(OUTPUT_FOLDER + treeName + "_v" + variation);
    if (!folder.exists() && !folder.mkdir()) {
        LOG.log(Level.SEVERE, "unable to make directory {0}", folder);
        return null;
    }//  ww  w .j a v a 2 s.  co m

    //create tree
    Params params = new Params();
    params.prepare(13);
    params.clearParams();
    params.readFromXML(new FileInputStream(INPUT_FOLDER + treeName + ".xml"));
    params.prepare(rand.nextInt(Short.MAX_VALUE));
    TreeGenerator treeGenerator = TreeGeneratorFactory.createTreeGenerator(params);
    treeGenerator.setSeed(rand.nextInt(Short.MAX_VALUE));
    treeGenerator.setParam("Smooth", params.getParam("Smooth").toString());
    ExporterFactory.setRenderW(1024);
    ExporterFactory.setRenderH(1024);
    ExporterFactory.setExportFormat(-1);
    ExporterFactory.setOutputStemUVs(true);
    ExporterFactory.setOutputLeafUVs(true);
    Progress progress = new Progress();
    Tree treeData = treeGenerator.makeTree(progress);
    MeshGenerator meshGenerator = MeshGeneratorFactory.createMeshGenerator(/*params,*/ true);
    ArbaroToJmeExporter exporter = new ArbaroToJmeExporter(assetManager, treeData, meshGenerator);
    exporter.setBarkTexture("org/shaman/terrain/textures2/" + params.getParam("BarkTexture").getValue());
    exporter.setLeafTexture("org/shaman/terrain/textures2/" + params.getParam("LeafTexture").getValue());
    exporter.setLeafRotation(Float.parseFloat(params.getParam("LeafTextureRotation").getValue()));
    exporter.doWrite();
    Spatial tree = exporter.getSpatial();
    LOG.log(Level.INFO, "tree generated, vertices:{0}, triangles:{1}",
            new Object[] { tree.getVertexCount(), tree.getTriangleCount() });

    //save tree
    BinaryExporter binaryExporter = new BinaryExporter();
    binaryExporter.save(tree, new File(folder, "Tree.j3o"));

    //compute bounding cylinder
    List<Geometry> geometries = new ArrayList<>();
    listGeometries(tree, geometries);
    System.out.println("count of geometries: " + geometries.size());
    //compute bounding cylinder, assuming that the tree starts at the origin and grows in z-direction
    BoundingVolume oldBoundingVolume = tree.getWorldBound();
    System.out.println("original bounding volume: " + oldBoundingVolume);
    float radius = 0;
    float height = 0;
    Vector3f pos = new Vector3f();
    Vector3f pos2 = new Vector3f();
    for (Geometry geom : geometries) {
        Mesh mesh = geom.getMesh();
        Transform trafo = geom.getWorldTransform();
        VertexBuffer buffer = mesh.getBuffer(VertexBuffer.Type.Position);
        FloatBuffer fbuf = (FloatBuffer) buffer.getData();
        fbuf.rewind();
        for (int i = 0; i < buffer.getNumElements(); ++i) {
            pos.x = fbuf.get();
            pos.y = fbuf.get();
            pos.z = fbuf.get();
            pos2 = trafo.transformVector(pos, pos2);
            radius = Math.max(radius, pos2.x * pos2.x + pos2.y * pos2.y);
            height = Math.max(height, pos2.z);
        }
        fbuf.rewind();
    }
    radius = FastMath.sqrt(radius);
    System.out.println("cylinder radius: " + radius + ", height: " + height);

    //setup scene
    Node sceneNode = new Node("scene");
    sceneNode.attachChild(tree);
    DirectionalLight light = new DirectionalLight();
    Vector3f lightDir = new Vector3f(-0.1f, -0.1f, -0.1f);
    light.setDirection(lightDir.normalize());
    AmbientLight ambientLight = new AmbientLight(new ColorRGBA(0.6f, 0.6f, 0.6f, 1));
    sceneNode.addLight(ambientLight);
    sceneNode.setQueueBucket(RenderQueue.Bucket.Gui);
    for (Geometry geom : geometries) {
        geom.setQueueBucket(RenderQueue.Bucket.Gui);
        geom.getMaterial().setFloat("FadeNear", 2000);
        geom.getMaterial().setFloat("FadeFar", 3000);
    }
    //transform to match texture size
    Node sceneNode2 = new Node("scene2");
    sceneNode2.attachChild(sceneNode);
    sceneNode2.rotate(-FastMath.HALF_PI, 0, 0);
    float scale = TEXTURE_SIZE / Math.max(height, 2 * radius);
    sceneNode2.scale(scale);
    Node sceneNode3 = new Node("scene3");
    sceneNode3.attachChild(sceneNode2);
    sceneNode3.setLocalTranslation(TEXTURE_SIZE / 2, 0, 0);
    //create offscreen surface
    ByteBuffer data = BufferUtils.createByteBuffer(TEXTURE_SIZE * TEXTURE_SIZE * 4);
    BufferedImage image = new BufferedImage(TEXTURE_SIZE, TEXTURE_SIZE, BufferedImage.TYPE_4BYTE_ABGR);
    Camera camera = new Camera(TEXTURE_SIZE, TEXTURE_SIZE);
    camera.setParallelProjection(true);
    final ViewPort view = new ViewPort("Off", camera);
    view.setBackgroundColor(ColorRGBA.BlackNoAlpha);
    view.setClearFlags(true, true, true);
    final FrameBuffer buffer = new FrameBuffer(TEXTURE_SIZE, TEXTURE_SIZE, 1);
    buffer.setDepthBuffer(Image.Format.Depth);
    buffer.setColorBuffer(Image.Format.RGBA32F);
    view.setOutputFrameBuffer(buffer);
    view.attachScene(sceneNode3);
    sceneNode3.setCullHint(Spatial.CullHint.Never);
    sceneNode2.setCullHint(Spatial.CullHint.Never);
    sceneNode.setCullHint(Spatial.CullHint.Never);
    tree.setCullHint(Spatial.CullHint.Never);
    view.setEnabled(true);
    //render
    sceneNode.addLight(light);
    for (int i = 0; i < IMPOSITOR_COUNT; ++i) {
        sceneNode3.updateGeometricState();

        renderManager.renderViewPort(view, 0);
        renderer.readFrameBuffer(buffer, data);
        sceneNode.rotate(0, 0, FastMath.TWO_PI / IMPOSITOR_COUNT);
        Quaternion rot = new Quaternion();
        rot.fromAngles(0, 0, i * FastMath.TWO_PI / IMPOSITOR_COUNT);
        light.setDirection(rot.mult(lightDir).normalizeLocal());

        try {
            convertScreenShot(data, image);
            BufferedImage img = new BufferedImage(OUTPUT_TEXTURE_SIZE, OUTPUT_TEXTURE_SIZE,
                    BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D G = img.createGraphics();
            G.drawImage(image, 0, 0, OUTPUT_TEXTURE_SIZE, OUTPUT_TEXTURE_SIZE, null);
            G.dispose();
            ImageIO.write(img, "png", new File(folder, i + ".png"));
        } catch (IOException ex) {
            Logger.getLogger(ImpositorCreator.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }
    view.clearScenes();

    //create tree info
    TreeInfo info = new TreeInfo();
    info.biome = biome;
    info.name = treeName + "_v" + variation;
    info.treeSize = height;
    info.probability = prob;
    info.impostorCount = IMPOSITOR_COUNT;
    info.impostorFadeNear = 30;
    info.impostorFadeFar = 50;
    info.highResStemFadeNear = 30;
    info.highResStemFadeFar = 50;
    info.highResLeavesFadeNear = 35;
    info.highResLeavesFadeFar = 55;

    System.out.println("impostors created");
    Runtime.getRuntime().gc();
    assetManager.clearCache();

    return info;
}

From source file:GeometryByReferenceNIOBuffer.java

public void updateData(Geometry geometry) {
    int i;/*w w  w. j av a  2  s .  c o m*/
    float val;
    float val1;
    if (updateIndex == 1) { // geometry
        // Translate the geometry by a small amount in x
        vertexCount++;
        if ((vertexCount & 1) == 1)
            val = 0.2f;
        else
            val = -0.2f;

        FloatBuffer indexedCoord = (FloatBuffer) indexedFloatBufferCoord.getBuffer();
        indexedCoord.rewind();
        FloatBuffer coord = (FloatBuffer) floatBufferCoord.getBuffer();
        coord.rewind();

        if (vertexIndex == 0) {
            // Do Indexed geometry
            for (i = 0; i < indexedCoord.limit(); i += 3) {
                val1 = indexedCoord.get(i);
                indexedCoord.put(i, val1 + val);
            }
            // Do non-indexed float geometry
            for (i = 0; i < coord.limit(); i += 3) {
                val1 = coord.get(i);
                coord.put(i, val1 + val);
            }
        }
    } else if (updateIndex == 2) { // colors
        colorCount++;
        if ((colorCount & 1) == 1)
            val = 0.4f;
        else
            val = -0.4f;

        FloatBuffer indexedColors = (FloatBuffer) indexedFloatBufferColor.getBuffer();
        indexedColors.rewind();
        FloatBuffer colors = (FloatBuffer) floatBufferColor.getBuffer();
        colors.rewind();

        if (colorIndex == 0) {
            // Do Indexed geometry
            for (i = 0; i < indexedColors.limit(); i += 3) {
                indexedColors.put(i, indexedColors.get(i) + val);
            }
            // Do non-indexed float geometry
            for (i = 0; i < colors.limit(); i += 3) {
                colors.put(i, colors.get(i) + val);
            }
        }

    }

}

From source file:org.goko.tools.viewer.jogl.utils.render.basic.PolylineRenderer.java

/** (inheritDoc)
 * @see org.goko.tools.viewer.jogl.utils.render.internal.AbstractVboJoglRenderer#buildGeometry()
 *//*from   w  w w  . j  a  va 2  s.c  om*/
@Override
protected void buildGeometry() throws GkException {
    if (closed) {
        setVerticesCount(CollectionUtils.size(points) + 1);
    } else {
        setVerticesCount(CollectionUtils.size(points));
    }
    FloatBuffer vertices = FloatBuffer.allocate(getVerticesCount() * 4);
    FloatBuffer colors = FloatBuffer.allocate(getVerticesCount() * 4);

    if (CollectionUtils.isNotEmpty(points)) {
        for (Point3d p : points) {
            vertices.put(new float[] { (float) p.x, (float) p.y, (float) p.z, 1 });
            colors.put(new float[] { color.x, color.y, color.z, color.w });
        }

        if (closed) {
            Point3d p = points.get(0);
            vertices.put(new float[] { (float) p.x, (float) p.y, (float) p.z, 1 });
            colors.put(new float[] { color.x, color.y, color.z, color.w });
        }
    }
    vertices.rewind();
    colors.rewind();
    setVerticesBuffer(vertices);
    setColorsBuffer(colors);
}

From source file:com.alvermont.terraj.fracplanet.geom.VertexBufferArray.java

/**
 * Resize the buffer. This is done by reallocating a new one and copying
 * data from the old buffer to the new one. This is necessary as buffers
 * cannot be dynamically resized./*from   ww  w.  j a va 2s  .co m*/
 */
protected void resizeBuffer() {
    // we can't resize it so we have to allocate a new one and copy the data
    final int slots = (buffer.capacity() / ELEMENTSIZE);
    final int newCapacity = buffer.capacity()
            + (((slots * CAPACITY_PCT_INCREASE) / HUNDRED_PERCENT) * ELEMENTSIZE);

    final ByteBuffer newBuffer = ByteBuffer.allocateDirect(newCapacity).order(ByteOrder.nativeOrder());

    if (log.isDebugEnabled()) {
        log.debug("Resizing vertex buffer capacity to: " + newBuffer.capacity());
    }

    final FloatBuffer oldVertexBuffer = positionBuffer;
    final FloatBuffer oldNormalBuffer = normalBuffer;
    final ByteBuffer oldColourBuffer = colourBuffer;
    final ByteBuffer oldEmissiveBuffer = emissiveBuffer;

    this.buffer = newBuffer;

    sliceAndDice(newCapacity / ELEMENTSIZE);

    oldVertexBuffer.rewind();
    positionBuffer.rewind();
    positionBuffer.limit(oldVertexBuffer.limit());
    positionBuffer.put(oldVertexBuffer);

    oldNormalBuffer.rewind();
    normalBuffer.rewind();
    normalBuffer.limit(oldNormalBuffer.limit());
    normalBuffer.put(oldNormalBuffer);

    oldColourBuffer.rewind();
    colourBuffer.rewind();
    colourBuffer.limit(oldColourBuffer.limit());
    colourBuffer.put(oldColourBuffer);

    oldEmissiveBuffer.rewind();
    emissiveBuffer.rewind();
    emissiveBuffer.limit(oldEmissiveBuffer.limit());
    emissiveBuffer.put(oldEmissiveBuffer);
}