com.jme3.bounding.BoundingSphere Java Examples

The following examples show how to use com.jme3.bounding.BoundingSphere. 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: PickEventSession.java    From Lemur with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 *  Returns the min and max world z values for the specified
 *  spatial. 
 */
protected float[] getZBounds( Spatial s ) {
    BoundingVolume bv = s.getWorldBound();
    if( bv == null ) {
        // JME returns null for empty nodes
        return new float[] {0, 1}; 
    }
    Vector3f center = bv.getCenter();
    if( bv instanceof BoundingBox ) {
        BoundingBox bb = (BoundingBox)bv;
        return new float[] { center.z - bb.getZExtent(), center.z + bb.getZExtent() };
    } else if( bv instanceof BoundingSphere ) {
        BoundingSphere bs = (BoundingSphere)bv;
        return new float[] { center.z - bs.getRadius(), center.z + bs.getRadius() };
    } else {
        throw new UnsupportedOperationException("Bounding volume type not supported for:" + bv);
    }        
}
 
Example #2
Source File: SphereWanderBehavior.java    From MonkeyBrains with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void construct(float timeInterval, float randomFactor, float rotationFactor) {
    if (timeInterval <= 0) {
        throw new SteeringExceptions.NegativeValueException("The time interval must be possitive." + timeInterval);
    } else if (randomFactor < 0 || randomFactor > 1) {
        throw new SteeringExceptions.IllegalIntervalException("random", randomFactor);
    } else if (rotationFactor < 0 || rotationFactor > 1) {
        throw new SteeringExceptions.IllegalIntervalException("rotation", rotationFactor);
    }

    this.timeInterval = timeInterval;
    this.time = this.timeInterval;
    this.randomFactor = randomFactor;
    this.wanderSphere = new BoundingSphere(this.sphereRadius, Vector3f.ZERO);
    this.targetPosition = this.wanderSphere.getCenter();
    this.randomDirection = new Vector2f();
    this.maxRandom = this.sphereRadius - SphereWanderBehavior.RANDOM_OFFSET;
    this.rotationFactor = rotationFactor;
    this.maxRandom *= this.rotationFactor;
}
 
Example #3
Source File: BoundingCollisionTest.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testBoxSphereCollision() {
    BoundingBox box1 = new BoundingBox(Vector3f.ZERO, 1, 1, 1);
    BoundingSphere sphere2 = new BoundingSphere(1, Vector3f.ZERO);
    checkCollision(box1, sphere2, 1);
    
    // Put it at the very edge - for sphere vs. box, it will not intersect
    sphere2.setCenter(new Vector3f(2f, 0f, 0f));
    checkCollision(box1, sphere2, 0);
    
    // Put it a wee bit closer - should intersect.
    sphere2.setCenter(new Vector3f(2f - FastMath.ZERO_TOLERANCE, 0, 0));
    checkCollision(box1, sphere2, 1);
    
    // Test if the algorithm converts the sphere 
    // to a box before testing the collision (incorrect)
    float sqrt3 = FastMath.sqrt(3);
    
    sphere2.setCenter(Vector3f.UNIT_XYZ.mult(2));
    sphere2.setRadius(sqrt3);
    checkCollision(box1, sphere2, 0);
    
    // Make it a wee bit larger.
    sphere2.setRadius(sqrt3 + FastMath.ZERO_TOLERANCE);
    checkCollision(box1, sphere2, 1);
}
 
Example #4
Source File: BoundingCollisionTest.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSphereSphereCollision() {
    BoundingSphere sphere1 = new BoundingSphere(1, Vector3f.ZERO);
    BoundingSphere sphere2 = new BoundingSphere(1, Vector3f.ZERO);
    checkCollision(sphere1, sphere2, 1);
    
    // Put it at the very edge - should still intersect.
    sphere2.setCenter(new Vector3f(2f, 0f, 0f));
    checkCollision(sphere1, sphere2, 1);
    
    // Put it a wee bit farther - no intersection expected
    sphere2.setCenter(new Vector3f(2f + FastMath.ZERO_TOLERANCE, 0, 0));
    checkCollision(sphere1, sphere2, 0);
}
 
