Search in sources :

Example 16 with AssetInfo

use of com.jme3.asset.AssetInfo in project jmonkeyengine by jMonkeyEngine.

the class SceneWithAnimationLoader method load.

@Override
public Object load(AssetInfo assetInfo) throws IOException {
    AssetKey<?> key = assetInfo.getKey();
    if (!(key instanceof ModelKey))
        throw new AssetLoadException("Invalid asset key");
    InputStream stream = assetInfo.openStream();
    Scanner scanner = new Scanner(stream);
    AnimationList animList = new AnimationList();
    String modelName = null;
    try {
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.startsWith("#"))
                continue;
            if (modelName == null) {
                modelName = line;
                continue;
            }
            String[] split = split(line);
            if (split.length < 3)
                throw new IOException("Unparseable string \"" + line + "\"");
            int start;
            int end;
            try {
                start = Integer.parseInt(split[0]);
                end = Integer.parseInt(split[1]);
            } catch (NumberFormatException e) {
                throw new IOException("Unparseable string \"" + line + "\"", e);
            }
            animList.add(split[2], split.length > 3 ? split[3] : null, start, end);
        }
    } finally {
        scanner.close();
        stream.close();
    }
    return assetInfo.getManager().loadAsset(new SceneKey(key.getFolder() + modelName, animList));
}
Also used : Scanner(java.util.Scanner) ModelKey(com.jme3.asset.ModelKey) InputStream(java.io.InputStream) IOException(java.io.IOException) AssetLoadException(com.jme3.asset.AssetLoadException)

Example 17 with AssetInfo

use of com.jme3.asset.AssetInfo in project jmonkeyengine by jMonkeyEngine.

the class TextureHelper method loadImageFromFile.

/**
     * This method loads the textre from outside the blend file using the
     * AssetManager that the blend file was loaded with. It returns a texture
     * with a full assetKey that references the original texture so it later
     * doesn't need to ba packed when the model data is serialized. It searches
     * the AssetManager for the full path if the model file is a relative path
     * and will attempt to truncate the path if it is an absolute file path
     * until the path can be found in the AssetManager. If the texture can not
     * be found, it will issue a load attempt for the initial path anyway so the
     * failed load can be reported by the AssetManagers callback methods for
     * failed assets.
     * 
     * @param name
     *            the path to the image
     * @param imaflag
     *            the image flag
     * @param blenderContext
     *            the blender context
     * @return the loaded image or null if the image cannot be found
     */
