Search in sources :

Example 1 with TextureHelper

use of com.jme3.scene.plugins.blender.textures.TextureHelper 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 2 with TextureHelper

use of com.jme3.scene.plugins.blender.textures.TextureHelper in project jmonkeyengine by jMonkeyEngine.

the class LandscapeHelper method toSky.

/**
     * Loads scene's sky. Sky can be plain or textured.
     * If no sky type is selected in blender then no sky is loaded.
     * @param worldStructure
     *            the world's structure
     * @return the scene's sky
     * @throws BlenderFileException
     *             blender exception is thrown when problems with blender file occur
     */
public Spatial toSky(Structure worldStructure) throws BlenderFileException {
    int skytype = ((Number) worldStructure.getFieldValue("skytype")).intValue();
    if (skytype == 0) {
        return null;
    }
    LOGGER.fine("Loading sky.");
    ColorRGBA horizontalColor = this.toBackgroundColor(worldStructure);
    float zenr = ((Number) worldStructure.getFieldValue("zenr")).floatValue();
    float zeng = ((Number) worldStructure.getFieldValue("zeng")).floatValue();
    float zenb = ((Number) worldStructure.getFieldValue("zenb")).floatValue();
    ColorRGBA zenithColor = new ColorRGBA(zenr, zeng, zenb, 1);
    // jutr for this case load generated textures wheather user had set it or not because those might be needed to properly load the sky
    boolean loadGeneratedTextures = blenderContext.getBlenderKey().isLoadGeneratedTextures();
    blenderContext.getBlenderKey().setLoadGeneratedTextures(true);
    TextureHelper textureHelper = blenderContext.getHelper(TextureHelper.class);
    List<CombinedTexture> loadedTextures = null;
    try {
        loadedTextures = textureHelper.readTextureData(worldStructure, new float[] { horizontalColor.r, horizontalColor.g, horizontalColor.b, horizontalColor.a }, true);
    } finally {
        blenderContext.getBlenderKey().setLoadGeneratedTextures(loadGeneratedTextures);
    }
    TextureCubeMap texture = null;
    if (loadedTextures != null && loadedTextures.size() > 0) {
        if (loadedTextures.size() > 1) {
            throw new IllegalStateException("There should be only one combined texture for sky!");
        }
        CombinedTexture combinedTexture = loadedTextures.get(0);
        texture = combinedTexture.generateSkyTexture(horizontalColor, zenithColor, blenderContext);
    } else {
        LOGGER.fine("Preparing colors for colorband.");
        int colorbandType = ColorBand.IPO_CARDINAL;
        List<ColorRGBA> colorbandColors = new ArrayList<ColorRGBA>(3);
        colorbandColors.add(horizontalColor);
        if ((skytype & SKYTYPE_BLEND) != 0) {
            if ((skytype & SKYTYPE_PAPER) != 0) {
                colorbandType = ColorBand.IPO_LINEAR;
            }
            if ((skytype & SKYTYPE_REAL) != 0) {
                colorbandColors.add(0, zenithColor);
            }
            colorbandColors.add(zenithColor);
        }
        int size = blenderContext.getBlenderKey().getSkyGeneratedTextureSize();
        List<Integer> positions = new ArrayList<Integer>(colorbandColors.size());
        positions.add(0);
        if (colorbandColors.size() == 2) {
            positions.add(size - 1);
        } else if (colorbandColors.size() == 3) {
            positions.add(size / 2);
            positions.add(size - 1);
        }
        LOGGER.fine("Generating sky texture.");
        float[][] values = new ColorBand(colorbandType, colorbandColors, positions, size).computeValues();
        Image image = ImageUtils.createEmptyImage(Format.RGB8, size, size, 6);
        PixelInputOutput pixelIO = PixelIOFactory.getPixelIO(image.getFormat());
        TexturePixel pixel = new TexturePixel();
        LOGGER.fine("Creating side textures.");
        int[] sideImagesIndexes = new int[] { 0, 1, 4, 5 };
        for (int i : sideImagesIndexes) {
            for (int y = 0; y < size; ++y) {
                pixel.red = values[y][0];
                pixel.green = values[y][1];
                pixel.blue = values[y][2];
                for (int x = 0; x < size; ++x) {
                    pixelIO.write(image, i, pixel, x, y);
                }
            }
        }
        LOGGER.fine("Creating top texture.");
        pixelIO.read(image, 0, pixel, 0, image.getHeight() - 1);
        for (int y = 0; y < size; ++y) {
            for (int x = 0; x < size; ++x) {
                pixelIO.write(image, 3, pixel, x, y);
            }
        }
        LOGGER.fine("Creating bottom texture.");
        pixelIO.read(image, 0, pixel, 0, 0);
        for (int y = 0; y < size; ++y) {
            for (int x = 0; x < size; ++x) {
                pixelIO.write(image, 2, pixel, x, y);
            }
        }
        texture = new TextureCubeMap(image);
    }
    LOGGER.fine("Sky texture created. Creating sky.");
    return SkyFactory.createSky(blenderContext.getAssetManager(), texture, SkyFactory.EnvMapType.CubeMap);
}
Also used : ColorBand(com.jme3.scene.plugins.blender.textures.ColorBand) ArrayList(java.util.ArrayList) Image(com.jme3.texture.Image) PixelInputOutput(com.jme3.scene.plugins.blender.textures.io.PixelInputOutput) ColorRGBA(com.jme3.math.ColorRGBA) TextureCubeMap(com.jme3.texture.TextureCubeMap) TextureHelper(com.jme3.scene.plugins.blender.textures.TextureHelper) TexturePixel(com.jme3.scene.plugins.blender.textures.TexturePixel) CombinedTexture(com.jme3.scene.plugins.blender.textures.CombinedTexture)

