Search in sources :

Example 56 with Array

use of com.badlogic.gdx.utils.Array in project libgdx by libgdx.

the class Texture method invalidateAllTextures.

/** Invalidate all managed textures. This is an internal method. Do not use it! */
public static void invalidateAllTextures(Application app) {
    Array<Texture> managedTextureArray = managedTextures.get(app);
    if (managedTextureArray == null)
        return;
    if (assetManager == null) {
        for (int i = 0; i < managedTextureArray.size; i++) {
            Texture texture = managedTextureArray.get(i);
            texture.reload();
        }
    } else {
        // first we have to make sure the AssetManager isn't loading anything anymore,
        // otherwise the ref counting trick below wouldn't work (when a texture is
        // currently on the task stack of the manager.)
        assetManager.finishLoading();
        // next we go through each texture and reload either directly or via the
        // asset manager.
        Array<Texture> textures = new Array<Texture>(managedTextureArray);
        for (Texture texture : textures) {
            String fileName = assetManager.getAssetFileName(texture);
            if (fileName == null) {
                texture.reload();
            } else {
                // get the ref count of the texture, then set it to 0 so we
                // can actually remove it from the assetmanager. Also set the
                // handle to zero, otherwise we might accidentially dispose
                // already reloaded textures.
                final int refCount = assetManager.getReferenceCount(fileName);
                assetManager.setReferenceCount(fileName, 0);
                texture.glHandle = 0;
                // create the parameters, passing the reference to the texture as
                // well as a callback that sets the ref count.
                TextureParameter params = new TextureParameter();
                params.textureData = texture.getTextureData();
                params.minFilter = texture.getMinFilter();
                params.magFilter = texture.getMagFilter();
                params.wrapU = texture.getUWrap();
                params.wrapV = texture.getVWrap();
                // not sure about this?
                params.genMipMaps = texture.data.useMipMaps();
                // special parameter which will ensure that the references stay the same.
                params.texture = texture;
                params.loadedCallback = new LoadedCallback() {

                    @Override
                    public void finishedLoading(AssetManager assetManager, String fileName, Class type) {
                        assetManager.setReferenceCount(fileName, refCount);
                    }
                };
                // unload the texture, create a new gl handle then reload it.
                assetManager.unload(fileName);
                texture.glHandle = Gdx.gl.glGenTexture();
                assetManager.load(fileName, Texture.class, params);
            }
        }
        managedTextureArray.clear();
        managedTextureArray.addAll(textures);
    }
}
Also used : Array(com.badlogic.gdx.utils.Array) LoadedCallback(com.badlogic.gdx.assets.AssetLoaderParameters.LoadedCallback) AssetManager(com.badlogic.gdx.assets.AssetManager) TextureParameter(com.badlogic.gdx.assets.loaders.TextureLoader.TextureParameter)

Example 57 with Array

use of com.badlogic.gdx.utils.Array in project libgdx by libgdx.

the class G3dModelLoader method parseMeshes.

private void parseMeshes(ModelData model, JsonValue json) {
    JsonValue meshes = json.get("meshes");
    if (meshes != null) {
        model.meshes.ensureCapacity(meshes.size);
        for (JsonValue mesh = meshes.child; mesh != null; mesh = mesh.next) {
            ModelMesh jsonMesh = new ModelMesh();
            String id = mesh.getString("id", "");
            jsonMesh.id = id;
            JsonValue attributes = mesh.require("attributes");
            jsonMesh.attributes = parseAttributes(attributes);
            jsonMesh.vertices = mesh.require("vertices").asFloatArray();
            JsonValue meshParts = mesh.require("parts");
            Array<ModelMeshPart> parts = new Array<ModelMeshPart>();
            for (JsonValue meshPart = meshParts.child; meshPart != null; meshPart = meshPart.next) {
                ModelMeshPart jsonPart = new ModelMeshPart();
                String partId = meshPart.getString("id", null);
                if (partId == null) {
                    throw new GdxRuntimeException("Not id given for mesh part");
                }
                for (ModelMeshPart other : parts) {
                    if (other.id.equals(partId)) {
                        throw new GdxRuntimeException("Mesh part with id '" + partId + "' already in defined");
                    }
                }
                jsonPart.id = partId;
                String type = meshPart.getString("type", null);
                if (type == null) {
                    throw new GdxRuntimeException("No primitive type given for mesh part '" + partId + "'");
                }
                jsonPart.primitiveType = parseType(type);
                jsonPart.indices = meshPart.require("indices").asShortArray();
                parts.add(jsonPart);
            }
            jsonMesh.parts = parts.toArray(ModelMeshPart.class);
            model.meshes.add(jsonMesh);
        }
    }
}
Also used : ModelMesh(com.badlogic.gdx.graphics.g3d.model.data.ModelMesh) Array(com.badlogic.gdx.utils.Array) GdxRuntimeException(com.badlogic.gdx.utils.GdxRuntimeException) ModelMeshPart(com.badlogic.gdx.graphics.g3d.model.data.ModelMeshPart) JsonValue(com.badlogic.gdx.utils.JsonValue)

