Java Code Examples for com.jme3.util.BufferUtils#createByteBuffer()

The following examples show how to use com.jme3.util.BufferUtils#createByteBuffer() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HeightfieldCollisionShape.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
     * Instantiate the configured shape in Bullet.
     */
    protected void createShape() {
        bbuf = BufferUtils.createByteBuffer(heightfieldData.length * 4); 
//        fbuf = bbuf.asFloatBuffer();//FloatBuffer.wrap(heightfieldData);
//        fbuf.rewind();
//        fbuf.put(heightfieldData);
        for (int i = 0; i < heightfieldData.length; i++) {
            float f = heightfieldData[i];
            bbuf.putFloat(f);
        }
//        fbuf.rewind();
        objectId = createShape(heightStickWidth, heightStickLength, bbuf, heightScale, minHeight, maxHeight, upAxis, flipQuadEdges);
        Logger.getLogger(this.getClass().getName()).log(Level.FINE, "Created Shape {0}", Long.toHexString(objectId));
        setScale(scale);
        setMargin(margin);
    }
 
Example 2
Source File: GlfwMouseInput.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static ByteBuffer transformCursorImage(final IntBuffer imageData, final int width, final int height,
                                               final int index) {

    final ByteBuffer byteBuffer = BufferUtils.createByteBuffer(width * height * 4);

    // Transform image: ARGB -> RGBA, vertical flip
    for (int y = height - 1; y >= 0; --y) {
        for (int x = 0; x < width; ++x) {
            int pixel = imageData.get(width * height * index + y * width + x);
            byteBuffer.put((byte) ((pixel >> 16) & 0xFF));  // red
            byteBuffer.put((byte) ((pixel >> 8) & 0xFF));   // green
            byteBuffer.put((byte) (pixel & 0xFF));          // blue
            byteBuffer.put((byte) ((pixel >> 24) & 0xFF));  // alpha
        }
    }

    byteBuffer.flip();

    return byteBuffer;
}
 
Example 3
Source File: JmeBatchRenderBackend.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void removeImageFromAtlas(final Image image, final int x, final int y, final int w, final int h, final int atlasTextureId) {
    // Since we clear the whole texture when we switch screens it's not really necessary to remove data from the
    // texture atlas when individual textures are removed. If necessary this can be enabled with a system property.
    if (!fillRemovedTexture) {
        return;
    }

    ByteBuffer initialData = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * 4);
    for (int i = 0; i < image.getWidth() * image.getHeight(); i++) {
        initialData.put((byte) 0xff);
        initialData.put((byte) 0x00);
        initialData.put((byte) 0x00);
        initialData.put((byte) 0xff);
    }
    initialData.rewind();
    modifyTexture(
            getTextureAtlas(atlasTextureId),
            new com.jme3.texture.Image(Format.RGBA8, image.getWidth(), image.getHeight(), initialData, ColorSpace.sRGB),
            x,
            y);
}
 
Example 4
Source File: MaterialTest.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testForcedColorSpace(){
   
    Image img=new Image(Format.RGBA8,2,2,BufferUtils.createByteBuffer(16),null,ColorSpace.sRGB);
    Image img2=new Image(Format.RGBA8,2,2,BufferUtils.createByteBuffer(16),null,ColorSpace.sRGB);
    Texture2D tx=new Texture2D(img);
    Texture2D tx2=new Texture2D(img2);

    assertTrue(tx2.getImage().getColorSpace()==ColorSpace.sRGB);
    assertTrue(tx2.getImage().getColorSpace()==ColorSpace.sRGB);

    AssetManager assetManager = TestUtil.createAssetManager();
    MaterialDef def=new MaterialDef(assetManager,"test");
    def.addMaterialParamTexture(VarType.Texture2D, "ColorMap",ColorSpace.Linear, null);
    Material mat=new Material(def);
    
    mat.setTexture("ColorMap",tx);          
    assertTrue(tx.getImage().getColorSpace()==ColorSpace.Linear);
    
    mat.setTexture("ColorMap",tx2);  
    assertTrue(tx2.getImage().getColorSpace()==ColorSpace.Linear);       

}
 
