Java Code Examples for com.jme3.scene.Mesh#setBuffer()

The following examples show how to use com.jme3.scene.Mesh#setBuffer() . 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: DebugShapeFactory.java    From jmonkeybuilder with Apache License 2.0 6 votes vote down vote up
public static Mesh getDebugMesh(CollisionShape shape) {
    Mesh mesh = new Mesh();
    DebugMeshCallback callback = new DebugMeshCallback();
    /*
     * Populate the mesh based on an unscaled shape;
     * the shape's scale will be applied later, to the geometry.
     */
    Vector3f savedScale = shape.getScale().clone();
    shape.setScale(Vector3f.UNIT_XYZ);
    getVertices(shape.getObjectId(), callback);
    shape.setScale(savedScale);

    mesh.setBuffer(Type.Position, 3, callback.getVertices());
    mesh.getFloatBuffer(Type.Position).clear();
    return mesh;
}
 
Example 2
Source File: Converter.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static Mesh convert(IndexedMesh mesh) {
    Mesh jmeMesh = new Mesh();

    jmeMesh.setBuffer(Type.Index, 3, BufferUtils.createShortBuffer(mesh.numTriangles * 3));
    jmeMesh.setBuffer(Type.Position, 3, BufferUtils.createFloatBuffer(mesh.numVertices * 3));

    IndexBuffer indicess = jmeMesh.getIndexBuffer();
    FloatBuffer vertices = jmeMesh.getFloatBuffer(Type.Position);

    for (int i = 0; i < mesh.numTriangles * 3; i++) {
        indicess.put(i, mesh.triangleIndexBase.getInt(i * 4));
    }

    for (int i = 0; i < mesh.numVertices * 3; i++) {
        vertices.put(i, mesh.vertexBase.getFloat(i * 4));
    }
    jmeMesh.updateCounts();
    jmeMesh.updateBound();
    jmeMesh.getFloatBuffer(Type.Position).clear();

    return jmeMesh;
}
 
Example 3
Source File: Converter.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static Mesh convert(IndexedMesh mesh) {
    Mesh jmeMesh = new Mesh();

    jmeMesh.setBuffer(Type.Index, 3, BufferUtils.createShortBuffer(mesh.numTriangles * 3));
    jmeMesh.setBuffer(Type.Position, 3, BufferUtils.createFloatBuffer(mesh.numVertices * 3));

    IndexBuffer indicess = jmeMesh.getIndexBuffer();
    FloatBuffer vertices = jmeMesh.getFloatBuffer(Type.Position);

    for (int i = 0; i < mesh.numTriangles * 3; i++) {
        indicess.put(i, mesh.triangleIndexBase.getInt(i * 4));
    }

    for (int i = 0; i < mesh.numVertices * 3; i++) {
        vertices.put(i, mesh.vertexBase.getFloat(i * 4));
    }
    jmeMesh.updateCounts();
    jmeMesh.updateBound();
    jmeMesh.getFloatBuffer(Type.Position).clear();

    return jmeMesh;
}
 
Example 4
Source File: TestRayCasting.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
    public void simpleInitApp() {
//        flyCam.setEnabled(false);

        // load material
        Material mat = (Material) assetManager.loadMaterial("Interface/Logo/Logo.j3m");

        Mesh q = new Mesh();
        q.setBuffer(Type.Position, 3, new float[]
        {
            1, 0, 0,
            0, 1.5f, 0,
            -1, 0, 0
        }
        );
        q.setBuffer(Type.Index, 3, new int[]{ 0, 1, 2 });
        q.setBound(new BoundingSphere());
        q.updateBound();
//        Geometry teapot = new Geometry("MyGeom", q);

        teapot = assetManager.loadModel("Models/Teapot/Teapot.mesh.xml");
//        teapot.scale(2f, 2f, 2f);
//        teapot.move(2f, 2f, -.5f);
        teapot.rotate(FastMath.HALF_PI, FastMath.HALF_PI, FastMath.HALF_PI);
        teapot.setMaterial(mat);
        rootNode.attachChild(teapot);

//        cam.setLocation(cam.getLocation().add(0,1,0));
//        cam.lookAt(teapot.getWorldBound().getCenter(), Vector3f.UNIT_Y);

        tracer = new RayTrace(rootNode, cam, 160, 128);
        tracer.show();
        tracer.update();
    }
 
