Java Code Examples for com.jme3.math.FastMath#PI

The following examples show how to use com.jme3.math.FastMath#PI . 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: SceneLoader.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void parseCamera(Attributes attribs) throws SAXException {
    camera = new Camera(DEFAULT_CAM_WIDTH, DEFAULT_CAM_HEIGHT);
    if (SAXUtil.parseString(attribs.getValue("projectionType"), "perspective").equals("parallel")){
        camera.setParallelProjection(true);
    }
    float fov = SAXUtil.parseFloat(attribs.getValue("fov"), 45f);
    if (fov < FastMath.PI) { 
        // XXX: Most likely, it is in radians..
        fov = fov * FastMath.RAD_TO_DEG;
    }
    camera.setFrustumPerspective(fov, (float)DEFAULT_CAM_WIDTH / DEFAULT_CAM_HEIGHT, 1, 1000);
    
    cameraNode = new CameraNode(attribs.getValue("name"), camera);
    cameraNode.setControlDir(ControlDirection.SpatialToCamera);
    
    node.attachChild(cameraNode);
    node = null;
}
 
Example 2
Source File: SceneLoader.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void parseCamera(Attributes attribs) throws SAXException {
    camera = new Camera(DEFAULT_CAM_WIDTH, DEFAULT_CAM_HEIGHT);
    if (SAXUtil.parseString(attribs.getValue("projectionType"), "perspective").equals("parallel")){
        camera.setParallelProjection(true);
    }
    float fov = SAXUtil.parseFloat(attribs.getValue("fov"), 45f);
    if (fov < FastMath.PI) { 
        // XXX: Most likely, it is in radians..
        fov = fov * FastMath.RAD_TO_DEG;
    }
    camera.setFrustumPerspective(fov, (float)DEFAULT_CAM_WIDTH / DEFAULT_CAM_HEIGHT, 1, 1000);
    
    cameraNode = new CameraNode(attribs.getValue("name"), camera);
    cameraNode.setControlDir(ControlDirection.SpatialToCamera);
    
    node.attachChild(cameraNode);
    node = null;
}
 
Example 3
Source File: Editor3DEditorState.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
public Editor3DEditorState() {
    this.cameraLocation = new Vector3f();
    this.cameraVRotation = FastMath.PI / 6;
    this.cameraTDistance = 20;
    this.cameraHRotation = 0;
    this.cameraSpeed = 1;
}
 
Example 4
Source File: ContainmentBehavior.java    From MonkeyBrains with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @see AbstractStrengthSteeringBehavior#calculateRawSteering()
 */
@Override
protected Vector3f calculateRawSteering() {
    Vector3f steer = new Vector3f();
    Vector3f predictedPos = this.agent.getPredictedPosition();

    //Check if the agent is outside the area
    if (!this.containmentArea.getWorldBound().contains(this.agent.getLocalTranslation())) {
        //If we know where is the point he exited, return to the area
        if (lastExitSurfaceNormal != null) {
            steer = this.surfaceNormal.mult(this.exitPoint.distance(predictedPos));
        } else {
            steer = this.containmentArea.getWorldBound().getCenter().subtract(this.agent.getLocalTranslation());
        }
    } else {
        //Check if correction is necessary
        if (!this.containmentArea.getWorldBound().contains(predictedPos)) {
            this.processExitSurface();

            if (exitPoint != null && surfaceNormal != null) {
                //Check If the normal vector will mantain the agent inside the area, 
                //if not flip it
                if (this.surfaceNormal.angleBetween(this.agent.getVelocity()) < FastMath.PI / 2) {
                    this.surfaceNormal = this.surfaceNormal.negate();
                }

                steer = this.surfaceNormal.mult(this.exitPoint.distance(predictedPos));
            }
        }
    }
    return steer;
}
 
Example 5
Source File: LeaderFollowingBehavior.java    From MonkeyBrains with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @see SeekBehavior#SeekBehavior(com.jme3.ai.agents.Agent,
 * com.jme3.ai.agents.Agent)
 */
public LeaderFollowingBehavior(Agent agent, Agent target) {
    super(agent, target);
    this.evadeBehavior = new EvadeBehavior(agent, target);
    this.arriveBehavior = new ArriveBehavior(agent, target);

    //Default values
    this.distanceToEvade = 2;
    this.distanceToChangeFocus = 5;
    this.minimumAngle = FastMath.PI / 2.35f;
}
 