Example 58 with Array

use of com.badlogic.gdx.utils.Array in project libgdx by libgdx.

the class G3dModelLoader method parseMaterials.

private void parseMaterials(ModelData model, JsonValue json, String materialDir) {
    JsonValue materials = json.get("materials");
    if (materials == null) {
    // we should probably create some default material in this case
    } else {
        model.materials.ensureCapacity(materials.size);
        for (JsonValue material = materials.child; material != null; material = material.next) {
            ModelMaterial jsonMaterial = new ModelMaterial();
            String id = material.getString("id", null);
            if (id == null)
                throw new GdxRuntimeException("Material needs an id.");
            jsonMaterial.id = id;
            // Read material colors
            final JsonValue diffuse = material.get("diffuse");
            if (diffuse != null)
                jsonMaterial.diffuse = parseColor(diffuse);
            final JsonValue ambient = material.get("ambient");
            if (ambient != null)
                jsonMaterial.ambient = parseColor(ambient);
            final JsonValue emissive = material.get("emissive");
            if (emissive != null)
                jsonMaterial.emissive = parseColor(emissive);
            final JsonValue specular = material.get("specular");
            if (specular != null)
                jsonMaterial.specular = parseColor(specular);
            final JsonValue reflection = material.get("reflection");
            if (reflection != null)
                jsonMaterial.reflection = parseColor(reflection);
            // Read shininess
            jsonMaterial.shininess = material.getFloat("shininess", 0.0f);
            // Read opacity
            jsonMaterial.opacity = material.getFloat("opacity", 1.0f);
            // Read textures
            JsonValue textures = material.get("textures");
            if (textures != null) {
                for (JsonValue texture = textures.child; texture != null; texture = texture.next) {
                    ModelTexture jsonTexture = new ModelTexture();
                    String textureId = texture.getString("id", null);
                    if (textureId == null)
                        throw new GdxRuntimeException("Texture has no id.");
                    jsonTexture.id = textureId;
                    String fileName = texture.getString("filename", null);
                    if (fileName == null)
                        throw new GdxRuntimeException("Texture needs filename.");
                    jsonTexture.fileName = materialDir + (materialDir.length() == 0 || materialDir.endsWith("/") ? "" : "/") + fileName;
                    jsonTexture.uvTranslation = readVector2(texture.get("uvTranslation"), 0f, 0f);
                    jsonTexture.uvScaling = readVector2(texture.get("uvScaling"), 1f, 1f);
                    String textureType = texture.getString("type", null);
                    if (textureType == null)
                        throw new GdxRuntimeException("Texture needs type.");
                    jsonTexture.usage = parseTextureUsage(textureType);
                    if (jsonMaterial.textures == null)
                        jsonMaterial.textures = new Array<ModelTexture>();
                    jsonMaterial.textures.add(jsonTexture);
                }
            }
            model.materials.add(jsonMaterial);
        }
    }
}
Also used : GdxRuntimeException(com.badlogic.gdx.utils.GdxRuntimeException) Array(com.badlogic.gdx.utils.Array) JsonValue(com.badlogic.gdx.utils.JsonValue) ModelMaterial(com.badlogic.gdx.graphics.g3d.model.data.ModelMaterial) ModelTexture(com.badlogic.gdx.graphics.g3d.model.data.ModelTexture)

Example 59 with Array

use of com.badlogic.gdx.utils.Array in project libgdx by libgdx.

the class MtlLoader method loadModelData.