Example 5
Source File: GeoMap.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public Mesh createMesh(Vector3f scale, Vector2f tcScale, boolean center){
    FloatBuffer pb = writeVertexArray(null, scale, center);
    FloatBuffer tb = writeTexCoordArray(null, Vector2f.ZERO, tcScale);
    FloatBuffer nb = writeNormalArray(null, scale);
    IntBuffer ib = writeIndexArray(null);
    Mesh m = new Mesh();
    m.setBuffer(Type.Position, 3, pb);
    m.setBuffer(Type.Normal, 3, nb);
    m.setBuffer(Type.TexCoord, 2, tb);
    m.setBuffer(Type.Index, 3, ib);
    m.setStatic();
    m.updateBound();
    return m;
}
 
Example 6
Source File: SilentTangentBinormalGenerator.java    From OpenRTS with MIT License 5 votes vote down vote up
private static void writeColorBuffer(List<VertexData> vertices, ColorRGBA[] cols, Mesh mesh) {
	FloatBuffer colors = BufferUtils.createFloatBuffer(vertices.size() * 4);
	colors.rewind();
	for (ColorRGBA color : cols) {
		colors.put(color.r);
		colors.put(color.g);
		colors.put(color.b);
		colors.put(color.a);
	}
	mesh.clearBuffer(Type.Color);
	mesh.setBuffer(Type.Color, 4, colors);
}
 
Example 7
Source File: MikkTSpaceImpl.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public MikkTSpaceImpl(Mesh mesh) {
    this.mesh = mesh;
    //replacing any existing tangent buffer, if you came here you want them new.
    mesh.clearBuffer(VertexBuffer.Type.Tangent);
    FloatBuffer fb = BufferUtils.createFloatBuffer(mesh.getVertexCount() * 4);
    mesh.setBuffer(VertexBuffer.Type.Tangent, 4, fb);
}
 
Example 8
Source File: DebugShapeFactory.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Create a mesh for visualizing the specified shape.
 *
 * @param shape (not null, unaffected)
 * @return a new mesh (not null)
 */
public static Mesh getDebugMesh(CollisionShape shape) {
    Mesh mesh = new Mesh();
    DebugMeshCallback callback = new DebugMeshCallback();
    long id = shape.getObjectId();
    getVertices(id, callback);

    mesh.setBuffer(Type.Position, 3, callback.getVertices());
    mesh.getFloatBuffer(Type.Position).clear();
    return mesh;
}
 
Example 9
Source File: FloatToFixed.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void compressIndexBuffer(Mesh mesh){
    int vertCount = mesh.getVertexCount();
    VertexBuffer vb = mesh.getBuffer(Type.Index);
    Format targetFmt;
    if (vb.getFormat() == Format.UnsignedInt && vertCount <= 0xffff){
        if (vertCount <= 256)
            targetFmt = Format.UnsignedByte;
        else
            targetFmt = Format.UnsignedShort;
    }else if (vb.getFormat() == Format.UnsignedShort && vertCount <= 0xff){
        targetFmt = Format.UnsignedByte;
    }else{
        return;
    }

    IndexBuffer src = mesh.getIndexBuffer();
    Buffer newBuf = VertexBuffer.createBuffer(targetFmt, vb.getNumComponents(), src.size());

    VertexBuffer newVb = new VertexBuffer(Type.Index);
    newVb.setupData(vb.getUsage(), vb.getNumComponents(), targetFmt, newBuf);
    mesh.clearBuffer(Type.Index);
    mesh.setBuffer(newVb);

    IndexBuffer dst = mesh.getIndexBuffer();
    for (int i = 0; i < src.size(); i++){
        dst.put(i, src.get(i));
    }
}
 