protected Texture loadImageFromFile(String name, int imaflag, BlenderContext blenderContext) {
    if (!name.contains(".")) {
        // no extension means not a valid image
        return null;
    }
    // decide if the mipmaps will be generated
    boolean generateMipmaps = false;
    switch(blenderContext.getBlenderKey().getMipmapGenerationMethod()) {
        case ALWAYS_GENERATE:
            generateMipmaps = true;
            break;
        case NEVER_GENERATE:
            break;
        case GENERATE_WHEN_NEEDED:
            generateMipmaps = (imaflag & 0x04) != 0;
            break;
        default:
            throw new IllegalStateException("Unknown mipmap generation method: " + blenderContext.getBlenderKey().getMipmapGenerationMethod());
    }
    AssetManager assetManager = blenderContext.getAssetManager();
    name = name.replace('\\', '/');
    Texture result = null;
    if (name.startsWith("//")) {
        // This is a relative path, so try to find it relative to the .blend file
        String relativePath = name.substring(2);
        // Augument the path with blender key path
        BlenderKey blenderKey = blenderContext.getBlenderKey();
        int idx = blenderKey.getName().lastIndexOf('/');
        String blenderAssetFolder = blenderKey.getName().substring(0, idx != -1 ? idx : 0);
        String absoluteName = blenderAssetFolder + '/' + relativePath;
        // Directly try to load texture so AssetManager can report missing textures
        try {
            TextureKey key = new TextureKey(absoluteName);
            key.setFlipY(true);
            key.setGenerateMips(generateMipmaps);
            result = assetManager.loadTexture(key);
            result.setKey(key);
        } catch (AssetNotFoundException | AssetLoadException e) {
            LOGGER.fine(e.getLocalizedMessage());
        }
    } else {
        // This is a full path, try to truncate it until the file can be found
        // this works as the assetManager root is most probably a part of the
        // image path. E.g. AssetManager has a locator at c:/Files/ and the
        // texture path is c:/Files/Textures/Models/Image.jpg.
        // For this we create a list with every possible full path name from
        // the asset name to the root. Image.jpg, Models/Image.jpg,
        // Textures/Models/Image.jpg (bingo) etc.
        List<String> assetNames = new ArrayList<String>();
        String[] paths = name.split("\\/");
        // the asset name
        StringBuilder sb = new StringBuilder(paths[paths.length - 1]);
        assetNames.add(paths[paths.length - 1]);
        for (int i = paths.length - 2; i >= 0; --i) {
            sb.insert(0, '/');
            sb.insert(0, paths[i]);
            assetNames.add(0, sb.toString());
        }
        // Now try to locate the asset
        for (String assetName : assetNames) {
            try {
                TextureKey key = new TextureKey(assetName);
                key.setFlipY(true);
                key.setGenerateMips(generateMipmaps);
                AssetInfo info = assetManager.locateAsset(key);
                if (info != null) {
                    Texture texture = assetManager.loadTexture(key);
                    result = texture;
                    // Set key explicitly here if other ways fail
                    texture.setKey(key);
                    // If texture is found return it;
                    return result;
                }
            } catch (AssetNotFoundException | AssetLoadException e) {
                LOGGER.fine(e.getLocalizedMessage());
            }
        }
        // the missing asset to subsystems.
        try {
            TextureKey key = new TextureKey(name);
            assetManager.loadTexture(key);
        } catch (AssetNotFoundException | AssetLoadException e) {
            LOGGER.fine(e.getLocalizedMessage());
        }
    }
    return result;
}
Also used : AssetManager(com.jme3.asset.AssetManager) ArrayList(java.util.ArrayList) AssetNotFoundException(com.jme3.asset.AssetNotFoundException) AssetInfo(com.jme3.asset.AssetInfo) Texture(com.jme3.texture.Texture) AssetLoadException(com.jme3.asset.AssetLoadException) GeneratedTextureKey(com.jme3.asset.GeneratedTextureKey) TextureKey(com.jme3.asset.TextureKey) BlenderKey(com.jme3.asset.BlenderKey)

Example 18 with AssetInfo

use of com.jme3.asset.AssetInfo in project jmonkeyengine by jMonkeyEngine.

the class DDSLoader method load.