Example 5
Source File: TestImageRaster.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Image createTestImage() {
    Image testImage = new Image(Format.BGR8, 4, 3, BufferUtils.createByteBuffer(4 * 4 * 3), null, ColorSpace.Linear);
    
    ImageRaster io = ImageRaster.create(testImage);
    io.setPixel(0, 0, ColorRGBA.Black);
    io.setPixel(1, 0, ColorRGBA.Gray);
    io.setPixel(2, 0, ColorRGBA.White);
    io.setPixel(3, 0, ColorRGBA.White.mult(4)); // HDR color

    io.setPixel(0, 1, ColorRGBA.Red);
    io.setPixel(1, 1, ColorRGBA.Green);
    io.setPixel(2, 1, ColorRGBA.Blue);
    io.setPixel(3, 1, new ColorRGBA(0, 0, 0, 0));

    io.setPixel(0, 2, ColorRGBA.Yellow);
    io.setPixel(1, 2, ColorRGBA.Magenta);
    io.setPixel(2, 2, ColorRGBA.Cyan);
    io.setPixel(3, 2, new ColorRGBA(1, 1, 1, 0));
    
    return testImage;
}
 
Example 6
Source File: NativeVorbisLoader.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static AudioBuffer loadBuffer(AssetInfo assetInfo) throws IOException {
    AndroidAssetInfo aai = (AndroidAssetInfo) assetInfo;
    AssetFileDescriptor afd = null;
    NativeVorbisFile file = null;
    try {
        afd = aai.openFileDescriptor();
        int fd = afd.getParcelFileDescriptor().getFd();
        file = new NativeVorbisFile(fd, afd.getStartOffset(), afd.getLength());
        ByteBuffer data = BufferUtils.createByteBuffer(file.totalBytes);
        file.readFully(data);
        AudioBuffer ab = new AudioBuffer();
        ab.setupFormat(file.channels, 16, file.sampleRate);
        ab.updateData(data);
        return ab;
    } finally {
        if (file != null) {
            file.close();
        }
        if (afd != null) {
            afd.close();
        }
    }
}
 
Example 7
Source File: ImageFlipper.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void flipImage(Image img, int index){
    if (img.getFormat().isCompressed())
        throw new UnsupportedOperationException("Flipping compressed " +
                                                "images is unsupported.");

    int w = img.getWidth();
    int h = img.getHeight();
    int halfH = h / 2;

    // bytes per pixel
    int bpp = img.getFormat().getBitsPerPixel() / 8;
    int scanline = w * bpp;

    ByteBuffer data = img.getData(index);
    ByteBuffer temp = BufferUtils.createByteBuffer(scanline);
    
    data.rewind();
    for (int y = 0; y < halfH; y++){
        int oppY = h - y - 1;
        // read in scanline
        data.position(y * scanline);
        data.limit(data.position() + scanline);

        temp.rewind();
        temp.put(data);

    }
}
 
Example 8
Source File: HeightfieldCollisionShape.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected void createShape() {
        bbuf = BufferUtils.createByteBuffer(heightfieldData.length * 4); 
//        fbuf = bbuf.asFloatBuffer();//FloatBuffer.wrap(heightfieldData);
//        fbuf.rewind();
//        fbuf.put(heightfieldData);
        for (int i = 0; i < heightfieldData.length; i++) {
            float f = heightfieldData[i];
            bbuf.putFloat(f);
        }
//        fbuf.rewind();
        objectId = createShape(heightStickWidth, heightStickLength, bbuf, heightScale, minHeight, maxHeight, upAxis, flipQuadEdges);
        Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Created Shape {0}", Long.toHexString(objectId));
        setScale(scale);
        setMargin(margin);
    }
 
Example 9
Source File: OffScenePanel.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void setupOffBuffer() {
        image = new BufferedImage(width, height,
                BufferedImage.TYPE_4BYTE_ABGR);
        cpuBuf = BufferUtils.createByteBuffer(width * height * 4);
//        cpuArray = new byte[width * height * 4];
        offBuffer = new FrameBuffer(width, height, 0);
        //setup framebuffer to use texture
        offBuffer.setDepthBuffer(Format.Depth);
        offBuffer.setColorBuffer(Format.RGBA8);
        //set viewport to render to offscreen framebuffer
        viewPort.setOutputFrameBuffer(offBuffer);
        camera.resize(width, height, false);
    }
 