Example 10
Source File: TestIssue1004.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void simpleInitApp() {
    BulletAppState bulletAppState = new BulletAppState();
    stateManager.attach(bulletAppState);
    String sinbadPath = "Models/Sinbad/SinbadOldAnim.j3o";
    Node sinbad = (Node) assetManager.loadModel(sinbadPath);

    Geometry geometry = (Geometry) sinbad.getChild(0);
    Mesh mesh = geometry.getMesh();
    VertexBuffer.Type bufferType = VertexBuffer.Type.BoneIndex;
    VertexBuffer vertexBuffer = mesh.getBuffer(bufferType);

    // Remove the existing bone-index buffer.
    mesh.getBufferList().remove(vertexBuffer);
    mesh.getBuffers().remove(bufferType.ordinal());

    // Copy the 8-bit bone indices to 16-bit indices.
    ByteBuffer oldBuffer = (ByteBuffer) vertexBuffer.getDataReadOnly();
    int numComponents = oldBuffer.limit();
    oldBuffer.rewind();
    short[] shortArray = new short[numComponents];
    for (int index = 0; oldBuffer.hasRemaining(); ++index) {
        shortArray[index] = oldBuffer.get();
    }

    // Add the 16-bit bone indices to the mesh.
    mesh.setBuffer(bufferType, 4, shortArray);

    KinematicRagdollControl ragdoll = new KinematicRagdollControl(0.5f);
    sinbad.addControl(ragdoll);

    stop();
}
 
Example 11
Source File: WrappedIndexBuffer.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void convertToList(Mesh mesh){
    IndexBuffer inBuf = mesh.getIndicesAsList();
    IndexBuffer outBuf = IndexBuffer.createIndexBuffer(mesh.getVertexCount(),
                                                       inBuf.size());

    for (int i = 0; i < inBuf.size(); i++){
        outBuf.put(i, inBuf.get(i));
    }

    mesh.clearBuffer(Type.Index);
    switch (mesh.getMode()){
        case LineLoop:
        case LineStrip:
            mesh.setMode(Mode.Lines);
            break;
        case TriangleStrip:
        case TriangleFan:
            mesh.setMode(Mode.Triangles);
            break;
        default:
            break;
    }
    if (outBuf instanceof IndexIntBuffer){
        mesh.setBuffer(Type.Index, 3, (IntBuffer)outBuf.getBuffer());
    }else{
        mesh.setBuffer(Type.Index, 3, (ShortBuffer)outBuf.getBuffer());
    }
}
 
Example 12
Source File: TangentBinormalGenerator.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static Mesh genNormalLines(Mesh mesh, float scale) {
    FloatBuffer vertexBuffer = (FloatBuffer) mesh.getBuffer(Type.Position).getData();
    FloatBuffer normalBuffer = (FloatBuffer) mesh.getBuffer(Type.Normal).getData();

    ColorRGBA originColor = ColorRGBA.White;
    ColorRGBA normalColor = ColorRGBA.Blue;

    Mesh lineMesh = new Mesh();
    lineMesh.setMode(Mesh.Mode.Lines);

    Vector3f origin = new Vector3f();
    Vector3f point = new Vector3f();

    FloatBuffer lineVertex = BufferUtils.createFloatBuffer(vertexBuffer.capacity() * 2);
    FloatBuffer lineColor = BufferUtils.createFloatBuffer(vertexBuffer.capacity() / 3 * 4 * 2);

    for (int i = 0; i < vertexBuffer.capacity() / 3; i++) {
        populateFromBuffer(origin, vertexBuffer, i);
        populateFromBuffer(point, normalBuffer, i);

        int index = i * 2;

        setInBuffer(origin, lineVertex, index);
        setInBuffer(originColor, lineColor, index);

        point.multLocal(scale);
        point.addLocal(origin);
        setInBuffer(point, lineVertex, index + 1);
        setInBuffer(normalColor, lineColor, index + 1);
    }

    lineMesh.setBuffer(Type.Position, 3, lineVertex);
    lineMesh.setBuffer(Type.Color, 4, lineColor);

    lineMesh.setStatic();
    lineMesh.setInterleaved();
    return lineMesh;
}
 
