Java Code Examples for com.jme3.texture.Texture#getImage()

The following examples show how to use com.jme3.texture.Texture#getImage() . 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: LwjglRenderer.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void updateRenderTexture(FrameBuffer fb, RenderBuffer rb) {
    Texture tex = rb.getTexture();
    Image image = tex.getImage();
    if (image.isUpdateNeeded()) {
        updateTexImageData(image, tex.getType(), tex.getMinFilter().usesMipMapLevels(), 0);

        // NOTE: For depth textures, sets nearest/no-mips mode
        // Required to fix "framebuffer unsupported"
        // for old NVIDIA drivers!
        setupTextureParams(tex);
    }

    glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,
            convertAttachmentSlot(rb.getSlot()),
            convertTextureType(tex.getType(), image.getMultiSamples()),
            image.getId(),
            0);
}
 
Example 2
Source File: OGLESShaderRenderer.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void updateRenderTexture(FrameBuffer fb, RenderBuffer rb) {
        Texture tex = rb.getTexture();
        Image image = tex.getImage();
        if (image.isUpdateNeeded()) {
            updateTexImageData(image, tex.getType(), false);

            // NOTE: For depth textures, sets nearest/no-mips mode
            // Required to fix "framebuffer unsupported"
            // for old NVIDIA drivers!
            setupTextureParams(tex);
        }

        GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER,
                convertAttachmentSlot(rb.getSlot()),
                convertTextureType(tex.getType()),
                image.getId(),
                0);

//        RendererUtil.checkGLError();
    }
 
Example 3
Source File: MaterialUtils.java    From jmonkeybuilder with Apache License 2.0 6 votes vote down vote up
/**
 * Save if need a texture.
 *
 * @param texture the texture.
 */
@FromAnyThread
private static void saveIfNeedTexture(@NotNull Texture texture) {

    var image = texture.getImage();
    if (!image.isChanged()) {
        return;
    }

    var key = texture.getKey();
    var file = notNull(getRealFile(key.getName()));
    var bufferedImage = ImageToAwt.convert(image, false, true, 0);

    try (var out = Files.newOutputStream(file, WRITE, TRUNCATE_EXISTING, CREATE)) {
        ImageIO.write(bufferedImage, "png", out);
    } catch (IOException e) {
        e.printStackTrace();
    }

    image.clearChanges();
}
 
Example 4
Source File: ImageBasedHeightMapGrid.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public HeightMap getHeightMapAt(Vector3f location) {
    // HEIGHTMAP image (for the terrain heightmap)
    int x = (int) location.x;
    int z = (int) location.z;
    
    AbstractHeightMap heightmap = null;
    //BufferedImage im = null;
    
    try {
        String name = namer.getName(x, z);
        logger.log(Level.FINE, "Loading heightmap from file: {0}", name);
        final Texture texture = assetManager.loadTexture(new TextureKey(name));
        
        // CREATE HEIGHTMAP
        heightmap = new ImageBasedHeightMap(texture.getImage());
        
        heightmap.setHeightScale(1);
        heightmap.load();
    
    } catch (AssetNotFoundException e) {
        logger.log(Level.SEVERE, "Asset Not found! ", e);
    }
    return heightmap;
}
 
Example 5
Source File: PaintTerrainToolAction.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void paintTexture(Terrain terrain, Vector3f markerLocation, float toolRadius, float toolWeight, int selectedTextureIndex) {
    if (selectedTextureIndex < 0 || markerLocation == null)
        return;
    
    int alphaIdx = selectedTextureIndex/4; // 4 = rgba = 4 textures
    Texture tex = getAlphaTexture(terrain, alphaIdx);
    Image image = tex.getImage();

    Vector2f UV = getPointPercentagePosition(terrain, markerLocation);

    // get the radius of the brush in pixel-percent
    float brushSize = toolRadius/(terrain.getTerrainSize()*((Node)terrain).getLocalScale().x);
    int texIndex = selectedTextureIndex - ((selectedTextureIndex/4)*4); // selectedTextureIndex/4 is an int floor, do not simplify the equation
    boolean erase = toolWeight<0;
    if (erase)
        toolWeight *= -1;

    doPaintAction(texIndex, image, UV, true, brushSize, erase, toolWeight);

    tex.getImage().setUpdateNeeded();
}
 