Example 10
Source File: FloatToFixed.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static VertexBuffer convertToUByte(VertexBuffer vb){
    FloatBuffer fb = (FloatBuffer) vb.getData();
    ByteBuffer bb = BufferUtils.createByteBuffer(fb.capacity());
    convertToUByte(fb, bb);

    VertexBuffer newVb = new VertexBuffer(vb.getBufferType());
    newVb.setupData(vb.getUsage(),
                    vb.getNumComponents(),
                    Format.UnsignedByte,
                    bb);
    newVb.setNormalized(true);
    return newVb;
}
 
Example 11
Source File: OpaqueComparatorTest.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Texture createTexture(String name) {
    ByteBuffer bb = BufferUtils.createByteBuffer(3);
    Image image = new Image(Format.RGB8, 1, 1, bb, ColorSpace.sRGB);
    Texture2D texture = new Texture2D(image);
    texture.setName(name);
    return texture;
}
 
Example 12
Source File: NativeMeshUtil.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static long getTriangleIndexVertexArray(Mesh mesh){
    ByteBuffer triangleIndexBase = BufferUtils.createByteBuffer(mesh.getTriangleCount() * 3 * 4);
    ByteBuffer vertexBase = BufferUtils.createByteBuffer(mesh.getVertexCount() * 3 * 4);
    int numVertices = mesh.getVertexCount();
    int vertexStride = 12; //3 verts * 4 bytes per.
    int numTriangles = mesh.getTriangleCount();
    int triangleIndexStride = 12; //3 index entries * 4 bytes each.

    IndexBuffer indices = mesh.getIndicesAsList();
    FloatBuffer vertices = mesh.getFloatBuffer(Type.Position);
    vertices.rewind();

    int verticesLength = mesh.getVertexCount() * 3;
    for (int i = 0; i < verticesLength; i++) {
        float tempFloat = vertices.get();
        vertexBase.putFloat(tempFloat);
    }

    int indicesLength = mesh.getTriangleCount() * 3;
    for (int i = 0; i < indicesLength; i++) {
        triangleIndexBase.putInt(indices.get(i));
    }
    vertices.rewind();
    vertices.clear();

    return createTriangleIndexVertexArray(triangleIndexBase, vertexBase, numTriangles, numVertices, vertexStride, triangleIndexStride);
}
 
Example 13
Source File: LwjglWindow.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Convert the {@link BufferedImage} to the {@link GLFWImage}.
 */
private GLFWImage imageToGLFWImage(BufferedImage image) {

    if (image.getType() != BufferedImage.TYPE_INT_ARGB_PRE) {

        final BufferedImage convertedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE);
        final Graphics2D graphics = convertedImage.createGraphics();

        final int targetWidth = image.getWidth();
        final int targetHeight = image.getHeight();

        graphics.drawImage(image, 0, 0, targetWidth, targetHeight, null);
        graphics.dispose();

        image = convertedImage;
    }

    final ByteBuffer buffer = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * 4);

    for (int i = 0; i < image.getHeight(); i++) {
        for (int j = 0; j < image.getWidth(); j++) {
            int colorSpace = image.getRGB(j, i);
            buffer.put((byte) ((colorSpace << 8) >> 24));
            buffer.put((byte) ((colorSpace << 16) >> 24));
            buffer.put((byte) ((colorSpace << 24) >> 24));
            buffer.put((byte) (colorSpace >> 24));
        }
    }

    buffer.flip();

    final GLFWImage result = GLFWImage.create();
    result.set(image.getWidth(), image.getHeight(), buffer);

    return result;
}
 
Example 14
Source File: BufferUtil.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static ByteBuffer read(DataInputStream is, byte[]buf) throws IOException {
    final int capacity = is.readInt();
    ByteBuffer bb = BufferUtils.createByteBuffer(capacity);
    while(bb.position() < capacity) {
        int size = capacity - bb.position();
        if (size > buf.length) {
            size = buf.length;
        }
        int i = is.read(buf, 0, size);
        bb.put(buf, 0, i);
    }
    bb.position(0);
    return bb;
}
 