Example 13
Source File: LODGeomap.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public Mesh createMesh(Vector3f scale, Vector2f tcScale, Vector2f tcOffset, float offsetAmount, int totalSize, boolean center, int lod, boolean rightLod, boolean topLod, boolean leftLod, boolean bottomLod) {
    FloatBuffer pb = writeVertexArray(null, scale, center);
    FloatBuffer texb = writeTexCoordArray(null, tcOffset, tcScale, offsetAmount, totalSize);
    FloatBuffer nb = writeNormalArray(null, scale);
    IndexBuffer ib = writeIndexArrayLodDiff(lod, rightLod, topLod, leftLod, bottomLod, totalSize);
    FloatBuffer bb = BufferUtils.createFloatBuffer(getWidth() * getHeight() * 3);
    FloatBuffer tanb = BufferUtils.createFloatBuffer(getWidth() * getHeight() * 3);
    writeTangentArray(nb, tanb, bb, texb, scale);
    Mesh m = new Mesh();
    m.setMode(Mode.TriangleStrip);
    m.setBuffer(Type.Position, 3, pb);
    m.setBuffer(Type.Normal, 3, nb);
    m.setBuffer(Type.Tangent, 3, tanb);
    m.setBuffer(Type.Binormal, 3, bb);
    m.setBuffer(Type.TexCoord, 2, texb);
    switch (ib.getFormat()) {
        case UnsignedInt:
            m.setBuffer(Type.Index, 3, (IntBuffer) ib.getBuffer());
            break;
        case UnsignedShort:
            m.setBuffer(Type.Index, 3, (ShortBuffer) ib.getBuffer());
            break;
        case UnsignedByte:
            m.setBuffer(Type.Index, 3, (ByteBuffer) ib.getBuffer());
            break;
    }
    m.setStatic();
    m.updateBound();
    return m;
}
 
Example 14
Source File: PhysicsTestHelper.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private static Mesh createFloorMesh(int meshDetail, float floorDimensions) {
    if (meshDetail < 10) {
        meshDetail = 10;
    }
    int numVertices = meshDetail * meshDetail * 2 * 3;//width * depth * two tris * 3 verts per tri

    int[] indexBuf = new int[numVertices];
    int i = 0;
    for (int x = 0; x < meshDetail; x++) {
        for (int z = 0; z < meshDetail; z++) {
            indexBuf[i] = i++;
            indexBuf[i] = i++;
            indexBuf[i] = i++;
            indexBuf[i] = i++;
            indexBuf[i] = i++;
            indexBuf[i] = i++;
        }
    }

    float[] vertBuf = new float[numVertices * 3];
    float xIncrement = floorDimensions / meshDetail;
    float zIncrement = floorDimensions / meshDetail;
    int j = 0;
    for (int x = 0; x < meshDetail; x++) {
        float xPos = x * xIncrement;
        for (int z = 0; z < meshDetail; z++) {
            float zPos = z * zIncrement;
            //First tri
            vertBuf[j++] = xPos;
            vertBuf[j++] = getY(xPos, zPos, floorDimensions);
            vertBuf[j++] = zPos;
            vertBuf[j++] = xPos;
            vertBuf[j++] = getY(xPos, zPos + zIncrement, floorDimensions);
            vertBuf[j++] = zPos + zIncrement;
            vertBuf[j++] = xPos + xIncrement;
            vertBuf[j++] = getY(xPos + xIncrement, zPos, floorDimensions);
            vertBuf[j++] = zPos;
            //Second tri
            vertBuf[j++] = xPos;
            vertBuf[j++] = getY(xPos, zPos + zIncrement, floorDimensions);
            vertBuf[j++] = zPos + zIncrement;
            vertBuf[j++] = xPos + xIncrement;
            vertBuf[j++] = getY(xPos + xIncrement, zPos + zIncrement, floorDimensions);
            vertBuf[j++] = zPos + zIncrement;
            vertBuf[j++] = xPos + xIncrement;
            vertBuf[j++] = getY(xPos + xIncrement, zPos, floorDimensions);
            vertBuf[j++] = zPos;
        }
    }

    Mesh m = new Mesh();
    m.setBuffer(VertexBuffer.Type.Index, 1, BufferUtils.createIntBuffer(indexBuf));
    m.setBuffer(VertexBuffer.Type.Position, 3, BufferUtils.createFloatBuffer(vertBuf));
    m.updateBound();
    return m;
}
 