Example #5
Source File: AreaUtils.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static float calcScreenArea(BoundingSphere bound, float distance, float screenWidth) {
    // Where is the center point and a radius point that lies in a plan parallel to the view plane?
//    // Calc radius based on these two points and plug into circle area formula.
//    Vector2f centerSP = null;
//    Vector2f outerSP = null;
//    float radiusSq = centerSP.subtract(outerSP).lengthSquared();
      float radius = (bound.getRadius() * screenWidth) / (distance * 2);
      return radius * radius * FastMath.PI;
  }
 
Example #6
Source File: TestRayCasting.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
    public void simpleInitApp() {
//        flyCam.setEnabled(false);

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

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

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

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

        tracer = new RayTrace(rootNode, cam, 160, 128);
        tracer.show();
        tracer.update();
    }
 
Example #7
Source File: UVCoordinatesGenerator.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * This method returns the bounding sphere of the given mesh.
 * 
 * @param mesh
 *            the mesh
 * @return bounding sphere of the given mesh
 */
/* package */static BoundingSphere getBoundingSphere(Mesh mesh) {
    mesh.updateBound();
    BoundingVolume bv = mesh.getBound();
    if (bv instanceof BoundingBox) {
        BoundingBox bb = (BoundingBox) bv;
        float r = Math.max(bb.getXExtent(), bb.getYExtent());
        r = Math.max(r, bb.getZExtent());
        return new BoundingSphere(r, bb.getCenter());
    } else if (bv instanceof BoundingSphere) {
        return (BoundingSphere) bv;
    } else {
        throw new IllegalStateException("Unknown bounding volume type: " + bv.getClass().getName());
    }
}
 
Example #8
Source File: UVCoordinatesGenerator.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * This method returns the bounding sphere of the given geometries.
 * 
 * @param geometries
 *            the list of geometries
 * @return bounding sphere of the given geometries
 */
/* package */static BoundingSphere getBoundingSphere(List<Geometry> geometries) {
    BoundingSphere result = null;
    for (Geometry geometry : geometries) {
        BoundingSphere bs = UVCoordinatesGenerator.getBoundingSphere(geometry.getMesh());
        if (result == null) {
            result = bs;
        } else {
            result.merge(bs);
        }
    }
    return result;
}
 
Example #9
Source File: UVCoordinatesGenerator.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * This method returns the bounding box of the given mesh.
 * 
 * @param mesh
 *            the mesh
 * @return bounding box of the given mesh
 */
/* package */static BoundingBox getBoundingBox(Mesh mesh) {
    mesh.updateBound();
    BoundingVolume bv = mesh.getBound();
    if (bv instanceof BoundingBox) {
        return (BoundingBox) bv;
    } else if (bv instanceof BoundingSphere) {
        BoundingSphere bs = (BoundingSphere) bv;
        float r = bs.getRadius();
        return new BoundingBox(bs.getCenter(), r, r, r);
    } else {
        throw new IllegalStateException("Unknown bounding volume type: " + bv.getClass().getName());
    }
}
 
Example #10
Source File: TerrainPatch.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private int collideWithBoundingVolume(BoundingVolume boundingVolume, CollisionResults results) {
    if (boundingVolume instanceof BoundingBox)
        return collideWithBoundingBox((BoundingBox)boundingVolume, results);
    else if(boundingVolume instanceof BoundingSphere) {
        BoundingSphere sphere = (BoundingSphere) boundingVolume;
        BoundingBox bbox = new BoundingBox(boundingVolume.getCenter().clone(), sphere.getRadius(),
                                                       sphere.getRadius(),
                                                       sphere.getRadius());
        return collideWithBoundingBox(bbox, results);
    }
    return 0;
}
 