Example 3 with TextureHelper

use of com.jme3.scene.plugins.blender.textures.TextureHelper in project jmonkeyengine by jMonkeyEngine.

the class TriangulatedTexture method castToUVS.

/**
     * This method alters the images to fit them into UV coordinates of the
     * given target texture.
     * 
     * @param targetTexture
     *            the texture to whose UV coordinates we fit current images
     * @param blenderContext
     *            the blender context
     */
public void castToUVS(TriangulatedTexture targetTexture, BlenderContext blenderContext) {
    int[] sourceSize = new int[2], targetSize = new int[2];
    ImageLoader imageLoader = new ImageLoader();
    TextureHelper textureHelper = blenderContext.getHelper(TextureHelper.class);
    for (TriangleTextureElement entry : faceTextures) {
        TriangleTextureElement targetFaceTextureElement = targetTexture.getFaceTextureElement(entry.faceIndex);
        Vector2f[] dest = targetFaceTextureElement.uv;
        // get the sizes of the source and target images
        sourceSize[0] = entry.image.getWidth();
        sourceSize[1] = entry.image.getHeight();
        targetSize[0] = targetFaceTextureElement.image.getWidth();
        targetSize[1] = targetFaceTextureElement.image.getHeight();
        // create triangle transformation
        AffineTransform affineTransform = textureHelper.createAffineTransform(entry.uv, dest, sourceSize, targetSize);
        // compute the result texture
        BufferedImage sourceImage = ImageToAwt.convert(entry.image, false, true, 0);
        BufferedImage targetImage = new BufferedImage(targetSize[0], targetSize[1], sourceImage.getType());
        Graphics2D g = targetImage.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.drawImage(sourceImage, affineTransform, null);
        g.dispose();
        Image output = imageLoader.load(targetImage, false);
        entry.image = output;
        entry.uv[0].set(dest[0]);
        entry.uv[1].set(dest[1]);
        entry.uv[2].set(dest[2]);
    }
}
Also used : Vector2f(com.jme3.math.Vector2f) AffineTransform(java.awt.geom.AffineTransform) Image(com.jme3.texture.Image) BufferedImage(java.awt.image.BufferedImage) BufferedImage(java.awt.image.BufferedImage) Graphics2D(java.awt.Graphics2D)

Example 4 with TextureHelper

use of com.jme3.scene.plugins.blender.textures.TextureHelper in project jmonkeyengine by jMonkeyEngine.

the class BlenderLoader method setup.

/**
     * This method sets up the loader.
     * @param assetInfo
     *            the asset info
     * @throws BlenderFileException
     *             an exception is throw when something wrong happens with blender file
     */