Example 6
Source File: SkyFactory.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Create a cube-mapped sky using six textures.
 *
 * @param assetManager from which to load materials
 * @param west texture for the western face of the cube
 * @param east texture for the eastern face of the cube
 * @param north texture for the northern face of the cube
 * @param south texture for the southern face of the cube
 * @param up texture for the top face of the cube
 * @param down texture for the bottom face of the cube
 * @param normalScale The normal scale is multiplied by the 3D normal to get
 * a texture coordinate. Use Vector3f.UNIT_XYZ to not apply and
 * transformation to the normal.
 * @param sphereRadius the sky sphere's radius: for the sky to be visible,
 * its radius must fall between the near and far planes of the camera's
 * frustum
 * @return a new spatial representing the sky, ready to be attached to the
 * scene graph
 */
public static Spatial createSky(AssetManager assetManager, Texture west,
        Texture east, Texture north, Texture south, Texture up,
        Texture down, Vector3f normalScale, float sphereRadius) {

    Image westImg = west.getImage();
    Image eastImg = east.getImage();
    Image northImg = north.getImage();
    Image southImg = south.getImage();
    Image upImg = up.getImage();
    Image downImg = down.getImage();

    checkImagesForCubeMap(westImg, eastImg, northImg, southImg, upImg, downImg);

    Image cubeImage = new Image(westImg.getFormat(), westImg.getWidth(), westImg.getHeight(), null, westImg.getColorSpace());

    cubeImage.addData(westImg.getData(0));
    cubeImage.addData(eastImg.getData(0));
    cubeImage.addData(downImg.getData(0));
    cubeImage.addData(upImg.getData(0));
    cubeImage.addData(southImg.getData(0));
    cubeImage.addData(northImg.getData(0));
    
    TextureCubeMap cubeMap = new TextureCubeMap(cubeImage);
    return createSky(assetManager, cubeMap, normalScale, EnvMapType.CubeMap, sphereRadius);
}
 
Example 7
Source File: PaintTerrainToolControl.java    From jmonkeybuilder with Apache License 2.0 6 votes vote down vote up
/**
 * Start making changes.
 */
@JmeThread
private void startChange() {

    final Array<ColorPoint> colorPoints = getColorPoints();
    colorPoints.clear();

    final Texture alphaTexture = notNull(getAlphaTexture());
    final Image image = alphaTexture.getImage();
    final ByteBuffer data = image.getData(0);

    if (prevBuffer == null) {
        prevBuffer = BufferUtils.createByteBuffer(data.capacity());
    } else if (prevBuffer.capacity() < data.capacity()) {
        BufferUtils.destroyDirectBuffer(prevBuffer);
        prevBuffer = BufferUtils.createByteBuffer(data.capacity());
    }

    final int position = data.position();
    data.position(0);
    prevBuffer.clear();
    prevBuffer.put(data);
    prevBuffer.flip();
    data.position(position);
}
 
Example 8
Source File: Material.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Returns the sorting ID or sorting index for this material.
 *
 * <p>The sorting ID is used internally by the system to sort rendering
 * of geometries. It sorted to reduce shader switches, if the shaders
 * are equal, then it is sorted by textures.
 *
 * @return The sorting ID used for sorting geometries for rendering.
 */