Example 15
Source File: TextureHelper.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * This method returns subimage of the give image. The subimage is
 * constrained by the rectangle coordinates. The source image is unchanged.
 * 
 * @param image
 *            the image to be subimaged
 * @param minX
 *            minimum X position
 * @param minY
 *            minimum Y position
 * @param maxX
 *            maximum X position
 * @param maxY
 *            maximum Y position
 * @return a part of the given image
 */
public Image getSubimage(Image image, int minX, int minY, int maxX, int maxY) {
    if (minY > maxY) {
        throw new IllegalArgumentException("Minimum Y value is higher than maximum Y value!");
    }
    if (minX > maxX) {
        throw new IllegalArgumentException("Minimum Y value is higher than maximum Y value!");
    }
    if (image.getData().size() > 1) {
        throw new IllegalArgumentException("Only flat images are allowed for subimage operation!");
    }
    if (image.getMipMapSizes() != null) {
        LOGGER.warning("Subimaging image with mipmaps is not yet supported!");
    }

    int width = maxX - minX;
    int height = maxY - minY;
    ByteBuffer data = BufferUtils.createByteBuffer(width * height * (image.getFormat().getBitsPerPixel() >> 3));

    Image result = new Image(image.getFormat(), width, height, data);
    PixelInputOutput pixelIO = PixelIOFactory.getPixelIO(image.getFormat());
    TexturePixel pixel = new TexturePixel();

    for (int x = minX; x < maxX; ++x) {
        for (int y = minY; y < maxY; ++y) {
            pixelIO.read(image, 0, pixel, x, y);
            pixelIO.write(result, 0, pixel, x - minX, y - minY);
        }
    }
    return result;
}
 
Example 16
Source File: DDSLoader.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Reads an uncompressed RGB or RGBA image.
 *
 * @param flip Flip the image on the Y axis
 * @param totalSize Size of the image in bytes including mipmaps
 * @return ByteBuffer containing image data with mipmaps in the format specified by pixelFormat_
 * @throws java.io.IOException If an error occured while reading from InputStream
 */
public ByteBuffer readRGB3D(boolean flip, int totalSize) throws IOException {
    int redCount = count(redMask),
            blueCount = count(blueMask),
            greenCount = count(greenMask),
            alphaCount = count(alphaMask);

    if (redMask == 0x00FF0000 && greenMask == 0x0000FF00 && blueMask == 0x000000FF) {
        if (alphaMask == 0xFF000000 && bpp == 32) {
            logger.finest("Data source format: BGRA8");
        } else if (bpp == 24) {
            logger.finest("Data source format: BGR8");
        }
    }

    int sourcebytesPP = bpp / 8;
    int targetBytesPP = pixelFormat.getBitsPerPixel() / 8;

    ByteBuffer dataBuffer = BufferUtils.createByteBuffer(totalSize * depth);

    for (int k = 0; k < depth; k++) {
        //   ByteBuffer dataBuffer = BufferUtils.createByteBuffer(totalSize);
        int mipWidth = width;
        int mipHeight = height;
        int offset = k * totalSize;
        byte[] b = new byte[sourcebytesPP];
        for (int mip = 0; mip < mipMapCount; mip++) {
            for (int y = 0; y < mipHeight; y++) {
                for (int x = 0; x < mipWidth; x++) {
                    in.readFully(b);

                    int i = byte2int(b);

                    byte red = (byte) (((i & redMask) >> redCount));
                    byte green = (byte) (((i & greenMask) >> greenCount));
                    byte blue = (byte) (((i & blueMask) >> blueCount));
                    byte alpha = (byte) (((i & alphaMask) >> alphaCount));

                    if (flip) {
                        dataBuffer.position(offset + ((mipHeight - y - 1) * mipWidth + x) * targetBytesPP);
                    }
                    //else
                    //    dataBuffer.position(offset + (y * width + x) * targetBytesPP);

                    if (alphaMask == 0) {
                        dataBuffer.put(red).put(green).put(blue);
                    } else {
                        dataBuffer.put(red).put(green).put(blue).put(alpha);
                    }
                }
            }

            offset += (mipWidth * mipHeight * targetBytesPP);

            mipWidth = Math.max(mipWidth / 2, 1);
            mipHeight = Math.max(mipHeight / 2, 1);
        }
    }
    dataBuffer.rewind();
    return dataBuffer;
}
 