Example #11
Source File: ShapeBoundsTest.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void testBounds(Geometry geometry) {
    BoundingVolume bv = geometry.getWorldBound();

    if (bv instanceof BoundingBox) {
        BoundingBox bb = (BoundingBox) bv;
        Assert.assertTrue(bb.getXExtent() > 0 && bb.getYExtent() > 0 && bb.getZExtent() > 0);
    } else if (bv instanceof BoundingSphere) {
        BoundingSphere bs = (BoundingSphere) bv;
        Assert.assertTrue(bs.getRadius() > 1f);
    }

    testVertices(geometry);
}
 
Example #12
Source File: LightFilterTest.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testDirectionalFiltering() {
    geom.addLight(new DirectionalLight(Vector3f.UNIT_Y));
    checkFilteredLights(1); // Directional lights must never be filtered
    
    // Test for bounding Sphere
    geom.setModelBound(new BoundingSphere(0.5f, Vector3f.ZERO));
    checkFilteredLights(1); // Directional lights must never be filtered
}
 
Example #13
Source File: LightFilterTest.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testAmbientFiltering() {
    geom.addLight(new AmbientLight());
    checkFilteredLights(1); // Ambient lights must never be filtered
    
    // Test for bounding Sphere
    geom.setModelBound(new BoundingSphere(0.5f, Vector3f.ZERO));
    checkFilteredLights(1); // Ambient lights must never be filtered
}
 
Example #14
Source File: BoundingCollisionTest.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSphereTriangleCollision() {
    BoundingSphere sphere = new BoundingSphere(1, Vector3f.ZERO);
    Geometry geom = new Geometry("geom", new Quad(1, 1));
    checkCollision(sphere, geom, 2);
    
    // The box touches the edges of the triangles.
    sphere.setCenter(new Vector3f(-1f + FastMath.ZERO_TOLERANCE, 0, 0));
    checkCollision(sphere, geom, 2);
    
    // Move it slightly farther..
    sphere.setCenter(new Vector3f(-1f - FastMath.ZERO_TOLERANCE, 0, 0));
    checkCollision(sphere, geom, 0);
    
    // Parallel triangle / box side, touching
    sphere.setCenter(new Vector3f(0, 0, -1f));
    checkCollision(sphere, geom, 2);
    
    // Not touching
    sphere.setCenter(new Vector3f(0, 0, -1f - FastMath.ZERO_TOLERANCE));
    checkCollision(sphere, geom, 0);
    
    // Test collisions only against one of the triangles
    sphere.setCenter(new Vector3f(-0.9f, 1.2f, 0f));
    checkCollision(sphere, geom, 1);
    
    sphere.setCenter(new Vector3f(1.2f, -0.9f, 0f));
    checkCollision(sphere, geom, 1);
}
 
Example #15
Source File: AbstractSceneEditor3DPart.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
/**
 * Look at the spatial.
 *
 * @param spatial the spatial.
 */
@FromAnyThread
public void cameraLookAt(@NotNull final Spatial spatial) {
    EXECUTOR_MANAGER.addJmeTask(() -> {

        final EditorCamera editorCamera = notNull(getEditorCamera());

        final LocalObjects local = LocalObjects.get();
        float distance;

        final BoundingVolume worldBound = spatial.getWorldBound();

        if (worldBound != null) {
            distance = worldBound.getVolume();

            if (worldBound instanceof BoundingBox) {
                final BoundingBox boundingBox = (BoundingBox) worldBound;
                distance = boundingBox.getXExtent();
                distance = Math.max(distance, boundingBox.getYExtent());
                distance = Math.max(distance, boundingBox.getZExtent());
                distance *= 2F;
            } else if (worldBound instanceof BoundingSphere) {
                distance = ((BoundingSphere) worldBound).getRadius() * 2F;
            }

        } else {

           distance = getCamera().getLocation()
                   .distance(spatial.getWorldTranslation());
        }

        editorCamera.setTargetDistance(distance);

        final Vector3f position = local.nextVector()
                .set(spatial.getWorldTranslation());

        getNodeForCamera().setLocalTranslation(position);
    });
}
 
