Java Code Examples for java.nio.ShortBuffer#rewind()

The following examples show how to use java.nio.ShortBuffer#rewind() . 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: BufferUtils.java    From aion-germany with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a new ShortBuffer with the same contents as the given ShortBuffer. The new ShortBuffer is seperate from the old one and changes are not reflected across. If you want to reflect changes,
 * consider using Buffer.duplicate().
 *
 * @param buf
 *            the ShortBuffer to copy
 * @return the copy
 */
public static ShortBuffer clone(ShortBuffer buf) {
	if (buf == null) {
		return null;
	}
	buf.rewind();

	ShortBuffer copy;
	if (buf.isDirect()) {
		copy = createShortBuffer(buf.limit());
	}
	else {
		copy = ShortBuffer.allocate(buf.limit());
	}
	copy.put(buf);

	return copy;
}
 
Example 2
Source File: ImageIndexTexture.java    From settlers-remake with MIT License 6 votes vote down vote up
private void loadTexture(GLDrawContext gl) {
	try {
		final DataInputStream in = new DataInputStream(new BufferedInputStream(file));
		int i = in.available() / 2;
		final int height = nextLowerPOT(Math.sqrt(i));
		final int width = nextLowerPOT(i / height);

		// TODO: Use better buffering.
		final ShortBuffer data = ByteBuffer.allocateDirect(width * height * 2).order(ByteOrder.nativeOrder()).asShortBuffer();
		while (data.hasRemaining()) {
			data.put(in.readShort());
		}
		data.rewind();
		textureIndex = gl.generateTexture(width, height, data, name);
	} catch (final IOException e) {
		e.printStackTrace();
		textureIndex = null;
	}
}
 
Example 3
Source File: NativeCursors.java    From Monocle with GNU General Public License v2.0 6 votes vote down vote up
private static void colorKeyCursor16(byte[] source, ShortBuffer destBuffer,
                                     int transparentPixel) {

    IntBuffer sourceBuffer = ByteBuffer.wrap(source).asIntBuffer();
    while (sourceBuffer.position() < sourceBuffer.limit()) {
        int i = sourceBuffer.get();
        if ((i & 0xff) == 0) {
            destBuffer.put((short) transparentPixel);
        } else {
            int pixel = ((i >> 8) & 0xf800)
                    | ((i >> 5) & 0x7e0)
                    | ( (i >> 3) & 0x1f);
            destBuffer.put((short) pixel);
        }
    }
    destBuffer.rewind();
}
 
Example 4
Source File: Sky.java    From tribaltrouble with GNU General Public License v2.0 6 votes vote down vote up
private final ShortVBO[] makeSkyStripIndices() {
	ShortVBO[] strip_indices = new ShortVBO[subdiv_height - 2];
	for (int i = 0; i < strip_indices.length; i++) {
		int size = subdiv_axis*2 + 2;
		ShortBuffer temp = BufferUtils.createShortBuffer(size);
		for (int j = 0; j < subdiv_axis; j++) {
			temp.put(j*2, (short)(i*subdiv_axis + j));
			temp.put(j*2 + 1, (short)((i + 1)*subdiv_axis + j));
		}
		temp.put(subdiv_axis*2, (short)(i*subdiv_axis));
		temp.put(subdiv_axis*2 + 1, (short)((i + 1)*subdiv_axis));
		strip_indices[i] = new ShortVBO(ARBBufferObject.GL_STATIC_DRAW_ARB, size);
		temp.rewind();
		strip_indices[i].put(temp);
	}
	return strip_indices;
}
 
Example 5
Source File: ProvidedImage.java    From settlers-remake with MIT License 5 votes vote down vote up
public ShortBuffer getData() {
	ShortBuffer data = ShortBuffer.allocate(image.getWidth() * image.getHeight());
	for (int y = 0; y < image.getHeight(); y++) {
		for (int x = 0; x < image.getWidth(); x++) {
			Color color = new Color(image.getRGB(x, y));
			data.put(color.toShortColor(1));
		}
	}
	data.rewind();
	return data;
}
 
Example 6
Source File: AudioChannelWithSP.java    From Mp4Composer-android with MIT License 5 votes vote down vote up
private void writeToSonicSteam(final ShortBuffer data) {

        short[] temBuff = new short[data.capacity()];
        data.get(temBuff);
        data.rewind();
        stream.writeShortToStream(temBuff, temBuff.length / outputChannelCount);
    }
 
Example 7
Source File: BinaryOutputCapsule.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void write(ShortBuffer value) throws IOException {
    if (value == null) {
        write(NULL_OBJECT);
        return;
    }
    value.rewind();
    int length = value.limit();
    write(length);
    for (int x = 0; x < length; x++) {
        writeForBuffer(value.get());
    }
    value.rewind();
}
 