Example 6
Source File: LeaderFollowingBehavior.java    From MonkeyBrains with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @see SeekBehavior#SeekBehavior(com.jme3.ai.agents.Agent,
 * com.jme3.ai.agents.Agent, com.jme3.scene.Spatial)
 */
public LeaderFollowingBehavior(Agent agent, Agent target, Spatial spatial) {
    super(agent, target, spatial);
    this.evadeBehavior = new EvadeBehavior(agent, target, spatial);
    this.arriveBehavior = new ArriveBehavior(agent, target);

    //Default values
    this.distanceToEvade = 2;
    this.distanceToChangeFocus = 5;
    this.minimumAngle = FastMath.PI / 2.35f;
}
 
Example 7
Source File: AnimationFactory.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Adds a key frame for the given rotation at the given key frame index.<br>
 * Rotation is expressed by Euler angles values in radians.<br>
 * Note that the generated rotation will be stored as a quaternion and interpolated using a spherical linear interpolation (slerp)<br>
 * Hence, this method may create intermediate keyFrames if the interpolation angle is higher than PI to ensure continuity in animation<br>
 * 
 * @param keyFrameIndex the index at which the keyFrame must be inserted
 * @param x the rotation around the x axis (aka yaw) in radians
 * @param y the rotation around the y axis (aka roll) in radians
 * @param z the rotation around the z axis (aka pitch) in radians
 */
public void addKeyFrameRotationAngles(int keyFrameIndex, float x, float y, float z) {
    Rotation r = getRotationForFrame(keyFrameIndex);
    r.set(x, y, z);

    // if the delta of euler angles is higher than PI, we create intermediate keyframes
    // since we are using quaternions and slerp for rotation interpolation, we cannot interpolate over an angle higher than PI
    int prev = getPreviousKeyFrame(keyFrameIndex, keyFramesRotation);
    if (prev != -1) {
        //previous rotation keyframe
        Rotation prevRot = keyFramesRotation[prev];
        //the maximum delta angle (x,y or z)
        float delta = Math.max(Math.abs(x - prevRot.eulerAngles.x), Math.abs(y - prevRot.eulerAngles.y));
        delta = Math.max(delta, Math.abs(z - prevRot.eulerAngles.z));
        //if delta > PI we have to create intermediates key frames
        if (delta >= FastMath.PI) {
            //frames delta
            int dF = keyFrameIndex - prev;
            //angle per frame for x,y ,z
            float dXAngle = (x - prevRot.eulerAngles.x) / dF;
            float dYAngle = (y - prevRot.eulerAngles.y) / dF;
            float dZAngle = (z - prevRot.eulerAngles.z) / dF;

            // the keyFrame step
            int keyStep = (int) (dF / delta * EULER_STEP);
            // the current keyFrame
            int cursor = prev + keyStep;
            while (cursor < keyFrameIndex) {
                //for each step we create a new rotation by interpolating the angles
                Rotation dr = getRotationForFrame(cursor);
                dr.masterKeyFrame = keyFrameIndex;
                dr.set(prevRot.eulerAngles.x + cursor * dXAngle, prevRot.eulerAngles.y + cursor * dYAngle, prevRot.eulerAngles.z + cursor * dZAngle);
                cursor += keyStep;
            }

        }
    }

}
 
Example 8
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 9
Source File: AreaUtils.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static float calcScreenArea(BoundingBox bound, float distance, float screenWidth) {
    // Calc as if we are a BoundingSphere for now...
    float radiusSquare = bound.getXExtent() * bound.getXExtent()
                       + bound.getYExtent() * bound.getYExtent()
                       + bound.getZExtent() * bound.getZExtent();
    return ((radiusSquare * screenWidth * screenWidth) / (distance * distance * 4)) * FastMath.PI;
}
 