Example #16
Source File: LodGenerator.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void build() {
    BoundingSphere bs = new BoundingSphere();
    bs.computeFromPoints(mesh.getFloatBuffer(VertexBuffer.Type.Position));
    meshBoundingSphereRadius = bs.getRadius();
    List<Vertex> vertexLookup = new ArrayList<Vertex>();
    initialize();
    
    gatherVertexData(mesh, vertexLookup);
    gatherIndexData(mesh, vertexLookup);
    computeCosts();
   // assert (assertValidMesh());
    
}
 
Example #17
Source File: TerrainPatch.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private int collideWithBoundingVolume(BoundingVolume boundingVolume, CollisionResults results) {
    if (boundingVolume instanceof BoundingBox)
        return collideWithBoundingBox((BoundingBox)boundingVolume, results);
    else if(boundingVolume instanceof BoundingSphere) {
        BoundingSphere sphere = (BoundingSphere) boundingVolume;
        BoundingBox bbox = new BoundingBox(boundingVolume.getCenter().clone(), sphere.getRadius(),
                                                       sphere.getRadius(),
                                                       sphere.getRadius());
        return collideWithBoundingBox(bbox, results);
    }
    return 0;
}
 
Example #18
Source File: SpotLight.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public boolean intersectsSphere(BoundingSphere sphere, TempVars vars) {
    if (this.spotRange > 0f) {
        // Check spot range first.
        // Sphere v. sphere collision
        if (!Intersection.intersect(sphere, position, spotRange)) {
            return false;
        }
    }

    float otherRadiusSquared = FastMath.sqr(sphere.getRadius());
    float otherRadius = sphere.getRadius();

    // Check if sphere is within spot angle.
    // Cone v. sphere collision.
    Vector3f E = direction.mult(otherRadius * outerAngleSinRcp, vars.vect1);
    Vector3f U = position.subtract(E, vars.vect2);
    Vector3f D = sphere.getCenter().subtract(U, vars.vect3);

    float dsqr = D.dot(D);
    float e = direction.dot(D);

    if (e > 0f && e * e >= dsqr * outerAngleCosSqr) {
        D = sphere.getCenter().subtract(position, vars.vect3);
        dsqr = D.dot(D);
        e = -direction.dot(D);

        if (e > 0f && e * e >= dsqr * outerAngleSinSqr) {
            return dsqr <= otherRadiusSquared;
        } else {
            return true;
        }
    }
    
    return false;
}
 
Example #19
Source File: TestRayCasting.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
    public void simpleInitApp() {
//        flyCam.setEnabled(false);

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

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

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

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

        tracer = new RayTrace(rootNode, cam, 160, 128);
        tracer.show();
        tracer.update();
    }
 