protected BlenderContext setup(AssetInfo assetInfo) throws BlenderFileException {
    // registering loaders
    ModelKey modelKey = (ModelKey) assetInfo.getKey();
    BlenderKey blenderKey;
    if (modelKey instanceof BlenderKey) {
        blenderKey = (BlenderKey) modelKey;
    } else {
        blenderKey = new BlenderKey(modelKey.getName());
    }
    // opening stream
    BlenderInputStream inputStream = new BlenderInputStream(assetInfo.openStream());
    // reading blocks
    List<FileBlockHeader> blocks = new ArrayList<FileBlockHeader>();
    FileBlockHeader fileBlock;
    BlenderContext blenderContext = new BlenderContext();
    blenderContext.setBlenderVersion(inputStream.getVersionNumber());
    blenderContext.setAssetManager(assetInfo.getManager());
    blenderContext.setInputStream(inputStream);
    blenderContext.setBlenderKey(blenderKey);
    // creating helpers
    blenderContext.putHelper(AnimationHelper.class, new AnimationHelper(inputStream.getVersionNumber(), blenderContext));
    blenderContext.putHelper(TextureHelper.class, new TextureHelper(inputStream.getVersionNumber(), blenderContext));
    blenderContext.putHelper(MeshHelper.class, new MeshHelper(inputStream.getVersionNumber(), blenderContext));
    blenderContext.putHelper(ObjectHelper.class, new ObjectHelper(inputStream.getVersionNumber(), blenderContext));
    blenderContext.putHelper(CurvesHelper.class, new CurvesHelper(inputStream.getVersionNumber(), blenderContext));
    blenderContext.putHelper(LightHelper.class, new LightHelper(inputStream.getVersionNumber(), blenderContext));
    blenderContext.putHelper(CameraHelper.class, new CameraHelper(inputStream.getVersionNumber(), blenderContext));
    blenderContext.putHelper(ModifierHelper.class, new ModifierHelper(inputStream.getVersionNumber(), blenderContext));
    blenderContext.putHelper(MaterialHelper.class, new MaterialHelper(inputStream.getVersionNumber(), blenderContext));
    blenderContext.putHelper(ConstraintHelper.class, new ConstraintHelper(inputStream.getVersionNumber(), blenderContext));
    blenderContext.putHelper(ParticlesHelper.class, new ParticlesHelper(inputStream.getVersionNumber(), blenderContext));
    blenderContext.putHelper(LandscapeHelper.class, new LandscapeHelper(inputStream.getVersionNumber(), blenderContext));
    // reading the blocks (dna block is automatically saved in the blender context when found)
    FileBlockHeader sceneFileBlock = null;
    do {
        fileBlock = new FileBlockHeader(inputStream, blenderContext);
        if (!fileBlock.isDnaBlock()) {
            blocks.add(fileBlock);
            // save the scene's file block
            if (fileBlock.getCode() == BlockCode.BLOCK_SC00) {
                sceneFileBlock = fileBlock;
            }
        }
    } while (!fileBlock.isLastBlock());
    if (sceneFileBlock != null) {
        blenderContext.setSceneStructure(sceneFileBlock.getStructure(blenderContext));
    }
    // adding locator for linked content
    assetInfo.getManager().registerLocator(assetInfo.getKey().getName(), LinkedContentLocator.class);
    return blenderContext;
}
Also used : ObjectHelper(com.jme3.scene.plugins.blender.objects.ObjectHelper) AnimationHelper(com.jme3.scene.plugins.blender.animations.AnimationHelper) ModelKey(com.jme3.asset.ModelKey) FileBlockHeader(com.jme3.scene.plugins.blender.file.FileBlockHeader) ArrayList(java.util.ArrayList) ConstraintHelper(com.jme3.scene.plugins.blender.constraints.ConstraintHelper) ModifierHelper(com.jme3.scene.plugins.blender.modifiers.ModifierHelper) LandscapeHelper(com.jme3.scene.plugins.blender.landscape.LandscapeHelper) CurvesHelper(com.jme3.scene.plugins.blender.curves.CurvesHelper) TextureHelper(com.jme3.scene.plugins.blender.textures.TextureHelper) MaterialHelper(com.jme3.scene.plugins.blender.materials.MaterialHelper) BlenderKey(com.jme3.asset.BlenderKey) BlenderInputStream(com.jme3.scene.plugins.blender.file.BlenderInputStream) ParticlesHelper(com.jme3.scene.plugins.blender.particles.ParticlesHelper) LightHelper(com.jme3.scene.plugins.blender.lights.LightHelper) MeshHelper(com.jme3.scene.plugins.blender.meshes.MeshHelper) CameraHelper(com.jme3.scene.plugins.blender.cameras.CameraHelper)

Aggregations

TextureHelper (com.jme3.scene.plugins.blender.textures.TextureHelper)3 ArrayList (java.util.ArrayList)3 BlenderKey (com.jme3.asset.BlenderKey)2 AnimationHelper (com.jme3.scene.plugins.blender.animations.AnimationHelper)2 ConstraintHelper (com.jme3.scene.plugins.blender.constraints.ConstraintHelper)2 FileBlockHeader (com.jme3.scene.plugins.blender.file.FileBlockHeader)2 LandscapeHelper (com.jme3.scene.plugins.blender.landscape.LandscapeHelper)2 MaterialHelper (com.jme3.scene.plugins.blender.materials.MaterialHelper)2 MeshHelper (com.jme3.scene.plugins.blender.meshes.MeshHelper)2 ObjectHelper (com.jme3.scene.plugins.blender.objects.ObjectHelper)2 Image (com.jme3.texture.Image)2 ModelKey (com.jme3.asset.ModelKey)1 Light (com.jme3.light.Light)1 ColorRGBA (com.jme3.math.ColorRGBA)1 Vector2f (com.jme3.math.Vector2f)1 Filter (com.jme3.post.Filter)1 CameraNode (com.jme3.scene.CameraNode)1 LightNode (com.jme3.scene.LightNode)1 Node (com.jme3.scene.Node)1 CameraHelper (com.jme3.scene.plugins.blender.cameras.CameraHelper)1