Example 17
Source File: TextureBlenderLuminance.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public Image blend(Image image, Image baseImage, BlenderContext blenderContext) {
    this.prepareImagesForBlending(image, baseImage);

    Format format = image.getFormat();
    PixelInputOutput basePixelIO = null;
    TexturePixel basePixel = null;
    float[] materialColor = this.materialColor;
    if (baseImage != null) {
        basePixelIO = PixelIOFactory.getPixelIO(baseImage.getFormat());
        materialColor = new float[this.materialColor.length];
        basePixel = new TexturePixel();
    }

    int width = image.getWidth();
    int height = image.getHeight();
    int depth = image.getDepth();
    if (depth == 0) {
        depth = 1;
    }
    ArrayList<ByteBuffer> dataArray = new ArrayList<ByteBuffer>(depth);

    float[] resultPixel = new float[4];
    float[] tinAndAlpha = new float[2];
    for (int dataLayerIndex = 0; dataLayerIndex < depth; ++dataLayerIndex) {
        ByteBuffer data = image.getData(dataLayerIndex);
        data.rewind();
        ByteBuffer newData = BufferUtils.createByteBuffer(width * height * 4);

        int dataIndex = 0, x = 0, y = 0;
        while (data.hasRemaining()) {
            // getting the proper material color if the base texture is applied
            if (basePixelIO != null) {
                basePixelIO.read(baseImage, dataLayerIndex, basePixel, x, y);
                basePixel.toRGBA(materialColor);
            }

            this.getTinAndAlpha(data, format, negateTexture, tinAndAlpha);
            this.blendPixel(resultPixel, materialColor, color, tinAndAlpha[0], blendFactor, blendType, blenderContext);
            newData.put(dataIndex++, (byte) (resultPixel[0] * 255.0f));
            newData.put(dataIndex++, (byte) (resultPixel[1] * 255.0f));
            newData.put(dataIndex++, (byte) (resultPixel[2] * 255.0f));
            newData.put(dataIndex++, (byte) (tinAndAlpha[1] * 255.0f));

            ++x;
            if (x >= width) {
                x = 0;
                ++y;
            }
        }
        dataArray.add(newData);
    }

    Image result = depth > 1 ? new Image(Format.RGBA8, width, height, depth, dataArray) : new Image(Format.RGBA8, width, height, dataArray.get(0));
    if (image.getMipMapSizes() != null) {
        result.setMipMapSizes(image.getMipMapSizes().clone());
    }
    return result;
}
 
Example 18
Source File: ScreenshotAppState.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void reshape(ViewPort vp, int w, int h) {
    outBuf = BufferUtils.createByteBuffer(w * h * 4);
    width = w;
    height = h;
}
 
Example 19
Source File: TriangulatedTexture.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Constructor that creates an image element from the 3D texture
 * (generated texture). It computes a flat smallest rectangle that can
 * hold a (3D) triangle defined by the given UV coordinates. Then it
 * defines the image pixels for points in 3D space that define the
 * calculated rectangle.
 * 
 * @param faceIndex
 *            the face index this image refers to
 * @param boundingBox
 *            the bounding box of the mesh
 * @param texture
 *            the texture that allows to compute a pixel value in 3D
 *            space
 * @param uv
 *            the UV coordinates of the mesh
 * @param blenderContext
 *            the blender context
 */