Example #20
Source File: TestObbVsBounds.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void makeSphereWire(BoundingSphere sphere) {

        sphereGeom = new Geometry("box", new Sphere(16, 16, 10));
        sphereGeom.setMaterial(new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"));
        sphereGeom.getMaterial().getAdditionalRenderState().setWireframe(true);
        sphereGeom.setLocalTranslation(sphere.getCenter());
        rootNode.attachChild(sphereGeom);
    }
 
Example #21
Source File: AreaUtils.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static float calcScreenArea(BoundingSphere bound, float distance, float screenWidth) {
    // Where is the center point and a radius point that lies in a plan parallel to the view plane?
//    // Calc radius based on these two points and plug into circle area formula.
//    Vector2f centerSP = null;
//    Vector2f outerSP = null;
//    float radiusSq = centerSP.subtract(outerSP).lengthSquared();
      float radius = (bound.getRadius() * screenWidth) / (distance * 2);
      return radius * radius * FastMath.PI;
  }
 
Example #22
Source File: OrientedBoxProbeArea.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public boolean intersectsSphere(BoundingSphere sphere, TempVars vars) {

    Vector3f closestPoint = getClosestPoint(vars, sphere.getCenter());
    // check if the point intersects with the sphere bound
    if (sphere.intersects(closestPoint)) {
        return true;
    }
    return false;
}
 
Example #23
Source File: PointLight.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public boolean intersectsSphere(BoundingSphere sphere, TempVars vars) {
    if (this.radius == 0) {
        return true;
    } else {
        // Sphere v. sphere collision
        return Intersection.intersect(sphere, position, radius);
    }
}
 
Example #24
Source File: UVProjectionGenerator.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Sphere projection for 2D textures.
 * 
 * @param positions
 *            points to be projected
 * @param bb
 *            the bounding box for projecting
 * @return UV coordinates after the projection
 */
public static float[] sphereProjection(float[] positions, BoundingSphere bs) {// TODO: rotate it to be vertical
    float[] uvCoordinates = new float[positions.length / 3 * 2];
    Vector3f v = new Vector3f();
    float cx = bs.getCenter().x, cy = bs.getCenter().y, cz = bs.getCenter().z;
    Vector3f uBase = new Vector3f(0, -1, 0);
    Vector3f vBase = new Vector3f(0, 0, -1);

    for (int i = 0, j = 0; i < positions.length; i += 3, j += 2) {
        // calculating U
        v.set(positions[i] - cx, positions[i + 1] - cy, 0);
        v.normalizeLocal();
        float angle = v.angleBetween(uBase);// result between [0; PI]
        if (v.x < 0) {// the angle should be greater than PI, we're on the other part of the image then
            angle = FastMath.TWO_PI - angle;
        }
        uvCoordinates[j] = angle / FastMath.TWO_PI;

        // calculating V
        v.set(positions[i] - cx, positions[i + 1] - cy, positions[i + 2] - cz);
        v.normalizeLocal();
        angle = v.angleBetween(vBase);// result between [0; PI]
        uvCoordinates[j + 1] = angle / FastMath.PI;
    }

    // looking for splitted triangles
    Triangle triangle = new Triangle();
    for (int i = 0; i < positions.length; i += 9) {
        triangle.set(0, positions[i], positions[i + 1], positions[i + 2]);
        triangle.set(1, positions[i + 3], positions[i + 4], positions[i + 5]);
        triangle.set(2, positions[i + 6], positions[i + 7], positions[i + 8]);
        float sgn1 = Math.signum(triangle.get1().x - cx);
        float sgn2 = Math.signum(triangle.get2().x - cx);
        float sgn3 = Math.signum(triangle.get3().x - cx);
        float xSideFactor = sgn1 + sgn2 + sgn3;
        float ySideFactor = Math.signum(triangle.get1().y - cy) + Math.signum(triangle.get2().y - cy) + Math.signum(triangle.get3().y - cy);
        if ((xSideFactor > -3 || xSideFactor < 3) && ySideFactor < 0) {// the triangle is on the splitting plane
            if (sgn1 == 1.0f) {
                uvCoordinates[i / 3 * 2] += 1.0f;
            }
            if (sgn2 == 1.0f) {
                uvCoordinates[(i / 3 + 1) * 2] += 1.0f;
            }
            if (sgn3 == 1.0f) {
                uvCoordinates[(i / 3 + 2) * 2] += 1.0f;
            }
        }
    }
    return uvCoordinates;
}
 
Example #25
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;
}
 
Example #26
Source File: UVCoordinatesGenerator.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Generates a UV coordinates for 2D texture.
 * 
 * @param mesh
 *            the mesh we generate UV's for
 * @param texco
 *            UV coordinates type
 * @param projection
 *            projection type
 * @param geometries
 *            the geometris the given mesh belongs to (required to compute
 *            bounding box)
 * @return UV coordinates for the given mesh
 */