Example 15
Source File: TestTextureArrayCompressed.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void simpleInitApp()
{
    Material mat = new Material(assetManager, "jme3test/texture/UnshadedArray.j3md");
    
    for (Caps caps : renderManager.getRenderer().getCaps()) {
        System.out.println(caps.name());
    }
    if(!renderManager.getRenderer().getCaps().contains(Caps.TextureArray)){
        throw new UnsupportedOperationException("Your hardware does not support TextureArray");
    }
    
    
    Texture tex1 = assetManager.loadTexture( "Textures/Terrain/Pond/Pond_dxt5.dds");
    Texture tex2 = assetManager.loadTexture("Textures/Terrain/BrickWall/BrickWall_dxt5.dds");
    List<Image> images = new ArrayList<Image>();
    images.add(tex1.getImage());
    images.add(tex2.getImage());
    TextureArray tex3 = new TextureArray(images);
    tex3.setMinFilter(Texture.MinFilter.Trilinear);
    mat.setTexture("ColorMap", tex3);

    Mesh m = new Mesh();
    Vector3f[] vertices = new Vector3f[8];
    vertices[0] = new Vector3f(0, 0, 0);
    vertices[1] = new Vector3f(3, 0, 0);
    vertices[2] = new Vector3f(0, 3, 0);
    vertices[3] = new Vector3f(3, 3, 0);

    vertices[4] = new Vector3f(3, 0, 0);
    vertices[5] = new Vector3f(6, 0, 0);
    vertices[6] = new Vector3f(3, 3, 0);
    vertices[7] = new Vector3f(6, 3, 0);

    Vector3f[] texCoord = new Vector3f[8];
    texCoord[0] = new Vector3f(0, 0, 0);
    texCoord[1] = new Vector3f(1, 0, 0);
    texCoord[2] = new Vector3f(0, 1, 0);
    texCoord[3] = new Vector3f(1, 1, 0);

    texCoord[4] = new Vector3f(0, 0, 1);
    texCoord[5] = new Vector3f(1, 0, 1);
    texCoord[6] = new Vector3f(0, 1, 1);
    texCoord[7] = new Vector3f(1, 1, 1);

    int[] indexes = { 2, 0, 1, 1, 3, 2 , 6, 4, 5, 5, 7, 6};

    m.setBuffer(Type.Position, 3, BufferUtils.createFloatBuffer(vertices));
    m.setBuffer(Type.TexCoord, 3, BufferUtils.createFloatBuffer(texCoord));
    m.setBuffer(Type.Index, 1, BufferUtils.createIntBuffer(indexes));
    m.updateBound();

    Geometry geom = new Geometry("Mesh", m);
    geom.setMaterial(mat);
    rootNode.attachChild(geom);
}
 