Example 8
Source File: BinaryOutputCapsule.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected void write(ShortBuffer value) throws IOException {
    if (value == null) {
        write(NULL_OBJECT);
        return;
    }
    value.rewind();
    int length = value.limit();
    write(length);
    for (int x = 0; x < length; x++) {
        writeForBuffer(value.get());
    }
    value.rewind();
}
 
Example 9
Source File: DOMOutputCapsule.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void write(ShortBuffer value, String name, ShortBuffer defVal) throws IOException {
    if (value == null) {
        return;
    }
    if (value.equals(defVal)) {
        return;
    }

    Element el = appendElement(name);
    el.setAttribute("size", String.valueOf(value.limit()));
    StringBuilder buf = new StringBuilder();
    int pos = value.position();
    value.rewind();
    int ctr = 0;
    while (value.hasRemaining()) {
        ctr++;
        buf.append(value.get());
        buf.append(" ");
    }
    if (ctr != value.limit()) {
        throw new IOException("'" + name
            + "' buffer contention resulted in write data consistency.  "
            + ctr + " values written when should have written "
            + value.limit());
    }
    
    if (buf.length() > 0) {
        //remove last space
        buf.setLength(buf.length() - 1);
    }
    
    value.position(pos);
    el.setAttribute(dataAttributeName, buf.toString());
    currentElement = (Element) el.getParentNode();
}
 
Example 10
Source File: TestUtils.java    From succinct with Apache License 2.0 5 votes vote down vote up
public static FSDataInputStream getStream(ShortBuffer buf) throws IOException {
  File tmpDir = Files.createTempDir();
  Path filePath = new Path(tmpDir.getAbsolutePath() + "/testOut");
  FileSystem fs = FileSystem.get(filePath.toUri(), new Configuration());
  FSDataOutputStream fOut = fs.create(filePath);
  buf.rewind();
  while (buf.hasRemaining()) {
    fOut.writeShort(buf.get());
  }
  fOut.close();
  buf.rewind();
  return fs.open(filePath);
}
 
Example 11
Source File: PcmChunkDecoder.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public void decode(byte[] encoded, ShortBuffer buffer) {
  buffer.clear();

  encodedAsByte.clear();
  encodedAsByte.put(encoded);

  encodedAsShort.clear();
  encodedAsShort.limit(encodedAsByte.position() / 2);

  buffer.put(encodedAsShort);
  buffer.rewind();
}
 
Example 12
Source File: BufferUtils.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static ShortBuffer ensureLargeEnough(ShortBuffer buffer, int required) {
    if (buffer == null || (buffer.remaining() < required)) {
        int position = (buffer != null ? buffer.position() : 0);
        ShortBuffer newVerts = createShortBuffer(position + required);
        if (buffer != null) {
            buffer.rewind();
            newVerts.put(buffer);
            newVerts.position(position);
        }
        buffer = newVerts;
    }
    return buffer;
}
 
Example 13
Source File: BitmapPixels.java    From codeexamples-android with Eclipse Public License 1.0 5 votes vote down vote up
private static ShortBuffer makeBuffer(short[] src, int n) {
    ShortBuffer dst = ShortBuffer.allocate(n*n);
    for (int i = 0; i < n; i++) {
        dst.put(src);
    }
    dst.rewind();
    return dst;
}
 
Example 14
Source File: OBAudioBufferPlayer.java    From GLEXP-Team-onebillion with Apache License 2.0 5 votes vote down vote up
void writeOutputBufferToBuffers(ByteBuffer outputBuffer,long prestimeus,long frameNo)
{
    ShortBuffer ib = outputBuffer.asShortBuffer();
    int noInts = ib.limit();
    if (noInts == 0)
        return;
    //MainActivity.log(String.format("Writing buffers for f %d",frameNo));
    ib.rewind();
    long bufferDurationus = 1024 * 1000000 / sampleRate;
    long framesInBuffer = 1024;
    int i = 0;
    while (noInts > 0)
    {
        int wamt = Math.min(noInts,1024);
        int idx = nextAvailableWriteBuffer();
        SimpleBuffer sb = buffers[idx];
        sb.startWriting();
        sb.writeData(ib,wamt);
        sb.sequence = bufferSequenceNo++;
        sb.presentationTimeus = prestimeus + (long)(i * bufferDurationus);
        sb.frameNo = frameNo + i * framesInBuffer;
        //MainActivity.log(String.format("  writing to buffer %d, us - %d",idx,sb.frameNo));
        sb.stopWriting();
        noInts -= wamt;
        nextBufIdx = (nextBufIdx + 1) % NO_BUFFERS;
        i++;
    }
}
 