public int getSortId() {
    if (sortingId == -1 && technique != null) {
        sortingId = technique.getSortId() << 16;
        int texturesSortId = 17;
        for (int i = 0; i < paramValues.size(); i++) {
            MatParam param = paramValues.getValue(i);
            if (!param.getVarType().isTextureType()) {
                continue;
            }
            Texture texture = (Texture) param.getValue();
            if (texture == null) {
                continue;
            }
            Image image = texture.getImage();
            if (image == null) {
                continue;
            }
            int textureId = image.getId();
            if (textureId == -1) {
                textureId = 0;
            }
            texturesSortId = texturesSortId * 23 + textureId;
        }
        sortingId |= texturesSortId & 0xFFFF;
    }
    return sortingId;
}
 
Example 9
Source File: TextureAtlas.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Add a texture for a specific map name at the location of another existing texture (on the master map).
 * @param texture A texture to add to the atlas.
 * @param mapName A freely chosen map name that can be later retrieved as a Texture.
 * @param sourceTextureName Name of the master map used for the location.
 */
public void addTexture(Texture texture, String mapName, String sourceTextureName) {
    if (texture == null) {
        throw new IllegalStateException("Texture cannot be null!");
    }
    String name = textureName(texture);
    if (texture.getImage() != null && name != null) {
        addImage(texture.getImage(), name, mapName, sourceTextureName);
    } else {
        throw new IllegalStateException("Texture has no asset key name!");
    }
}
 
Example 10
Source File: TextureAtlas.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Add a texture for a specific map name
 * @param texture A texture to add to the atlas.
 * @param mapName A freely chosen map name that can be later retrieved as a Texture. The first map name supplied will be the master map.
 * @return false if the atlas is full.
 */
public boolean addTexture(Texture texture, String mapName) {
    if (texture == null) {
        throw new IllegalStateException("Texture cannot be null!");
    }
    String name = textureName(texture);
    if (texture.getImage() != null && name != null) {
        return addImage(texture.getImage(), name, mapName, null);
    } else {
        throw new IllegalStateException("Texture has no asset key name!");
    }
}
 
Example 11
Source File: GLRenderer.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void updateRenderTexture(FrameBuffer fb, RenderBuffer rb) {
    Texture tex = rb.getTexture();
    Image image = tex.getImage();
    if (image.isUpdateNeeded()) {
        // Check NPOT requirements
        checkNonPowerOfTwo(tex);

        updateTexImageData(image, tex.getType(), 0, false);

        // NOTE: For depth textures, sets nearest/no-mips mode
        // Required to fix "framebuffer unsupported"
        // for old NVIDIA drivers!
        setupTextureParams(0, tex);
    }

    if (rb.getLayer() < 0){
        glfbo.glFramebufferTexture2DEXT(GLFbo.GL_FRAMEBUFFER_EXT,
                convertAttachmentSlot(rb.getSlot()),
                convertTextureType(tex.getType(), image.getMultiSamples(), rb.getFace()),
                image.getId(),
                0);
    } else {
        glfbo.glFramebufferTextureLayerEXT(GLFbo.GL_FRAMEBUFFER_EXT, 
                convertAttachmentSlot(rb.getSlot()), 
                image.getId(), 
                0,
                rb.getLayer());
    }
}
 
Example 12
Source File: TerrainCollisionTest.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Before
public void initQuad() {
    Texture heightMapImage = getAssetManager().loadTexture("Textures/Terrain/splat/mountains512.png");
    AbstractHeightMap map = new ImageBasedHeightMap(heightMapImage.getImage(), 0.25f);
    map.load();
    quad = new TerrainQuad("terrain", 65, 513, map.getHeightMap());
}
 
Example 13
Source File: TbtQuadBackgroundComponent.java    From Lemur with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static TbtQuadBackgroundComponent create( Texture t,
                                                 float imageScale,
                                                 int x1, int y1, int x2, int y2,
                                                 float zOffset, boolean lit ) {
    Image img = t.getImage();

    // we use the image size for the quad just to make sure
    // it is always big enough for whatever insets are thrown at it
    TbtQuad q = new TbtQuad(img.getWidth(), img.getHeight(),
                            x1, y1, x2, y2, img.getWidth(), img.getHeight(),
                            imageScale);
    TbtQuadBackgroundComponent c = new TbtQuadBackgroundComponent(q, t, x1, y1, zOffset, lit);
    return c;
}
 