Example 16
Source File: TestCustomMesh.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
    public void simpleInitApp() {
      
        Mesh m = new Mesh();

        // Vertex positions in space
        Vector3f [] vertices = new Vector3f[4];
        vertices[0] = new Vector3f(0,0,0);
        vertices[1] = new Vector3f(3,0,0);
        vertices[2] = new Vector3f(0,3,0);
        vertices[3] = new Vector3f(3,3,0);

        // Texture coordinates
        Vector2f [] texCoord = new Vector2f[4];
        texCoord[0] = new Vector2f(0,0);
        texCoord[1] = new Vector2f(1,0);
        texCoord[2] = new Vector2f(0,1);
        texCoord[3] = new Vector2f(1,1);

        // Indexes. We define the order in which mesh should be constructed
        short[] indexes = {2, 0, 1, 1, 3, 2};

        // Setting buffers
        m.setBuffer(Type.Position, 3, BufferUtils.createFloatBuffer(vertices));
        m.setBuffer(Type.TexCoord, 2, BufferUtils.createFloatBuffer(texCoord));
        m.setBuffer(Type.Index, 1, BufferUtils.createShortBuffer(indexes));
        m.updateBound();

        // *************************************************************************
        // First mesh uses one solid color
        // *************************************************************************

        // Creating a geometry, and apply a single color material to it
        Geometry geom = new Geometry("OurMesh", m);
        Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        mat.setColor("Color", ColorRGBA.Blue);
        geom.setMaterial(mat);

        // Attaching our geometry to the root node.
        rootNode.attachChild(geom);

        // *************************************************************************
        // Second mesh uses vertex colors to color each vertex
        // *************************************************************************
        Mesh cMesh = m.clone();
        Geometry coloredMesh = new Geometry ("ColoredMesh", cMesh);
        Material matVC = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        matVC.setBoolean("VertexColor", true);

        //We have 4 vertices and 4 color values for each of them.
        //If you have more vertices, you need 'new float[yourVertexCount * 4]' here!
        float[] colorArray = new float[4*4];
        int colorIndex = 0;

        //Set custom RGBA value for each Vertex. Values range from 0.0f to 1.0f
        for(int i = 0; i < 4; i++){
           // Red value (is increased by .2 on each next vertex here)
           colorArray[colorIndex++]= 0.1f+(.2f*i);
           // Green value (is reduced by .2 on each next vertex)
           colorArray[colorIndex++]= 0.9f-(0.2f*i);
           // Blue value (remains the same in our case)
           colorArray[colorIndex++]= 0.5f;
           // Alpha value (no transparency set here)
           colorArray[colorIndex++]= 1.0f;
        }
        // Set the color buffer
        cMesh.setBuffer(Type.Color, 4, colorArray);
        coloredMesh.setMaterial(matVC);
        // move mesh a bit so that it doesn't intersect with the first one
        coloredMesh.setLocalTranslation(4, 0, 0);
        rootNode.attachChild(coloredMesh);

//        /** Alternatively, you can show the mesh vertixes as points
//          * instead of coloring the faces. */
//        cMesh.setMode(Mesh.Mode.Points);
//        cMesh.setPointSize(10f);
//        cMesh.updateBound();
//        cMesh.setStatic();
//        Geometry points = new Geometry("Points", m);
//        points.setMaterial(mat);
//        rootNode.attachChild(points);

        // *************************************************************************
        // Third mesh will use a wireframe shader to show wireframe
        // *************************************************************************
        Mesh wfMesh = m.clone();
        Geometry wfGeom = new Geometry("wireframeGeometry", wfMesh);
        Material matWireframe = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        matWireframe.setColor("Color", ColorRGBA.Green);
        matWireframe.getAdditionalRenderState().setWireframe(true);
        wfGeom.setMaterial(matWireframe);
        wfGeom.setLocalTranslation(4, 4, 0);
        rootNode.attachChild(wfGeom);
        
    }
 