Example 10
Source File: LodControl.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected void controlRender(RenderManager rm, ViewPort vp) {
    BoundingVolume bv = spatial.getWorldBound();

    Camera cam = vp.getCamera();
    float atanNH = FastMath.atan(cam.getFrustumNear() * cam.getFrustumTop());
    float ratio = (FastMath.PI / (8f * atanNH));
    float newDistance = bv.distanceTo(vp.getCamera().getLocation()) / ratio;
    int level;

    if (Math.abs(newDistance - lastDistance) <= distTolerance) {
        level = lastLevel; // we haven't moved relative to the model, send the old measurement back.
    } else if (lastDistance > newDistance && lastLevel == 0) {
        level = lastLevel; // we're already at the lowest setting and we just got closer to the model, no need to keep trying.
    } else if (lastDistance < newDistance && lastLevel == numLevels - 1) {
        level = lastLevel; // we're already at the highest setting and we just got further from the model, no need to keep trying.
    } else {
        lastDistance = newDistance;

        // estimate area of polygon via bounding volume
        float area = AreaUtils.calcScreenArea(bv, lastDistance, cam.getWidth());
        float trisToDraw = area * trisPerPixel;
        level = numLevels - 1;
        for (int i = numLevels; --i >= 0;) {
            if (trisToDraw - numTris[i] < 0) {
                break;
            }
            level = i;
        }
        lastLevel = level;
    }

    spatial.setLodLevel(level);
}
 
Example 11
Source File: AnimationFactory.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Adds a key frame for the given rotation at the given key frame index.<br>
 * Rotation is expressed by Euler angles values in radians.<br>
 * Note that the generated rotation will be stored as a quaternion and interpolated using a spherical linear interpolation (slerp)<br>
 * Hence, this method may create intermediate keyFrames if the interpolation angle is higher than PI to ensure continuity in animation<br>
 * 
 * @param keyFrameIndex the index at which the keyFrame must be inserted
 * @param x the rotation around the x axis (aka yaw) in radians
 * @param y the rotation around the y axis (aka roll) in radians
 * @param z the rotation around the z axis (aka pitch) in radians
 */
public void addKeyFrameRotationAngles(int keyFrameIndex, float x, float y, float z) {
    Rotation r = getRotationForFrame(keyFrameIndex);
    r.set(x, y, z);

    // if the delta of euler angles is higher than PI, we create intermediate keyframes
    // since we are using quaternions and slerp for rotation interpolation, we cannot interpolate over an angle higher than PI
    int prev = getPreviousKeyFrame(keyFrameIndex, keyFramesRotation);
    if (prev != -1) {
        //previous rotation keyframe
        Rotation prevRot = keyFramesRotation[prev];
        //the maximum delta angle (x,y or z)
        float delta = Math.max(Math.abs(x - prevRot.eulerAngles.x), Math.abs(y - prevRot.eulerAngles.y));
        delta = Math.max(delta, Math.abs(z - prevRot.eulerAngles.z));
        //if delta > PI we have to create intermediates key frames
        if (delta >= FastMath.PI) {
            //frames delta
            int dF = keyFrameIndex - prev;
            //angle per frame for x,y ,z
            float dXAngle = (x - prevRot.eulerAngles.x) / (float) dF;
            float dYAngle = (y - prevRot.eulerAngles.y) / (float) dF;
            float dZAngle = (z - prevRot.eulerAngles.z) / (float) dF;

            // the keyFrame step
            int keyStep = (int) (((float) (dF)) / delta * (float) EULER_STEP);
            // the current keyFrame
            int cursor = prev + keyStep;
            while (cursor < keyFrameIndex) {
                //for each step we create a new rotation by interpolating the angles
                Rotation dr = getRotationForFrame(cursor);
                dr.masterKeyFrame = keyFrameIndex;
                dr.set(prevRot.eulerAngles.x + cursor * dXAngle, prevRot.eulerAngles.y + cursor * dYAngle, prevRot.eulerAngles.z + cursor * dZAngle);
                cursor += keyStep;
            }

        }
    }

}
 
Example 12
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 13
Source File: AreaUtils.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static float calcScreenArea(BoundingBox bound, float distance, float screenWidth) {
    // Calc as if we are a BoundingSphere for now...
    float radiusSquare = bound.getXExtent() * bound.getXExtent()
                       + bound.getYExtent() * bound.getYExtent()
                       + bound.getZExtent() * bound.getZExtent();
    return ((radiusSquare * screenWidth * screenWidth) / (distance * distance * 4)) * FastMath.PI;
}
 