Example 14
Source File: PaintTerrainToolControl.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
/**
 * Paint texture.
 *
 * @param input the editing input.
 * @param contactPoint the contact point.
 */
@JmeThread
private void paintTexture(@NotNull final PaintingInput input, @NotNull final Vector3f contactPoint) {

    final Texture alphaTexture = getAlphaTexture();
    if (alphaTexture == null) {
        return;
    }

    final LocalObjects local = getLocalObjects();
    final Spatial terrainNode = notNull(getPaintedModel());
    final Terrain terrain = (Terrain) terrainNode;
    final Image image = alphaTexture.getImage();

    final Vector3f worldTranslation = terrainNode.getWorldTranslation();
    final Vector3f localPoint = contactPoint.subtract(worldTranslation, local.nextVector());
    final Vector3f localScale = terrainNode.getLocalScale();
    final Vector2f uv = getPointPercentagePosition(terrain, localPoint, localScale, local.nextVector2f());
    final Vector2f temp = local.nextVector2f();
    final ColorRGBA color = local.nextColor();

    final int layer = getLayer();

    // get the radius of the brush in pixel-percent
    float brushSize = getBrushSize() / (terrain.getTerrainSize() * localScale.getX());
    float brushPower = getBrushPower();

    if (input == PaintingInput.MOUSE_SECONDARY) {
        brushPower *= -1;
    }

    // selectedTextureIndex/4 is an int floor, do not simplify the equation
    final ObjectFloatObjectConsumer<ColorRGBA, Boolean> colorFunction = COLOR_FUNCTIONS[layer - ((layer / 4) * 4)];

    doPaintAction(colorFunction, image, uv, temp, color, brushSize, false, brushPower);

    image.setUpdateNeeded();
}
 