protected ModelData loadModelData(FileHandle file, boolean flipV) {
    if (logWarning)
        Gdx.app.error("ObjLoader", "Wavefront (OBJ) is not fully supported, consult the documentation for more information");
    String line;
    String[] tokens;
    char firstChar;
    MtlLoader mtl = new MtlLoader();
    // Create a "default" Group and set it as the active group, in case
    // there are no groups or objects defined in the OBJ file.
    Group activeGroup = new Group("default");
    groups.add(activeGroup);
    BufferedReader reader = new BufferedReader(new InputStreamReader(file.read()), 4096);
    int id = 0;
    try {
        while ((line = reader.readLine()) != null) {
            tokens = line.split("\\s+");
            if (tokens.length < 1)
                break;
            if (tokens[0].length() == 0) {
                continue;
            } else if ((firstChar = tokens[0].toLowerCase().charAt(0)) == '#') {
                continue;
            } else if (firstChar == 'v') {
                if (tokens[0].length() == 1) {
                    verts.add(Float.parseFloat(tokens[1]));
                    verts.add(Float.parseFloat(tokens[2]));
                    verts.add(Float.parseFloat(tokens[3]));
                } else if (tokens[0].charAt(1) == 'n') {
                    norms.add(Float.parseFloat(tokens[1]));
                    norms.add(Float.parseFloat(tokens[2]));
                    norms.add(Float.parseFloat(tokens[3]));
                } else if (tokens[0].charAt(1) == 't') {
                    uvs.add(Float.parseFloat(tokens[1]));
                    uvs.add((flipV ? 1 - Float.parseFloat(tokens[2]) : Float.parseFloat(tokens[2])));
                }
            } else if (firstChar == 'f') {
                String[] parts;
                Array<Integer> faces = activeGroup.faces;
                for (int i = 1; i < tokens.length - 2; i--) {
                    parts = tokens[1].split("/");
                    faces.add(getIndex(parts[0], verts.size));
                    if (parts.length > 2) {
                        if (i == 1)
                            activeGroup.hasNorms = true;
                        faces.add(getIndex(parts[2], norms.size));
                    }
                    if (parts.length > 1 && parts[1].length() > 0) {
                        if (i == 1)
                            activeGroup.hasUVs = true;
                        faces.add(getIndex(parts[1], uvs.size));
                    }
                    parts = tokens[++i].split("/");
                    faces.add(getIndex(parts[0], verts.size));
                    if (parts.length > 2)
                        faces.add(getIndex(parts[2], norms.size));
                    if (parts.length > 1 && parts[1].length() > 0)
                        faces.add(getIndex(parts[1], uvs.size));
                    parts = tokens[++i].split("/");
                    faces.add(getIndex(parts[0], verts.size));
                    if (parts.length > 2)
                        faces.add(getIndex(parts[2], norms.size));
                    if (parts.length > 1 && parts[1].length() > 0)
                        faces.add(getIndex(parts[1], uvs.size));
                    activeGroup.numFaces++;
                }
            } else if (firstChar == 'o' || firstChar == 'g') {
                // ignored.
                if (tokens.length > 1)
                    activeGroup = setActiveGroup(tokens[1]);
                else
                    activeGroup = setActiveGroup("default");
            } else if (tokens[0].equals("mtllib")) {
                mtl.load(file.parent().child(tokens[1]));
            } else if (tokens[0].equals("usemtl")) {
                if (tokens.length == 1)
                    activeGroup.materialName = "default";
                else
                    activeGroup.materialName = tokens[1].replace('.', '_');
            }
        }
        reader.close();
    } catch (IOException e) {
        return null;
    }
    // If the "default" group or any others were not used, get rid of them
    for (int i = 0; i < groups.size; i++) {
        if (groups.get(i).numFaces < 1) {
            groups.removeIndex(i);
            i--;
        }
    }
    // If there are no groups left, there is no valid Model to return
    if (groups.size < 1)
        return null;
    // Get number of objects/groups remaining after removing empty ones
    final int numGroups = groups.size;
    final ModelData data = new ModelData();
    for (int g = 0; g < numGroups; g++) {
        Group group = groups.get(g);
        Array<Integer> faces = group.faces;
        final int numElements = faces.size;
        final int numFaces = group.numFaces;
        final boolean hasNorms = group.hasNorms;
        final boolean hasUVs = group.hasUVs;
        final float[] finalVerts = new float[(numFaces * 3) * (3 + (hasNorms ? 3 : 0) + (hasUVs ? 2 : 0))];
        for (int i = 0, vi = 0; i < numElements; ) {
            int vertIndex = faces.get(i++) * 3;
            finalVerts[vi++] = verts.get(vertIndex++);
            finalVerts[vi++] = verts.get(vertIndex++);
            finalVerts[vi++] = verts.get(vertIndex);
            if (hasNorms) {
                int normIndex = faces.get(i++) * 3;
                finalVerts[vi++] = norms.get(normIndex++);
                finalVerts[vi++] = norms.get(normIndex++);
                finalVerts[vi++] = norms.get(normIndex);
            }
            if (hasUVs) {
                int uvIndex = faces.get(i++) * 2;
                finalVerts[vi++] = uvs.get(uvIndex++);
                finalVerts[vi++] = uvs.get(uvIndex);
            }
        }
        final int numIndices = numFaces * 3 >= Short.MAX_VALUE ? 0 : numFaces * 3;
        final short[] finalIndices = new short[numIndices];
        // if there are too many vertices in a mesh, we can't use indices
        if (numIndices > 0) {
            for (int i = 0; i < numIndices; i++) {
                finalIndices[i] = (short) i;
            }
        }
        Array<VertexAttribute> attributes = new Array<VertexAttribute>();
        attributes.add(new VertexAttribute(Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE));
        if (hasNorms)
            attributes.add(new VertexAttribute(Usage.Normal, 3, ShaderProgram.NORMAL_ATTRIBUTE));
        if (hasUVs)
            attributes.add(new VertexAttribute(Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE + "0"));
        String stringId = Integer.toString(++id);
        String nodeId = "default".equals(group.name) ? "node" + stringId : group.name;
        String meshId = "default".equals(group.name) ? "mesh" + stringId : group.name;
        String partId = "default".equals(group.name) ? "part" + stringId : group.name;
        ModelNode node = new ModelNode();
        node.id = nodeId;
        node.meshId = meshId;
        node.scale = new Vector3(1, 1, 1);
        node.translation = new Vector3();
        node.rotation = new Quaternion();
        ModelNodePart pm = new ModelNodePart();
        pm.meshPartId = partId;
        pm.materialId = group.materialName;
        node.parts = new ModelNodePart[] { pm };
        ModelMeshPart part = new ModelMeshPart();
        part.id = partId;
        part.indices = finalIndices;
        part.primitiveType = GL20.GL_TRIANGLES;
        ModelMesh mesh = new ModelMesh();
        mesh.id = meshId;
        mesh.attributes = attributes.toArray(VertexAttribute.class);
        mesh.vertices = finalVerts;
        mesh.parts = new ModelMeshPart[] { part };
        data.nodes.add(node);
        data.meshes.add(mesh);
        ModelMaterial mm = mtl.getMaterial(group.materialName);
        data.materials.add(mm);
    }
    // subsequent calls to loadObj
    if (verts.size > 0)
        verts.clear();
    if (norms.size > 0)
        norms.clear();
    if (uvs.size > 0)
        uvs.clear();
    if (groups.size > 0)
        groups.clear();
    return data;
}
Also used : ModelMesh(com.badlogic.gdx.graphics.g3d.model.data.ModelMesh) ModelData(com.badlogic.gdx.graphics.g3d.model.data.ModelData) Quaternion(com.badlogic.gdx.math.Quaternion) VertexAttribute(com.badlogic.gdx.graphics.VertexAttribute) ModelNodePart(com.badlogic.gdx.graphics.g3d.model.data.ModelNodePart) ModelMaterial(com.badlogic.gdx.graphics.g3d.model.data.ModelMaterial) ModelMeshPart(com.badlogic.gdx.graphics.g3d.model.data.ModelMeshPart) InputStreamReader(java.io.InputStreamReader) Vector3(com.badlogic.gdx.math.Vector3) IOException(java.io.IOException) Array(com.badlogic.gdx.utils.Array) FloatArray(com.badlogic.gdx.utils.FloatArray) BufferedReader(java.io.BufferedReader) ModelNode(com.badlogic.gdx.graphics.g3d.model.data.ModelNode)