Example 15
Source File: BufferUtils.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
public static ShortBuffer ensureLargeEnough(ShortBuffer buffer, int required) {
	if (buffer == null || (buffer.remaining() < required)) {
		int position = (buffer != null ? buffer.position() : 0);
		ShortBuffer newVerts = createShortBuffer(position + required);
		if (buffer != null) {
			buffer.rewind();
			newVerts.put(buffer);
			newVerts.position(position);
		}
		buffer = newVerts;
	}
	return buffer;
}
 
Example 16
Source File: BufferUtils.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create a new ShortBuffer of an appropriate size to hold the specified number of shorts only if the given buffer if not already the right size.
 *
 * @param buf
 *            the buffer to first check and rewind
 * @param size
 *            number of shorts that need to be held by the newly created buffer
 * @return the requested new ShortBuffer
 */
public static ShortBuffer createShortBuffer(ShortBuffer buf, int size) {
	if (buf != null && buf.limit() == size) {
		buf.rewind();
		return buf;
	}

	buf = createShortBuffer(size);
	return buf;
}
 
Example 17
Source File: GLTFMeshExporter.java    From gdx-gltf with Apache License 2.0 5 votes vote down vote up
GLTFPrimitive exportMeshPart(MeshPart meshPart) {
	Mesh mesh = meshPart.mesh;
	GLTFPrimitive primitive = new GLTFPrimitive();
	primitive.attributes = new ObjectMap<String, Integer>();
	primitive.mode = mapPrimitiveMode(meshPart.primitiveType);
	
	GLTFPrimitive layout = layouts.get(mesh);
	if(layout != null){
		copyLayout(primitive, layout);
	}else{
		layouts.put(mesh, primitive);
		exportMesh(primitive, mesh);
	}
	
	// mesh may not have indices
	if(mesh.getNumIndices() > 0)
	{
		ShortBuffer outBuffer = base.binManager.beginShorts(meshPart.size);
		ShortBuffer inBuffer = mesh.getIndicesBuffer();
		if(meshPart.offset == 0 && meshPart.size == mesh.getNumIndices()){
			outBuffer.put(mesh.getIndicesBuffer());
		}else{
			short[] localIndices = new short[meshPart.size];
			inBuffer.position(meshPart.offset);
			inBuffer.get(localIndices);
			outBuffer.put(localIndices);
		}
		inBuffer.rewind();
		
		GLTFAccessor accessor = base.obtainAccessor();
		accessor.type = GLTFTypes.TYPE_SCALAR;
		accessor.componentType = GLTFTypes.C_SHORT;
		accessor.count = meshPart.size;
		accessor.bufferView = base.binManager.end();
		
		primitive.indices = base.root.accessors.size-1;
	}
	
	return primitive;
}
 
Example 18
Source File: Utils.java    From tribaltrouble with GNU General Public License v2.0 4 votes vote down vote up
public final static ShortBuffer toBuffer(short[] shorts) {
	ShortBuffer buffer = BufferUtils.createShortBuffer(shorts.length);
	buffer.put(shorts);
	buffer.rewind();
	return buffer;
}
 
Example 19
Source File: TestBaseAnimSerialization.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private Mesh createMesh() {
    Cylinder c = new Cylinder(30, 16, 0.1f, 1, true);

    ShortBuffer jointIndex = (ShortBuffer) VertexBuffer.createBuffer(VertexBuffer.Format.UnsignedShort, 4, c.getVertexCount());
    jointIndex.rewind();
    c.setMaxNumWeights(1);
    FloatBuffer jointWeight = (FloatBuffer) VertexBuffer.createBuffer(VertexBuffer.Format.Float, 4, c.getVertexCount());
    jointWeight.rewind();
    VertexBuffer vb = c.getBuffer(VertexBuffer.Type.Position);
    FloatBuffer fvb = (FloatBuffer) vb.getData();
    fvb.rewind();
    for (int i = 0; i < c.getVertexCount(); i++) {
        fvb.get();
        fvb.get();
        float z = fvb.get();
        int index = 0;
        if (z > 0) {
            index = 0;
        } else if (z > -0.2) {
            index = 1;
        } else {
            index = 2;
        }
        jointIndex.put((short) index).put((short) 0).put((short) 0).put((short) 0);
        jointWeight.put(1f).put(0f).put(0f).put(0f);

    }
    c.setBuffer(VertexBuffer.Type.BoneIndex, 4, jointIndex);
    c.setBuffer(VertexBuffer.Type.BoneWeight, 4, jointWeight);

    c.updateCounts();
    c.updateBound();

    VertexBuffer weightsHW = new VertexBuffer(VertexBuffer.Type.HWBoneWeight);
    VertexBuffer indicesHW = new VertexBuffer(VertexBuffer.Type.HWBoneIndex);

    indicesHW.setUsage(VertexBuffer.Usage.CpuOnly);
    weightsHW.setUsage(VertexBuffer.Usage.CpuOnly);
    c.setBuffer(weightsHW);
    c.setBuffer(indicesHW);
    c.generateBindPose();

    c.prepareForAnim(false);

    return c;
}
 