Example 15
Source File: GLRenderer.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@SuppressWarnings("fallthrough")
private void setupTextureParams(int unit, Texture tex) {
    Image image = tex.getImage();
    int samples = image != null ? image.getMultiSamples() : 1;
    int target = convertTextureType(tex.getType(), samples, -1);

    if (samples > 1) {
        bindTextureOnly(target, image, unit);
        return;
    }

    boolean haveMips = true;
    if (image != null) {
        haveMips = image.isGeneratedMipmapsRequired() || image.hasMipmaps();
    }
    
    LastTextureState curState = image.getLastTextureState();

    if (curState.magFilter != tex.getMagFilter()) {
        bindTextureAndUnit(target, image, unit);
        gl.glTexParameteri(target, GL.GL_TEXTURE_MAG_FILTER, convertMagFilter(tex.getMagFilter()));
        curState.magFilter = tex.getMagFilter();
    }
    if (curState.minFilter != tex.getMinFilter()) {
        bindTextureAndUnit(target, image, unit);
        gl.glTexParameteri(target, GL.GL_TEXTURE_MIN_FILTER, convertMinFilter(tex.getMinFilter(), haveMips));
        curState.minFilter = tex.getMinFilter();
    }

    int desiredAnisoFilter = tex.getAnisotropicFilter() == 0
            ? defaultAnisotropicFilter
            : tex.getAnisotropicFilter();

    if (caps.contains(Caps.TextureFilterAnisotropic)
            && curState.anisoFilter != desiredAnisoFilter) {
        bindTextureAndUnit(target, image, unit);
        gl.glTexParameterf(target,
                GLExt.GL_TEXTURE_MAX_ANISOTROPY_EXT,
                desiredAnisoFilter);
        curState.anisoFilter = desiredAnisoFilter;
    }

    switch (tex.getType()) {
        case ThreeDimensional:
        case CubeMap: // cubemaps use 3D coords
            if (gl2 != null && (caps.contains(Caps.OpenGL20) || caps.contains(Caps.OpenGLES30)) && curState.rWrap != tex.getWrap(WrapAxis.R)) {
                bindTextureAndUnit(target, image, unit);
                gl.glTexParameteri(target, GL2.GL_TEXTURE_WRAP_R, convertWrapMode(tex.getWrap(WrapAxis.R)));
                curState.rWrap = tex.getWrap(WrapAxis.R);
            }
            //There is no break statement on purpose here
        case TwoDimensional:
        case TwoDimensionalArray:
            if (curState.tWrap != tex.getWrap(WrapAxis.T)) {
                bindTextureAndUnit(target, image, unit);
                gl.glTexParameteri(target, GL.GL_TEXTURE_WRAP_T, convertWrapMode(tex.getWrap(WrapAxis.T)));
                image.getLastTextureState().tWrap = tex.getWrap(WrapAxis.T);
            }
            if (curState.sWrap != tex.getWrap(WrapAxis.S)) {
                bindTextureAndUnit(target, image, unit);
                gl.glTexParameteri(target, GL.GL_TEXTURE_WRAP_S, convertWrapMode(tex.getWrap(WrapAxis.S)));
                curState.sWrap = tex.getWrap(WrapAxis.S);
            }
            break;
        default:
            throw new UnsupportedOperationException("Unknown texture type: " + tex.getType());
    }

    ShadowCompareMode texCompareMode = tex.getShadowCompareMode();
    if ( (gl2 != null || caps.contains(Caps.OpenGLES30)) && curState.shadowCompareMode != texCompareMode) {
        bindTextureAndUnit(target, image, unit);
        if (texCompareMode != ShadowCompareMode.Off) {
            gl.glTexParameteri(target, GL2.GL_TEXTURE_COMPARE_MODE, GL2.GL_COMPARE_REF_TO_TEXTURE);
            if (texCompareMode == ShadowCompareMode.GreaterOrEqual) {
                gl.glTexParameteri(target, GL2.GL_TEXTURE_COMPARE_FUNC, GL.GL_GEQUAL);
            } else {
                gl.glTexParameteri(target, GL2.GL_TEXTURE_COMPARE_FUNC, GL.GL_LEQUAL);
            }
        } else {
            gl.glTexParameteri(target, GL2.GL_TEXTURE_COMPARE_MODE, GL.GL_NONE);
        }
        curState.shadowCompareMode = texCompareMode;
    }
    
    // If at this point we didn't bind the texture, bind it now
    bindTextureOnly(target, image, unit);
}
 
Example 16
Source File: ImageTileLoader.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * The ImageHeightmap that will parse the image type that you 
 * specify with setImageType().
 * @param customImageHeightmap must extend AbstractHeightmap
 */
/*public void setCustomImageHeightmap(ImageHeightmap customImageHeightmap) {
    if (!(customImageHeightmap instanceof AbstractHeightMap)) {
        throw new IllegalArgumentException("customImageHeightmap must be an AbstractHeightMap!");
    }
    this.customImageHeightmap = customImageHeightmap;
}*/