Example 17
Source File: FbxSkin.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private int generateBoneData(Mesh mesh, FbxMesh fbxMesh) {
	// Create bone buffers
	FloatBuffer boneWeightData = BufferUtils.createFloatBuffer(fbxMesh.vCount * 4);
	ByteBuffer boneIndicesData = BufferUtils.createByteBuffer(fbxMesh.vCount * 4);
	mesh.setBuffer(VertexBuffer.Type.BoneWeight, 4, boneWeightData);
	mesh.setBuffer(VertexBuffer.Type.BoneIndex, 4, boneIndicesData);
	mesh.getBuffer(VertexBuffer.Type.BoneWeight).setUsage(Usage.CpuOnly);
	mesh.getBuffer(VertexBuffer.Type.BoneIndex).setUsage(Usage.CpuOnly);
	VertexBuffer weightsHW = new VertexBuffer(Type.HWBoneWeight);
	VertexBuffer indicesHW = new VertexBuffer(Type.HWBoneIndex);
	indicesHW.setUsage(Usage.CpuOnly); // Setting usage to CpuOnly so that the buffer is not send empty to the GPU
	weightsHW.setUsage(Usage.CpuOnly);
	mesh.setBuffer(weightsHW);
	mesh.setBuffer(indicesHW);
	int bonesLimitExceeded = 0;
	// Accumulate skin bones influence into mesh buffers
	for(FbxNode limb : bones) {
		FbxCluster cluster = limb.skinToCluster.get(id);
		if(cluster == null || cluster.indexes == null || cluster.weights == null || cluster.indexes.length != cluster.weights.length)
			continue;
		if(limb.boneIndex > 255)
			throw new AssetLoadException("Bone index can't be packed into byte");
		for(int i = 0; i < cluster.indexes.length; ++i) {
			int vertexIndex = cluster.indexes[i];
			if(vertexIndex >= fbxMesh.reverseVertexMap.size())
				throw new AssetLoadException("Invalid skinning vertex index. Unexpected index lookup " + vertexIndex + " from " + fbxMesh.reverseVertexMap.size());
			List<Integer> dstVertices = fbxMesh.reverseVertexMap.get(vertexIndex);
			for(int j = 0; j < dstVertices.size(); ++j) {
				int v = dstVertices.get(j);
				// Append bone index and weight to vertex
				int offset;
				int smalestOffset = 0;
				float w = 0;
				float smalestW = Float.MAX_VALUE;
				for(offset = v * 4; offset < v * 4 + 4; ++offset) {
					w = boneWeightData.get(offset);
					if(w == 0)
						break;
					if(w < smalestW) {
						smalestW = w;
						smalestOffset = offset;
					}
				}
				if(w == 0) {
					boneWeightData.put(offset, (float) cluster.weights[i]);
					boneIndicesData.put(offset, (byte) limb.boneIndex);
				} else {
					if((float) cluster.weights[i] > smalestW) { // If current weight more than smallest, discard smallest
						boneWeightData.put(smalestOffset, (float) cluster.weights[i]);
						boneIndicesData.put(smalestOffset, (byte) limb.boneIndex);
					}
					bonesLimitExceeded++;
				}
			}
		}
	}
	if(bonesLimitExceeded > 0)
		scene.warning("Skinning support max 4 bone per vertex. Exceeding data of " + bonesLimitExceeded + " weights in mesh bones will be discarded");
	// Postprocess bones weights
	int maxWeightsPerVert = 0;
	boneWeightData.rewind();
	for(int v = 0; v < fbxMesh.vCount; v++) {
		float w0 = boneWeightData.get();
		float w1 = boneWeightData.get();
		float w2 = boneWeightData.get();
		float w3 = boneWeightData.get();
		if(w3 != 0) {
			maxWeightsPerVert = Math.max(maxWeightsPerVert, 4);
		} else if(w2 != 0) {
			maxWeightsPerVert = Math.max(maxWeightsPerVert, 3);
		} else if(w1 != 0) {
			maxWeightsPerVert = Math.max(maxWeightsPerVert, 2);
		} else if(w0 != 0) {
			maxWeightsPerVert = Math.max(maxWeightsPerVert, 1);
		}
		float sum = w0 + w1 + w2 + w3;
		if(sum != 1f) {
			// normalize weights
			float mult = (sum != 0) ? (1f / sum) : 0;
			boneWeightData.position(v * 4);
			boneWeightData.put(w0 * mult);
			boneWeightData.put(w1 * mult);
			boneWeightData.put(w2 * mult);
			boneWeightData.put(w3 * mult);
		}
	}
	return maxWeightsPerVert;
}
 
Example 18
Source File: BitmapTextPage.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
BitmapTextPage(BitmapFont font, boolean arrayBased, int page) {
    super("BitmapFont", new Mesh());
    setRequiresUpdates(false);
    setBatchHint(BatchHint.Never);
    if (font == null) {
        throw new IllegalArgumentException("font cannot be null.");
    }

    this.page = page;

    Material mat = font.getPage(page);
    if (mat == null) {
        throw new IllegalStateException("The font's texture was not found!");
    }

    setMaterial(mat);
    this.texture = (Texture2D) mat.getTextureParam("ColorMap").getTextureValue();

    // initialize buffers
    Mesh m = getMesh();
    m.setBuffer(Type.Position, 3, new float[0]);
    m.setBuffer(Type.TexCoord, 2, new float[0]);
    m.setBuffer(Type.Color, 4, new byte[0]);
    m.setBuffer(Type.Index, 3, new short[0]);

    // scale colors from 0 - 255 range into 0 - 1
    m.getBuffer(Type.Color).setNormalized(true);

    arrayBased = true;

    /*
     * TODO: Since this is forced to true, should we just lose the conditional?
     * - Skye (sbook)
     */
    if (arrayBased) {
        pos = new float[4 * 3];  // 4 verticies * 3 floats
        tc = new float[4 * 2];  // 4 verticies * 2 floats
        idx = new short[2 * 3];  // 2 triangles * 3 indices
        color = new byte[4 * 4];   // 4 verticies * 4 bytes
    } else {
        pos = null;
        tc = null;
        idx = null;
        color = null;
    }
}
 