Example 20
Source File: PMDNode.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void softwareSkinUpdate(PMDMesh mesh){
        int maxWeightsPerVert = 2;//mesh.getMaxNumWeights();
        int fourMinusMaxWeights = 4 - maxWeightsPerVert;
//        Matrix4f[] offsetMatrices = mesh.getBoneMatrixArray();

        // NOTE: This code assumes the vertex buffer is in bind pose
        // resetToBind() has been called this frame
        resetToBind(mesh);
        VertexBuffer vb = mesh.getBuffer(VertexBuffer.Type.Position);
        FloatBuffer fvb = (FloatBuffer) vb.getData();
        fvb.rewind();

        VertexBuffer nb = mesh.getBuffer(VertexBuffer.Type.Normal);
        FloatBuffer fnb = (FloatBuffer) nb.getData();
        fnb.rewind();
        
        FloatBuffer fvb2 = (FloatBuffer)mesh.getVbBackup().getData();
        fvb2.rewind();
        FloatBuffer fnb2 = (FloatBuffer)mesh.getNbBackup().getData();
        fnb2.rewind();
        
        // get boneIndexes and weights for mesh
        ShortBuffer ib = (ShortBuffer) mesh.getBuffer(VertexBuffer.Type.BoneIndex).getData();
        FloatBuffer wb = (FloatBuffer) mesh.getBuffer(VertexBuffer.Type.BoneWeight).getData();

        ib.rewind();
        wb.rewind();

//        float[] weights = wb.array();
//        short[] indices = ib.array();
        int idxWeights = 0;

        TempVars vars = TempVars.get();
        float[] posBuf = vars.skinPositions;
        float[] normBuf = vars.skinNormals;

        int iterations = (int) FastMath.ceil(fvb.capacity() / ((float)posBuf.length));
        int bufLength = posBuf.length * 3;
        for (int i = iterations-1; i >= 0; i--){
            // read next set of positions and normals from native buffer
            bufLength = Math.min(posBuf.length, fvb.remaining());
            fvb2.get(posBuf, 0, bufLength);
            fnb2.get(normBuf, 0, bufLength);
            int verts = bufLength / 3;
            int idxPositions = 0;

            // iterate vertices and apply skinning transform for each effecting bone
            for (int vert = verts - 1; vert >= 0; vert--){
                float nmx = normBuf[idxPositions];
                float vtx = posBuf[idxPositions++];
                float nmy = normBuf[idxPositions];
                float vty = posBuf[idxPositions++];
                float nmz = normBuf[idxPositions];
                float vtz = posBuf[idxPositions++];

                float rx=0, ry=0, rz=0, rnx=0, rny=0, rnz=0;

                for (int w = maxWeightsPerVert - 1; w >= 0; w--){
                    float weight = wb.get(idxWeights); //weights[idxWeights];
                    Matrix4f mat = mesh.getBoneMatrixArray()[ib.get(idxWeights++)];//offsetMatrices[indices[idxWeights++]];

                    rx += (mat.m00 * vtx + mat.m01 * vty + mat.m02 * vtz + mat.m03) * weight;
                    ry += (mat.m10 * vtx + mat.m11 * vty + mat.m12 * vtz + mat.m13) * weight;
                    rz += (mat.m20 * vtx + mat.m21 * vty + mat.m22 * vtz + mat.m23) * weight;

                    rnx += (nmx * mat.m00 + nmy * mat.m01 + nmz * mat.m02) * weight;
                    rny += (nmx * mat.m10 + nmy * mat.m11 + nmz * mat.m12) * weight;
                    rnz += (nmx * mat.m20 + nmy * mat.m21 + nmz * mat.m22) * weight;
                }

                idxWeights += fourMinusMaxWeights;

                idxPositions -= 3;
                normBuf[idxPositions] = rnx;
                posBuf[idxPositions++] = rx;
                normBuf[idxPositions] = rny;
                posBuf[idxPositions++] = ry;
                normBuf[idxPositions] = rnz;
                posBuf[idxPositions++] = rz;
            }


//            fvb.position(fvb2.position()-bufLength);
            fvb.put(posBuf, 0, bufLength);
//            fnb.position(fnb2.position()-bufLength);
            fnb.put(normBuf, 0, bufLength);
        }
        vb.setUpdateNeeded();
        nb.setUpdateNeeded();
        vars.release();
        
//        mesh.updateBound();
    }