private HeightMap getHeightMapAt(Vector3f location) {
    // HEIGHTMAP image (for the terrain heightmap)
    int x = (int) location.x;
    int z = (int) location.z;
    
    AbstractHeightMap heightmap = null;
    //BufferedImage im = null;
    
    String name = null;
    try {
        name = namer.getName(x, z);
        logger.log(Level.FINE, "Loading heightmap from file: {0}", name);
        final Texture texture = assetManager.loadTexture(new TextureKey(name));
        heightmap = new ImageBasedHeightMap(texture.getImage());
        /*if (assetInfo != null){
            InputStream in = assetInfo.openStream();
            im = ImageIO.read(in);
        } else {
            im = new BufferedImage(patchSize, patchSize, imageType);
            logger.log(Level.WARNING, "File: {0} not found, loading zero heightmap instead", name);
        }*/
        // CREATE HEIGHTMAP
        /*if (imageType == BufferedImage.TYPE_USHORT_GRAY) {
            heightmap = new Grayscale16BitHeightMap(im);
        } else if (imageType == BufferedImage.TYPE_3BYTE_BGR) {
            heightmap = new ImageBasedHeightMap(im);
        } else if (customImageHeightmap != null && customImageHeightmap instanceof AbstractHeightMap) {
            // If it gets here, it means you have specified a different image type, and you must
            // then also supply a custom image heightmap class that can parse that image into
            // a heightmap.
            customImageHeightmap.setImage(im);
            heightmap = (AbstractHeightMap) customImageHeightmap;
        } else {
            // error, no supported image format and no custom image heightmap specified
            if (customImageHeightmap == null)
                logger.log(Level.SEVERE, "Custom image type specified [{0}] but no customImageHeightmap declared! Use setCustomImageHeightmap()",imageType);
            if (!(customImageHeightmap instanceof AbstractHeightMap))
                logger.severe("customImageHeightmap must be an AbstractHeightMap!");
            return null;
        }*/
        heightmap.setHeightScale(1);
        heightmap.load();
    //} catch (IOException e) {
    //    e.printStackTrace();
    } catch (AssetNotFoundException e) {
        logger.log(Level.WARNING, "Asset {0} not found, loading zero heightmap instead", name);
    }
    return heightmap;
}
 