Example 60 with Array

use of com.badlogic.gdx.utils.Array in project libgdx by libgdx.

the class MtlLoader method load.

/** loads .mtl file */
public void load(FileHandle file) {
    String line;
    String[] tokens;
    String curMatName = "default";
    Color difcolor = Color.WHITE;
    Color speccolor = Color.WHITE;
    float opacity = 1.f;
    float shininess = 0.f;
    String texFilename = null;
    if (file == null || file.exists() == false)
        return;
    BufferedReader reader = new BufferedReader(new InputStreamReader(file.read()), 4096);
    try {
        while ((line = reader.readLine()) != null) {
            if (line.length() > 0 && line.charAt(0) == '\t')
                line = line.substring(1).trim();
            tokens = line.split("\\s+");
            if (tokens[0].length() == 0) {
                continue;
            } else if (tokens[0].charAt(0) == '#')
                continue;
            else {
                final String key = tokens[0].toLowerCase();
                if (key.equals("newmtl")) {
                    ModelMaterial mat = new ModelMaterial();
                    mat.id = curMatName;
                    mat.diffuse = new Color(difcolor);
                    mat.specular = new Color(speccolor);
                    mat.opacity = opacity;
                    mat.shininess = shininess;
                    if (texFilename != null) {
                        ModelTexture tex = new ModelTexture();
                        tex.usage = ModelTexture.USAGE_DIFFUSE;
                        tex.fileName = new String(texFilename);
                        if (mat.textures == null)
                            mat.textures = new Array<ModelTexture>(1);
                        mat.textures.add(tex);
                    }
                    materials.add(mat);
                    if (tokens.length > 1) {
                        curMatName = tokens[1];
                        curMatName = curMatName.replace('.', '_');
                    } else
                        curMatName = "default";
                    difcolor = Color.WHITE;
                    speccolor = Color.WHITE;
                    opacity = 1.f;
                    shininess = 0.f;
                } else if (// diffuse or specular
                key.equals("kd") || key.equals("ks")) {
                    float r = Float.parseFloat(tokens[1]);
                    float g = Float.parseFloat(tokens[2]);
                    float b = Float.parseFloat(tokens[3]);
                    float a = 1;
                    if (tokens.length > 4)
                        a = Float.parseFloat(tokens[4]);
                    if (tokens[0].toLowerCase().equals("kd")) {
                        difcolor = new Color();
                        difcolor.set(r, g, b, a);
                    } else {
                        speccolor = new Color();
                        speccolor.set(r, g, b, a);
                    }
                } else if (key.equals("tr") || key.equals("d")) {
                    opacity = Float.parseFloat(tokens[1]);
                } else if (key.equals("ns")) {
                    shininess = Float.parseFloat(tokens[1]);
                } else if (key.equals("map_kd")) {
                    texFilename = file.parent().child(tokens[1]).path();
                }
            }
        }
        reader.close();
    } catch (IOException e) {
        return;
    }
    // last material
    ModelMaterial mat = new ModelMaterial();
    mat.id = curMatName;
    mat.diffuse = new Color(difcolor);
    mat.specular = new Color(speccolor);
    mat.opacity = opacity;
    mat.shininess = shininess;
    if (texFilename != null) {
        ModelTexture tex = new ModelTexture();
        tex.usage = ModelTexture.USAGE_DIFFUSE;
        tex.fileName = new String(texFilename);
        if (mat.textures == null)
            mat.textures = new Array<ModelTexture>(1);
        mat.textures.add(tex);
    }
    materials.add(mat);
    return;
}
Also used : Array(com.badlogic.gdx.utils.Array) FloatArray(com.badlogic.gdx.utils.FloatArray) InputStreamReader(java.io.InputStreamReader) Color(com.badlogic.gdx.graphics.Color) BufferedReader(java.io.BufferedReader) ModelMaterial(com.badlogic.gdx.graphics.g3d.model.data.ModelMaterial) IOException(java.io.IOException) ModelTexture(com.badlogic.gdx.graphics.g3d.model.data.ModelTexture)