public TriangleTextureElement(int faceIndex, BoundingBox boundingBox, GeneratedTexture texture, Vector3f[] uv, int[] uvIndices, BlenderContext blenderContext) {
    this.faceIndex = faceIndex;

    // compute the face vertices from the UV coordinates
    float width = boundingBox.getXExtent() * 2;
    float height = boundingBox.getYExtent() * 2;
    float depth = boundingBox.getZExtent() * 2;

    Vector3f min = boundingBox.getMin(null);
    Vector3f v1 = min.add(uv[uvIndices[0]].x * width, uv[uvIndices[0]].y * height, uv[uvIndices[0]].z * depth);
    Vector3f v2 = min.add(uv[uvIndices[1]].x * width, uv[uvIndices[1]].y * height, uv[uvIndices[1]].z * depth);
    Vector3f v3 = min.add(uv[uvIndices[2]].x * width, uv[uvIndices[2]].y * height, uv[uvIndices[2]].z * depth);

    // get the rectangle envelope for the triangle
    RectangleEnvelope envelope = this.getTriangleEnvelope(v1, v2, v3);

    // create the result image
    Format imageFormat = texture.getImage().getFormat();
    int imageWidth = (int) (envelope.width * blenderContext.getBlenderKey().getGeneratedTexturePPU());
    if (imageWidth == 0) {
        imageWidth = 1;
    }
    int imageHeight = (int) (envelope.height * blenderContext.getBlenderKey().getGeneratedTexturePPU());
    if (imageHeight == 0) {
        imageHeight = 1;
    }
    ByteBuffer data = BufferUtils.createByteBuffer(imageWidth * imageHeight * (imageFormat.getBitsPerPixel() >> 3));
    image = new Image(texture.getImage().getFormat(), imageWidth, imageHeight, data);

    // computing the pixels
    PixelInputOutput pixelWriter = PixelIOFactory.getPixelIO(imageFormat);
    TexturePixel pixel = new TexturePixel();
    float[] uvs = new float[3];
    Vector3f point = new Vector3f(envelope.min);
    Vector3f vecY = new Vector3f();
    Vector3f wDelta = new Vector3f(envelope.w).multLocal(1.0f / imageWidth);
    Vector3f hDelta = new Vector3f(envelope.h).multLocal(1.0f / imageHeight);
    for (int x = 0; x < imageWidth; ++x) {
        for (int y = 0; y < imageHeight; ++y) {
            this.toTextureUV(boundingBox, point, uvs);
            texture.getPixel(pixel, uvs[0], uvs[1], uvs[2]);
            pixelWriter.write(image, 0, pixel, x, y);
            point.addLocal(hDelta);
        }

        vecY.addLocal(wDelta);
        point.set(envelope.min).addLocal(vecY);
    }

    // preparing UV coordinates for the flatted texture
    this.uv = new Vector2f[3];
    this.uv[0] = new Vector2f(FastMath.clamp(v1.subtract(envelope.min).length(), 0, Float.MAX_VALUE) / envelope.height, 0);
    Vector3f heightDropPoint = v2.subtract(envelope.w);// w is directed from the base to v2
    this.uv[1] = new Vector2f(1, heightDropPoint.subtractLocal(envelope.min).length() / envelope.height);
    this.uv[2] = new Vector2f(0, 1);
}
 
Example 20
Source File: PFMLoader.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private Image load(InputStream in, boolean needYFlip) throws IOException{
    Format format = null;

    String fmtStr = readString(in);
    if (fmtStr.equals("PF")){
        format = Format.RGB32F;
    }else if (fmtStr.equals("Pf")){
        format = Format.Luminance32F;
    }else{
        throw new IOException("File is not PFM format");
    }

    String sizeStr = readString(in);
    int spaceIdx = sizeStr.indexOf(" ");
    if (spaceIdx <= 0 || spaceIdx >= sizeStr.length() - 1)
        throw new IOException("Invalid size syntax in PFM file");

    int width = Integer.parseInt(sizeStr.substring(0,spaceIdx));
    int height = Integer.parseInt(sizeStr.substring(spaceIdx+1));

    if (width <= 0 || height <= 0)
        throw new IOException("Invalid size specified in PFM file");
    
    String scaleStr = readString(in);
    float scale = Float.parseFloat(scaleStr);
    ByteOrder order = scale < 0 ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN;
    boolean needEndienFlip = order != ByteOrder.nativeOrder();

    // make sure all unnecessary stuff gets deleted from heap
    // before allocating large amount of memory
    System.gc();

    int bytesPerPixel = format.getBitsPerPixel() / 8;
    int scanLineBytes = bytesPerPixel * width;

    ByteBuffer imageData = BufferUtils.createByteBuffer(width * height * bytesPerPixel);
    byte[] scanline = new byte[width * bytesPerPixel];

    for (int y = height - 1; y >= 0; y--) {
        if (!needYFlip)
            imageData.position(scanLineBytes * y);

        int read = 0;
        int off = 0;
        do {
            read = in.read(scanline, off, scanline.length - off);
            off += read;
        } while (read > 0);

        if (needEndienFlip){
            flipScanline(scanline);
        }

        imageData.put(scanline);
    }
    imageData.rewind();

    return new Image(format, width, height, imageData, null, ColorSpace.Linear);
}