Example 17
Source File: LwjglRenderer.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@SuppressWarnings("fallthrough")
    private void setupTextureParams(Texture tex) {
        Image image = tex.getImage();
        int target = convertTextureType(tex.getType(), image != null ? image.getMultiSamples() : 1);

        // filter things
        int minFilter = convertMinFilter(tex.getMinFilter());
        int magFilter = convertMagFilter(tex.getMagFilter());
        glTexParameteri(target, GL_TEXTURE_MIN_FILTER, minFilter);
        glTexParameteri(target, GL_TEXTURE_MAG_FILTER, magFilter);

        if (tex.getAnisotropicFilter() > 1) {
            if (GLContext.getCapabilities().GL_EXT_texture_filter_anisotropic) {
                glTexParameterf(target,
                        EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT,
                        tex.getAnisotropicFilter());
            }
        }

        if (context.pointSprite) {
            return; // Attempt to fix glTexParameter crash for some ATI GPUs
        }
        // repeat modes
        switch (tex.getType()) {
            case ThreeDimensional:
            case CubeMap: // cubemaps use 3D coords
                glTexParameteri(target, GL_TEXTURE_WRAP_R, convertWrapMode(tex.getWrap(WrapAxis.R)));
            case TwoDimensional:
            case TwoDimensionalArray:
                glTexParameteri(target, GL_TEXTURE_WRAP_T, convertWrapMode(tex.getWrap(WrapAxis.T)));
                // fall down here is intentional..
//            case OneDimensional:
                glTexParameteri(target, GL_TEXTURE_WRAP_S, convertWrapMode(tex.getWrap(WrapAxis.S)));
                break;
            default:
                throw new UnsupportedOperationException("Unknown texture type: " + tex.getType());
        }

        // R to Texture compare mode
        if (tex.getShadowCompareMode() != Texture.ShadowCompareMode.Off) {
            glTexParameteri(target, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE);
            glTexParameteri(target, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY);
            if (tex.getShadowCompareMode() == Texture.ShadowCompareMode.GreaterOrEqual) {
                glTexParameteri(target, GL_TEXTURE_COMPARE_FUNC, GL_GEQUAL);
            } else {
                glTexParameteri(target, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
            }
        }
    }
 
Example 18
Source File: ImageTileLoader.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * The ImageHeightmap that will parse the image type that you 
 * specify with setImageType().
 * @param customImageHeightmap must extend AbstractHeightmap
 */
/*public void setCustomImageHeightmap(ImageHeightmap customImageHeightmap) {
    if (!(customImageHeightmap instanceof AbstractHeightMap)) {
        throw new IllegalArgumentException("customImageHeightmap must be an AbstractHeightMap!");
    }
    this.customImageHeightmap = customImageHeightmap;
}*/

private HeightMap getHeightMapAt(Vector3f location) {
    // HEIGHTMAP image (for the terrain heightmap)
    int x = (int) location.x;
    int z = (int) location.z;
    
    AbstractHeightMap heightmap = null;
    //BufferedImage im = null;
    
    String name = null;
    try {
        name = namer.getName(x, z);
        logger.log(Level.FINE, "Loading heightmap from file: {0}", name);
        final Texture texture = assetManager.loadTexture(new TextureKey(name));
        heightmap = new ImageBasedHeightMap(texture.getImage());
        /*if (assetInfo != null){
            InputStream in = assetInfo.openStream();
            im = ImageIO.read(in);
        } else {
            im = new BufferedImage(patchSize, patchSize, imageType);
            logger.log(Level.WARNING, "File: {0} not found, loading zero heightmap instead", name);
        }*/
        // CREATE HEIGHTMAP
        /*if (imageType == BufferedImage.TYPE_USHORT_GRAY) {
            heightmap = new Grayscale16BitHeightMap(im);
        } else if (imageType == BufferedImage.TYPE_3BYTE_BGR) {
            heightmap = new ImageBasedHeightMap(im);
        } else if (customImageHeightmap != null && customImageHeightmap instanceof AbstractHeightMap) {
            // If it gets here, it means you have specified a different image type, and you must
            // then also supply a custom image heightmap class that can parse that image into
            // a heightmap.
            customImageHeightmap.setImage(im);
            heightmap = (AbstractHeightMap) customImageHeightmap;
        } else {
            // error, no supported image format and no custom image heightmap specified
            if (customImageHeightmap == null)
                logger.log(Level.SEVERE, "Custom image type specified [{0}] but no customImageHeightmap declared! Use setCustomImageHeightmap()",imageType);
            if (!(customImageHeightmap instanceof AbstractHeightMap))
                logger.severe("customImageHeightmap must be an AbstractHeightMap!");
            return null;
        }*/
        heightmap.setHeightScale(1);
        heightmap.load();
    //} catch (IOException e) {
    //    e.printStackTrace();
    } catch (AssetNotFoundException e) {
        logger.log(Level.WARNING, "Asset {0} not found, loading zero heightmap instead", name);
    }
    return heightmap;
}
 
Example 19
Source File: JoglRenderer.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void updateTextureData(Texture tex) {
    int texId = tex.getId();
    GL gl = GLContext.getCurrentGL();
    if (texId == -1) {
        // create texture
        gl.glGenTextures(1, intBuf1);
        texId = intBuf1.get(0);
        tex.setId(texId);
        objManager.registerForCleanup(tex);
    }

    // bind texture
    int target = convertTextureType(tex.getType());
    if (context.boundTextures[0] != tex) {
        if (context.boundTextureUnit != 0) {
            setActiveTexture(GL.GL_TEXTURE0);
            context.boundTextureUnit = 0;
        }

        bindTexture(target, texId);
        context.boundTextures[0] = tex;
    }

    // filter things
    int minFilter = convertMinFilter(tex.getMinFilter());
    int magFilter = convertMagFilter(tex.getMagFilter());
    gl.glTexParameteri(target, GL.GL_TEXTURE_MIN_FILTER, minFilter);
    gl.glTexParameteri(target, GL.GL_TEXTURE_MAG_FILTER, magFilter);

    // repeat modes
    switch (tex.getType()) {
        case ThreeDimensional:
        case CubeMap:
            gl.glTexParameteri(target, GL2GL3.GL_TEXTURE_WRAP_R,
                    convertWrapMode(tex.getWrap(WrapAxis.R)));
        case TwoDimensional:
            gl.glTexParameteri(target, GL.GL_TEXTURE_WRAP_T,
                    convertWrapMode(tex.getWrap(WrapAxis.T)));
            // fall down here is intentional..
            // case OneDimensional:
            gl.glTexParameteri(target, GL.GL_TEXTURE_WRAP_S,
                    convertWrapMode(tex.getWrap(WrapAxis.S)));
            break;
        default:
            throw new UnsupportedOperationException("Unknown texture type: " + tex.getType());
    }

    Image img = tex.getImage();
    if (img != null) {
        boolean generateMips = false;
        if (!img.hasMipmaps() && tex.getMinFilter().usesMipMapLevels()) {
            // No pregenerated mips available,
            // generate from base level if required
            if (hardwareMips) {
                gl.glTexParameteri(target, GL2ES1.GL_GENERATE_MIPMAP, GL.GL_TRUE);
            }
            else {
                generateMips = true;
            }
        }

        TextureUtil.uploadTexture(gl, img, tex.getImageDataIndex(), generateMips, powerOf2);
    }

    tex.clearUpdateNeeded();
}
 
Example 20
Source File: SkyFactory.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static Spatial createSky(AssetManager assetManager, Texture west, Texture east, Texture north, Texture south, Texture up, Texture down, Vector3f normalScale, int sphereRadius) {
    final Sphere sphereMesh = new Sphere(10, 10, sphereRadius, false, true);
    Geometry sky = new Geometry("Sky", sphereMesh);
    sky.setQueueBucket(Bucket.Sky);
    sky.setCullHint(Spatial.CullHint.Never);
    sky.setModelBound(new BoundingSphere(Float.POSITIVE_INFINITY, Vector3f.ZERO));

    Image westImg = west.getImage();
    Image eastImg = east.getImage();
    Image northImg = north.getImage();
    Image southImg = south.getImage();
    Image upImg = up.getImage();
    Image downImg = down.getImage();

    checkImagesForCubeMap(westImg, eastImg, northImg, southImg, upImg, downImg);

    Image cubeImage = new Image(westImg.getFormat(), westImg.getWidth(), westImg.getHeight(), null);

    cubeImage.addData(westImg.getData(0));
    cubeImage.addData(eastImg.getData(0));

    cubeImage.addData(downImg.getData(0));
    cubeImage.addData(upImg.getData(0));

    cubeImage.addData(southImg.getData(0));
    cubeImage.addData(northImg.getData(0));
    
    if (westImg.getEfficentData() != null){
        // also consilidate efficient data
        ArrayList<Object> efficientData = new ArrayList<Object>(6);
        efficientData.add(westImg.getEfficentData());
        efficientData.add(eastImg.getEfficentData());
        efficientData.add(downImg.getEfficentData());
        efficientData.add(upImg.getEfficentData());
        efficientData.add(southImg.getEfficentData());
        efficientData.add(northImg.getEfficentData());
        cubeImage.setEfficentData(efficientData);
    }

    TextureCubeMap cubeMap = new TextureCubeMap(cubeImage);
    cubeMap.setAnisotropicFilter(0);
    cubeMap.setMagFilter(Texture.MagFilter.Bilinear);
    cubeMap.setMinFilter(Texture.MinFilter.NearestNoMipMaps);
    cubeMap.setWrap(Texture.WrapMode.EdgeClamp);

    Material skyMat = new Material(assetManager, "Common/MatDefs/Misc/Sky.j3md");
    skyMat.setTexture("Texture", cubeMap);
    skyMat.setVector3("NormalScale", normalScale);
    sky.setMaterial(skyMat);

    return sky;
}