public static List<Vector2f> generateUVCoordinatesFor2DTexture(Mesh mesh, UVCoordinatesType texco, UVProjectionType projection, List<Geometry> geometries) {
    List<Vector2f> result = new ArrayList<Vector2f>();
    BoundingBox bb = UVCoordinatesGenerator.getBoundingBox(geometries);
    float[] inputData = null;// positions, normals, reflection vectors, etc.

    switch (texco) {
        case TEXCO_ORCO:
            inputData = BufferUtils.getFloatArray(mesh.getFloatBuffer(VertexBuffer.Type.Position));
            break;
        case TEXCO_UV:// this should be used if not defined by user explicitly
            Vector2f[] data = new Vector2f[] { new Vector2f(0, 1), new Vector2f(0, 0), new Vector2f(1, 0) };
            for (int i = 0; i < mesh.getVertexCount(); ++i) {
                result.add(data[i % 3]);
            }
            break;
        case TEXCO_NORM:
            inputData = BufferUtils.getFloatArray(mesh.getFloatBuffer(VertexBuffer.Type.Normal));
            break;
        case TEXCO_REFL:
        case TEXCO_GLOB:
        case TEXCO_TANGENT:
        case TEXCO_STRESS:
        case TEXCO_LAVECTOR:
        case TEXCO_OBJECT:
        case TEXCO_OSA:
        case TEXCO_PARTICLE_OR_STRAND:
        case TEXCO_SPEED:
        case TEXCO_STICKY:
        case TEXCO_VIEW:
        case TEXCO_WINDOW:
            LOGGER.warning("Texture coordinates type not currently supported: " + texco);
            break;
        default:
            throw new IllegalStateException("Unknown texture coordinates value: " + texco);
    }

    if (inputData != null) {// make projection calculations
        switch (projection) {
            case PROJECTION_FLAT:
                inputData = UVProjectionGenerator.flatProjection(inputData, bb);
                break;
            case PROJECTION_CUBE:
                inputData = UVProjectionGenerator.cubeProjection(inputData, bb);
                break;
            case PROJECTION_TUBE:
                BoundingTube bt = UVCoordinatesGenerator.getBoundingTube(geometries);
                inputData = UVProjectionGenerator.tubeProjection(inputData, bt);
                break;
            case PROJECTION_SPHERE:
                BoundingSphere bs = UVCoordinatesGenerator.getBoundingSphere(geometries);
                inputData = UVProjectionGenerator.sphereProjection(inputData, bs);
                break;
            default:
                throw new IllegalStateException("Unknown projection type: " + projection);
        }
        for (int i = 0; i < inputData.length; i += 2) {
            result.add(new Vector2f(inputData[i], inputData[i + 1]));
        }
    }
    return result;
}
 