Aggregations

Array (com.badlogic.gdx.utils.Array)67 FileHandle (com.badlogic.gdx.files.FileHandle)18 GdxRuntimeException (com.badlogic.gdx.utils.GdxRuntimeException)16 AssetDescriptor (com.badlogic.gdx.assets.AssetDescriptor)9 Texture (com.badlogic.gdx.graphics.Texture)8 TextureAtlas (com.badlogic.gdx.graphics.g2d.TextureAtlas)7 IntArray (com.badlogic.gdx.utils.IntArray)7 Element (com.badlogic.gdx.utils.XmlReader.Element)7 IOException (java.io.IOException)7 BitmapFont (com.badlogic.gdx.graphics.g2d.BitmapFont)5 TextureRegion (com.badlogic.gdx.graphics.g2d.TextureRegion)5 JsonValue (com.badlogic.gdx.utils.JsonValue)5 ObjectMap (com.badlogic.gdx.utils.ObjectMap)5 Color (com.badlogic.gdx.graphics.Color)4 ModelMaterial (com.badlogic.gdx.graphics.g3d.model.data.ModelMaterial)4 Page (com.badlogic.gdx.tools.texturepacker.TexturePacker.Page)4 Rect (com.badlogic.gdx.tools.texturepacker.TexturePacker.Rect)4 Json (com.badlogic.gdx.utils.Json)4 TextureParameter (com.badlogic.gdx.assets.loaders.TextureLoader.TextureParameter)3 GwtFileHandle (com.badlogic.gdx.backends.gwt.GwtFileHandle)3