Example 19
Source File: SilentTangentBinormalGenerator.java    From OpenRTS with MIT License 4 votes vote down vote up
public static void generate(Mesh mesh, boolean approxTangents, boolean splitMirrored) {
	int[] index = new int[3];
	Vector3f[] v = new Vector3f[3];
	Vector2f[] t = new Vector2f[3];
	for (int i = 0; i < 3; i++) {
		v[i] = new Vector3f();
		t[i] = new Vector2f();
	}

	if (mesh.getBuffer(Type.Normal) == null) {
		throw new IllegalArgumentException("The given mesh has no normal data!");
	}

	List<VertexData> vertices;
	switch (mesh.getMode()) {
		case Triangles:
			vertices = processTriangles(mesh, index, v, t, splitMirrored);
			if (splitMirrored) {
				splitVertices(mesh, vertices, splitMirrored);
			}
			break;
		case TriangleStrip:
			vertices = processTriangleStrip(mesh, index, v, t);
			break;
		case TriangleFan:
			vertices = processTriangleFan(mesh, index, v, t);
			break;
		default:
			throw new UnsupportedOperationException(mesh.getMode() + " is not supported.");
	}

	processTriangleData(mesh, vertices, approxTangents, splitMirrored);

	// if the mesh has a bind pose, we need to generate the bind pose for the tangent buffer
	if (mesh.getBuffer(Type.BindPosePosition) != null) {

		VertexBuffer tangents = mesh.getBuffer(Type.Tangent);
		if (tangents != null) {
			VertexBuffer bindTangents = new VertexBuffer(Type.BindPoseTangent);
			bindTangents.setupData(Usage.CpuOnly, 4, Format.Float, BufferUtils.clone(tangents.getData()));

			if (mesh.getBuffer(Type.BindPoseTangent) != null) {
				mesh.clearBuffer(Type.BindPoseTangent);
			}
			mesh.setBuffer(bindTangents);
			tangents.setUsage(Usage.Stream);
		}
	}
}
 
Example 20
Source File: EntropyComputeUtil.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static float computeLodEntropy(Mesh terrainBlock, Buffer lodIndices){
    // Bounding box for the terrain block
    BoundingBox bbox = (BoundingBox) terrainBlock.getBound();

    // Vertex positions for the block
    FloatBuffer positions = terrainBlock.getFloatBuffer(Type.Position);

    // Prepare to cast rays
    Vector3f pos = new Vector3f();
    Vector3f dir = new Vector3f(0, -1, 0);
    Ray ray = new Ray(pos, dir);

    // Prepare collision results
    CollisionResults results = new CollisionResults();

    // Set the LOD indices on the block
    VertexBuffer originalIndices = terrainBlock.getBuffer(Type.Index);

    terrainBlock.clearBuffer(Type.Index);
    if (lodIndices instanceof IntBuffer)
        terrainBlock.setBuffer(Type.Index, 3, (IntBuffer)lodIndices);
    else if (lodIndices instanceof ShortBuffer) {
        terrainBlock.setBuffer(Type.Index, 3, (ShortBuffer) lodIndices);
    } else {
        terrainBlock.setBuffer(Type.Index, 3, (ByteBuffer) lodIndices);
    }

    // Recalculate collision mesh
    terrainBlock.createCollisionData();

    float entropy = 0;
    for (int i = 0; i < positions.limit() / 3; i++){
        BufferUtils.populateFromBuffer(pos, positions, i);

        float realHeight = pos.y;

        pos.addLocal(0, bbox.getYExtent(), 0);
        ray.setOrigin(pos);

        results.clear();
        terrainBlock.collideWith(ray, Matrix4f.IDENTITY, bbox, results);

        if (results.size() > 0){
            Vector3f contactPoint = results.getClosestCollision().getContactPoint();
            float delta = Math.abs(realHeight - contactPoint.y);
            entropy = Math.max(delta, entropy);
        }
    }

    // Restore original indices
    terrainBlock.clearBuffer(Type.Index);
    terrainBlock.setBuffer(originalIndices);

    return entropy;
}