Example 14
Source File: LodControl.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected void controlRender(RenderManager rm, ViewPort vp){
    BoundingVolume bv = spatial.getWorldBound();

    Camera cam = vp.getCamera();
    float atanNH = FastMath.atan(cam.getFrustumNear() * cam.getFrustumTop());
    float ratio = (FastMath.PI / (8f * atanNH));
    float newDistance = bv.distanceTo(vp.getCamera().getLocation()) / ratio;
    int level;

    if (Math.abs(newDistance - lastDistance) <= distTolerance)
        level = lastLevel; // we haven't moved relative to the model, send the old measurement back.
    else if (lastDistance > newDistance && lastLevel == 0)
        level = lastLevel; // we're already at the lowest setting and we just got closer to the model, no need to keep trying.
    else if (lastDistance < newDistance && lastLevel == numLevels - 1)
        level = lastLevel; // we're already at the highest setting and we just got further from the model, no need to keep trying.
    else{
        lastDistance = newDistance;

        // estimate area of polygon via bounding volume
        float area = AreaUtils.calcScreenArea(bv, lastDistance, cam.getWidth());
        float trisToDraw = area * trisPerPixel;
        level = numLevels - 1;
        for (int i = numLevels; --i >= 0;){
            if (trisToDraw - numTris[i] < 0){
                break;
            }
            level = i;
        }
        lastLevel = level;
    }

    spatial.setLodLevel(level);
}
 
Example 15
Source File: TestColorApp.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
    public void simpleInitApp() {
        // Lights
        DirectionalLight sun = new DirectionalLight();
        Vector3f sunPosition = new Vector3f(1, -1, 1);
        sun.setDirection(sunPosition);
        sun.setColor(new ColorRGBA(1f,1f,1f,1f));
        rootNode.addLight(sun);
 
        //DirectionalLightShadowFilter sun_renderer = new DirectionalLightShadowFilter(assetManager, 2048, 4);
        DirectionalLightShadowRenderer sun_renderer = new DirectionalLightShadowRenderer(assetManager, 2048, 1);
        sun_renderer.setLight(sun);
        viewPort.addProcessor(sun_renderer);
        
//        FilterPostProcessor fpp = new FilterPostProcessor(assetManager);
//        fpp.addFilter(sun_renderer);
//        viewPort.addProcessor(fpp);
        
        rootNode.setShadowMode(RenderQueue.ShadowMode.CastAndReceive);
 
        // Camera
        viewPort.setBackgroundColor(new ColorRGBA(.6f, .6f, .6f, 1f));
        ChaseCamera chaseCam = new ChaseCamera(cam, inputManager);
 
 
        // Objects
        // Ground Object
        final Geometry groundBoxWhite = new Geometry("Box", new Box(7.5f, 7.5f, .25f));
        float[] f = {-FastMath.PI / 2, 3 * FastMath.PI / 2, 0f};
        groundBoxWhite.setLocalRotation(new Quaternion(f));
        groundBoxWhite.move(7.5f, -.75f, 7.5f);
        final Material groundMaterial = new Material(assetManager, "Common/MatDefs/Light/Lighting.j3md");
        groundMaterial.setColor("Diffuse", new ColorRGBA(.9f, .9f, .9f, .9f));
        groundBoxWhite.setMaterial(groundMaterial);
        groundBoxWhite.addControl(chaseCam);
        rootNode.attachChild(groundBoxWhite);
 
        // Planter
        Geometry planterBox = new Geometry("Box", new Box(.5f, .5f, .5f));
        final Material planterMaterial = new Material(assetManager, "Common/MatDefs/Light/Lighting.j3md");
        planterMaterial.setTexture("DiffuseMap", assetManager.loadTexture("Textures/Terrain/BrickWall/BrickWall.jpg"));
        planterBox.setMaterial(groundMaterial);
        planterBox.setLocalTranslation(10, 0, 9);
        rootNode.attachChild(planterBox);
 
        // Action!
        inputManager.addMapping("on", new KeyTrigger(KeyInput.KEY_Z));
        inputManager.addMapping("off", new KeyTrigger(KeyInput.KEY_X));
 
        inputManager.addListener(new AnalogListener() {
            @Override
            public void onAnalog(String s, float v, float v1) {
                if (s.equals("on")) {
                    groundBoxWhite.setMaterial(planterMaterial);
                }
                if (s.equals("off")) {
                    groundBoxWhite.setMaterial(groundMaterial);
                }
            }
        }, "on", "off");
 
        inputEnabled = true;
    }
 
Example 16
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;
}