public Object load(AssetInfo info) throws IOException {
    if (!(info.getKey() instanceof TextureKey)) {
        throw new IllegalArgumentException("Texture assets must be loaded using a TextureKey");
    }
    InputStream stream = null;
    try {
        stream = info.openStream();
        in = new LittleEndien(stream);
        loadHeader();
        if (texture3D) {
            ((TextureKey) info.getKey()).setTextureTypeHint(Texture.Type.ThreeDimensional);
        } else if (depth > 1) {
            ((TextureKey) info.getKey()).setTextureTypeHint(Texture.Type.CubeMap);
        }
        ArrayList<ByteBuffer> data = readData(((TextureKey) info.getKey()).isFlipY());
        return new Image(pixelFormat, width, height, depth, data, sizes, ColorSpace.sRGB);
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}
Also used : TextureKey(com.jme3.asset.TextureKey) InputStream(java.io.InputStream) Image(com.jme3.texture.Image) ByteBuffer(java.nio.ByteBuffer) LittleEndien(com.jme3.util.LittleEndien)

Example 19 with AssetInfo

use of com.jme3.asset.AssetInfo in project jmonkeyengine by jMonkeyEngine.

the class BlenderLoader method load.

@Override
public Spatial load(AssetInfo assetInfo) throws IOException {
    try {
        BlenderContext blenderContext = this.setup(assetInfo);
        AnimationHelper animationHelper = blenderContext.getHelper(AnimationHelper.class);
        animationHelper.loadAnimations();
        BlenderKey blenderKey = blenderContext.getBlenderKey();
        LoadedFeatures loadedFeatures = new LoadedFeatures();
        for (FileBlockHeader block : blenderContext.getBlocks()) {
            switch(block.getCode()) {
                case BLOCK_OB00:
                    ObjectHelper objectHelper = blenderContext.getHelper(ObjectHelper.class);
                    Node object = (Node) objectHelper.toObject(block.getStructure(blenderContext), blenderContext);
                    if (LOGGER.isLoggable(Level.FINE)) {
                        LOGGER.log(Level.FINE, "{0}: {1}--> {2}", new Object[] { object.getName(), object.getLocalTranslation().toString(), object.getParent() == null ? "null" : object.getParent().getName() });
                    }
                    if (object.getParent() == null) {
                        loadedFeatures.objects.add(object);
                    }
                    if (object instanceof LightNode && ((LightNode) object).getLight() != null) {
                        loadedFeatures.lights.add(((LightNode) object).getLight());
                    } else if (object instanceof CameraNode && ((CameraNode) object).getCamera() != null) {
                        loadedFeatures.cameras.add(((CameraNode) object).getCamera());
                    }
                    break;
                case // Scene
                BLOCK_SC00:
                    loadedFeatures.sceneBlocks.add(block);
                    break;
                case // Material
                BLOCK_MA00:
                    MaterialHelper materialHelper = blenderContext.getHelper(MaterialHelper.class);
                    MaterialContext materialContext = materialHelper.toMaterialContext(block.getStructure(blenderContext), blenderContext);
                    loadedFeatures.materials.add(materialContext);
                    break;
                case // Mesh
                BLOCK_ME00:
                    MeshHelper meshHelper = blenderContext.getHelper(MeshHelper.class);
                    TemporalMesh temporalMesh = meshHelper.toTemporalMesh(block.getStructure(blenderContext), blenderContext);
                    loadedFeatures.meshes.add(temporalMesh);
                    break;
                case // Image
                BLOCK_IM00:
                    TextureHelper textureHelper = blenderContext.getHelper(TextureHelper.class);
                    Texture image = textureHelper.loadImageAsTexture(block.getStructure(blenderContext), 0, blenderContext);
                    if (image != null && image.getImage() != null) {
                        // render results are stored as images but are not being loaded
                        loadedFeatures.images.add(image);
                    }
                    break;
                case BLOCK_TE00:
                    Structure textureStructure = block.getStructure(blenderContext);
                    int type = ((Number) textureStructure.getFieldValue("type")).intValue();
                    if (type == TextureHelper.TEX_IMAGE) {
                        TextureHelper texHelper = blenderContext.getHelper(TextureHelper.class);
                        Texture texture = texHelper.getTexture(textureStructure, null, blenderContext);
                        if (texture != null) {
                            // null is returned when texture has no image
                            loadedFeatures.textures.add(texture);
                        }
                    } else {
                        LOGGER.fine("Only image textures can be loaded as unlinked assets. Generated textures will be applied to an existing object.");
                    }
                    break;
                case // World
                BLOCK_WO00:
                    LandscapeHelper landscapeHelper = blenderContext.getHelper(LandscapeHelper.class);
                    Structure worldStructure = block.getStructure(blenderContext);
                    String worldName = worldStructure.getName();
                    if (blenderKey.getUsedWorld() == null || blenderKey.getUsedWorld().equals(worldName)) {
                        Light ambientLight = landscapeHelper.toAmbientLight(worldStructure);
                        if (ambientLight != null) {
                            loadedFeatures.objects.add(new LightNode(null, ambientLight));
                            loadedFeatures.lights.add(ambientLight);
                        }
                        loadedFeatures.sky = landscapeHelper.toSky(worldStructure);
                        loadedFeatures.backgroundColor = landscapeHelper.toBackgroundColor(worldStructure);
                        Filter fogFilter = landscapeHelper.toFog(worldStructure);
                        if (fogFilter != null) {
                            loadedFeatures.filters.add(landscapeHelper.toFog(worldStructure));
                        }
                    }
                    break;
                case BLOCK_AC00:
                    LOGGER.fine("Loading unlinked animations is not yet supported!");
                    break;
                default:
                    LOGGER.log(Level.FINEST, "Ommiting the block: {0}.", block.getCode());
            }
        }
        LOGGER.fine("Baking constraints after every feature is loaded.");
        ConstraintHelper constraintHelper = blenderContext.getHelper(ConstraintHelper.class);
        constraintHelper.bakeConstraints(blenderContext);
        LOGGER.fine("Loading scenes and attaching them to the root object.");
        for (FileBlockHeader sceneBlock : loadedFeatures.sceneBlocks) {
            loadedFeatures.scenes.add(this.toScene(sceneBlock.getStructure(blenderContext), blenderContext));
        }
        LOGGER.fine("Creating the root node of the model and applying loaded nodes of the scene and loaded features to it.");
        Node modelRoot = new Node(blenderKey.getName());
        for (Node scene : loadedFeatures.scenes) {
            modelRoot.attachChild(scene);
        }
        if (blenderKey.isLoadUnlinkedAssets()) {
            LOGGER.fine("Setting loaded content as user data in resulting sptaial.");
            Map<String, Map<String, Object>> linkedData = new HashMap<String, Map<String, Object>>();
            Map<String, Object> thisFileData = new HashMap<String, Object>();
            thisFileData.put("scenes", loadedFeatures.scenes == null ? new ArrayList<Object>() : loadedFeatures.scenes);
            thisFileData.put("objects", loadedFeatures.objects == null ? new ArrayList<Object>() : loadedFeatures.objects);
            thisFileData.put("meshes", loadedFeatures.meshes == null ? new ArrayList<Object>() : loadedFeatures.meshes);
            thisFileData.put("materials", loadedFeatures.materials == null ? new ArrayList<Object>() : loadedFeatures.materials);
            thisFileData.put("textures", loadedFeatures.textures == null ? new ArrayList<Object>() : loadedFeatures.textures);
            thisFileData.put("images", loadedFeatures.images == null ? new ArrayList<Object>() : loadedFeatures.images);
            thisFileData.put("animations", loadedFeatures.animations == null ? new ArrayList<Object>() : loadedFeatures.animations);
            thisFileData.put("cameras", loadedFeatures.cameras == null ? new ArrayList<Object>() : loadedFeatures.cameras);
            thisFileData.put("lights", loadedFeatures.lights == null ? new ArrayList<Object>() : loadedFeatures.lights);
            thisFileData.put("filters", loadedFeatures.filters == null ? new ArrayList<Object>() : loadedFeatures.filters);
            thisFileData.put("backgroundColor", loadedFeatures.backgroundColor);
            thisFileData.put("sky", loadedFeatures.sky);
            linkedData.put("this", thisFileData);
            linkedData.putAll(blenderContext.getLinkedFeatures());
            modelRoot.setUserData("linkedData", linkedData);
        }
        return modelRoot;
    } catch (BlenderFileException e) {
        throw new IOException(e.getLocalizedMessage(), e);
    } catch (Exception e) {
        throw new IOException("Unexpected importer exception occured: " + e.getLocalizedMessage(), e);
    } finally {
        this.clear(assetInfo);
    }
}
Also used : HashMap(java.util.HashMap) LightNode(com.jme3.scene.LightNode) Node(com.jme3.scene.Node) CameraNode(com.jme3.scene.CameraNode) CameraNode(com.jme3.scene.CameraNode) ArrayList(java.util.ArrayList) Texture(com.jme3.texture.Texture) LandscapeHelper(com.jme3.scene.plugins.blender.landscape.LandscapeHelper) LightNode(com.jme3.scene.LightNode) Light(com.jme3.light.Light) TextureHelper(com.jme3.scene.plugins.blender.textures.TextureHelper) BlenderKey(com.jme3.asset.BlenderKey) Structure(com.jme3.scene.plugins.blender.file.Structure) ObjectHelper(com.jme3.scene.plugins.blender.objects.ObjectHelper) AnimationHelper(com.jme3.scene.plugins.blender.animations.AnimationHelper) FileBlockHeader(com.jme3.scene.plugins.blender.file.FileBlockHeader) BlenderFileException(com.jme3.scene.plugins.blender.file.BlenderFileException) IOException(java.io.IOException) ConstraintHelper(com.jme3.scene.plugins.blender.constraints.ConstraintHelper) BlenderFileException(com.jme3.scene.plugins.blender.file.BlenderFileException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) TemporalMesh(com.jme3.scene.plugins.blender.meshes.TemporalMesh) Filter(com.jme3.post.Filter) MaterialHelper(com.jme3.scene.plugins.blender.materials.MaterialHelper) MaterialContext(com.jme3.scene.plugins.blender.materials.MaterialContext) HashMap(java.util.HashMap) Map(java.util.Map) MeshHelper(com.jme3.scene.plugins.blender.meshes.MeshHelper)

Example 20 with AssetInfo

use of com.jme3.asset.AssetInfo in project jmonkeyengine by jMonkeyEngine.

the class NativeVorbisLoader method loadStream.

private static AudioStream loadStream(AssetInfo assetInfo) throws IOException {
    AndroidAssetInfo aai = (AndroidAssetInfo) assetInfo;
    AssetFileDescriptor afd = null;
    NativeVorbisFile file = null;
    boolean success = false;
    try {
        afd = aai.openFileDescriptor();
        int fd = afd.getParcelFileDescriptor().getFd();
        file = new NativeVorbisFile(fd, afd.getStartOffset(), afd.getLength());
        AudioStream stream = new AudioStream();
        stream.setupFormat(file.channels, 16, file.sampleRate);
        stream.updateData(new VorbisInputStream(afd, file), file.duration);
        success = true;
        return stream;
    } finally {
        if (!success) {
            if (file != null) {
                file.close();
            }
            if (afd != null) {
                afd.close();
            }
        }
    }
}
Also used : AudioStream(com.jme3.audio.AudioStream) AssetFileDescriptor(android.content.res.AssetFileDescriptor) AndroidAssetInfo(com.jme3.asset.plugins.AndroidLocator.AndroidAssetInfo)

Aggregations

InputStream (java.io.InputStream)17 TextureKey (com.jme3.asset.TextureKey)12 IOException (java.io.IOException)9 Image (com.jme3.texture.Image)7 AssetInfo (com.jme3.asset.AssetInfo)6 Texture (com.jme3.texture.Texture)6 AssetLoadException (com.jme3.asset.AssetLoadException)5 Test (org.junit.Test)5 AssetKey (com.jme3.asset.AssetKey)4 AssetNotFoundException (com.jme3.asset.AssetNotFoundException)4 ModelKey (com.jme3.asset.ModelKey)4 InputStreamReader (java.io.InputStreamReader)4 BlenderKey (com.jme3.asset.BlenderKey)3 AudioStream (com.jme3.audio.AudioStream)3 MaterialDef (com.jme3.material.MaterialDef)3 DataInputStream (java.io.DataInputStream)3 AssetFileDescriptor (android.content.res.AssetFileDescriptor)2 AssetManager (com.jme3.asset.AssetManager)2 AndroidAssetInfo (com.jme3.asset.plugins.AndroidLocator.AndroidAssetInfo)2 AudioBuffer (com.jme3.audio.AudioBuffer)2