Example #27
Source File: LightFilterTest.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void testPointFiltering() {
    PointLight pl = new PointLight(Vector3f.ZERO);
    geom.addLight(pl);
    checkFilteredLights(1); // Infinite point lights must never be filtered
    
    // Light at origin does not intersect geom which is at Z=10
    pl.setRadius(1);
    checkFilteredLights(0);
    
    // Put it closer to geom, the very edge of the sphere touches the box.
    // Still not considered an intersection though.
    pl.setPosition(new Vector3f(0, 0, 8f));
    checkFilteredLights(0);
    
    // And more close - now its an intersection.
    pl.setPosition(new Vector3f(0, 0, 8f + FastMath.ZERO_TOLERANCE));
    checkFilteredLights(1);
    
    // Move the geometry away
    geom.move(0, 0, FastMath.ZERO_TOLERANCE);
    checkFilteredLights(0);
    
    // Test if the algorithm converts the sphere 
    // to a box before testing the collision (incorrect)
    float sqrt3 = FastMath.sqrt(3);
    
    pl.setPosition(new Vector3f(2, 2, 8));
    pl.setRadius(sqrt3);
    checkFilteredLights(0);
    
    // Make it a wee bit larger.
    pl.setRadius(sqrt3 + FastMath.ZERO_TOLERANCE);
    checkFilteredLights(1);
    
    // Rotate the camera so it is up, light is outside frustum.
    cam.lookAtDirection(Vector3f.UNIT_Y, Vector3f.UNIT_Y);
    checkFilteredLights(0);
    
    // ==================================
    // Tests for bounding Sphere
    geom.setModelBound(new BoundingSphere(1f, Vector3f.ZERO));
    geom.setLocalTranslation(0, 0, 2);
    pl.setPosition(new Vector3f(0, 0, 2f));

    // Infinite point lights must never be filtered
    pl.setRadius(0);
    checkFilteredLights(1);
 
    pl.setRadius(1f);
    // Put the light at the very close to the geom,
    // the very edge of the sphere touches the other bounding sphere
    // Still not considered an intersection though.
    pl.setPosition(new Vector3f(0, 0, 0));
    checkFilteredLights(0);

    // And more close - now its an intersection.
    pl.setPosition(new Vector3f(0, 0, 0f + FastMath.ZERO_TOLERANCE));
    checkFilteredLights(1);
           
    geom.setLocalTranslation(0, 0, 0);
    // In this case its an intersection for pointLight v. box
    // But not for pointLight v. sphere
    // Vector3f(0, 0.5f, 0.5f).normalize().mult(2) ~ >= (0.0, 1.4142135, 1.4142135)
    //pl.setPosition(new Vector3f(0, 0.5f, 0.5f).normalizeLocal().multLocal(2 + FastMath.ZERO_TOLERANCE));
    pl.setPosition(new Vector3f(0f, 1.4142135f, 1.4142135f).multLocal(1+FastMath.ZERO_TOLERANCE));
    checkFilteredLights(0);
    
    // Make the distance a wee bit closer, now its an intersection
    //pl.setPosition(new Vector3f(0, 0.5f, 0.5f).normalizeLocal().multLocal(2 - FastMath.ZERO_TOLERANCE));
    pl.setPosition(new Vector3f(0f, 1.4142135f, 1.4142135f).multLocal(1-FastMath.ZERO_TOLERANCE));
    checkFilteredLights(1);
    
    // it's a point light, also test for the other corner
    pl.setPosition(new Vector3f(0f, -1.4142135f, -1.4142135f).multLocal(1-FastMath.ZERO_TOLERANCE));
    checkFilteredLights(0);

}
 
Example #28
Source File: DefaultLightFilter.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void filterLights(Geometry geometry, LightList filteredLightList) {
    TempVars vars = TempVars.get();
    try {
        LightList worldLights = geometry.getWorldLightList();
       
        for (int i = 0; i < worldLights.size(); i++) {
            Light light = worldLights.get(i);

            // If this light is not enabled it will be ignored.
            if (!light.isEnabled()) {
                continue;
            }

            if (light.frustumCheckNeeded) {
                processedLights.add(light);
                light.frustumCheckNeeded = false;
                light.intersectsFrustum = light.intersectsFrustum(camera, vars);
            }

            if (!light.intersectsFrustum) {
                continue;
            }

            BoundingVolume bv = geometry.getWorldBound();
            
            if (bv instanceof BoundingBox) {
                if (!light.intersectsBox((BoundingBox)bv, vars)) {
                    continue;
                }
            } else if (bv instanceof BoundingSphere) {
                if (!Float.isInfinite( ((BoundingSphere)bv).getRadius() )) {
                    if (!light.intersectsSphere((BoundingSphere)bv, vars)) {
                        continue;
                    }
                }
            }
            
            if (light.getType() == Light.Type.Probe) {
                probeBlendStrat.registerProbe((LightProbe) light);
            } else {
                filteredLightList.add(light);
            }
            
        }
        
        probeBlendStrat.populateProbes(geometry, filteredLightList);

    } finally {
        vars.release();
    }
}
 
Example #29
Source File: DirectionalLight.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public boolean intersectsSphere(BoundingSphere sphere, TempVars vars) {
    return true;
}
 
Example #30
Source File: AmbientLight.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public boolean intersectsSphere(BoundingSphere sphere, TempVars vars) {
    return true;
}