Java Code Examples for com.jme3.math.Vector3f#normalizeLocal()

The following examples show how to use com.jme3.math.Vector3f#normalizeLocal() . 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: TestHoveringTank.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void updateCamera() {
    rootNode.updateGeometricState();

    Vector3f pos = spaceCraft.getWorldTranslation().clone();
    Quaternion rot = spaceCraft.getWorldRotation();
    Vector3f dir = rot.getRotationColumn(2);

    // make it XZ only
    Vector3f camPos = new Vector3f(dir);
    camPos.setY(0);
    camPos.normalizeLocal();

    // negate and multiply by distance from object
    camPos.negateLocal();
    camPos.multLocal(15);

    // add Y distance
    camPos.setY(2);
    camPos.addLocal(pos);
    cam.setLocation(camPos);

    Vector3f lookAt = new Vector3f(dir);
    lookAt.multLocal(7); // look at dist
    lookAt.addLocal(pos);
    cam.lookAt(lookAt, Vector3f.UNIT_Y);
}
 
Example 2
Source File: SeparationBehavior.java    From MonkeyBrains with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * @see AbstractSteeringBehavior#calculateSteering()
 */
@Override
protected Vector3f calculateRawSteering() {
    //Propities whom behaviour belongs.
    Vector3f agentLocation = super.agent.getLocalTranslation();
    Vector3f steering = new Vector3f();

    for (GameEntity obstacle : this.obstacles) {
        //If the obstacle is not himself
        if (obstacle != this.agent && obstacle.distanceRelativeToGameEntity(this.agent) < this.minDistance) {
            Vector3f location = obstacle.getLocalTranslation().subtract(agentLocation);
            float lengthSquared = location.lengthSquared();
            location.normalizeLocal();
            steering.addLocal(location.negate().mult(1f / ((float) FastMath.pow(lengthSquared, 2))));
        }
    }

    return steering;
}
 
Example 3
Source File: CurvesHelper.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * The method transforms the bevel along the curve.
 * 
 * @param bevel
 *            the bevel to be transformed
 * @param prevPos
 *            previous curve point
 * @param currPos
 *            current curve point (here the center of the new bevel will be
 *            set)
 * @param nextPos
 *            next curve point
 * @return points of transformed bevel
 */
private Vector3f[] transformBevel(Vector3f[] bevel, Vector3f prevPos, Vector3f currPos, Vector3f nextPos) {
    bevel = bevel.clone();

    // currPos and directionVector define the line in 3D space
    Vector3f directionVector = prevPos != null ? currPos.subtract(prevPos) : nextPos.subtract(currPos);
    directionVector.normalizeLocal();

    // plane is described by equation: Ax + By + Cz + D = 0 where planeNormal = [A, B, C] and D = -(Ax + By + Cz)
    Vector3f planeNormal = null;
    if (prevPos != null) {
        planeNormal = currPos.subtract(prevPos).normalizeLocal();
        if (nextPos != null) {
            planeNormal.addLocal(nextPos.subtract(currPos).normalizeLocal()).normalizeLocal();
        }
    } else {
        planeNormal = nextPos.subtract(currPos).normalizeLocal();
    }
    float D = -planeNormal.dot(currPos);// D = -(Ax + By + Cz)

    // now we need to compute paralell cast of each bevel point on the plane, the leading line is already known
    // parametric equation of a line: x = px + vx * t; y = py + vy * t; z = pz + vz * t
    // where p = currPos and v = directionVector
    // using x, y and z in plane equation we get value of 't' that will allow us to compute the point where plane and line cross
    float temp = planeNormal.dot(directionVector);
    for (int i = 0; i < bevel.length; ++i) {
        float t = -(planeNormal.dot(bevel[i]) + D) / temp;
        if (fixUpAxis) {
            bevel[i] = new Vector3f(bevel[i].x + directionVector.x * t, bevel[i].y + directionVector.y * t, bevel[i].z + directionVector.z * t);
        } else {
            bevel[i] = new Vector3f(bevel[i].x + directionVector.x * t, -bevel[i].z + directionVector.z * t, bevel[i].y + directionVector.y * t);
        }
    }
    return bevel;
}
 
Example 4
Source File: ConstraintDefinitionDistLimit.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void bake(Transform ownerTransform, Transform targetTransform, float influence) {
    if (this.getOwner() instanceof Bone && ((Bone) this.getOwner()).getParent() != null) {
        // distance limit does not work on bones who have parent
        return;
    }

    Vector3f v = ownerTransform.getTranslation().subtract(targetTransform.getTranslation());
    float currentDistance = v.length();

    switch (mode) {
        case LIMITDIST_INSIDE:
            if (currentDistance >= dist) {
                v.normalizeLocal();
                v.multLocal(dist + (currentDistance - dist) * (1.0f - influence));
                ownerTransform.getTranslation().set(v.addLocal(targetTransform.getTranslation()));
            }
            break;
        case LIMITDIST_ONSURFACE:
            if (currentDistance > dist) {
                v.normalizeLocal();
                v.multLocal(dist + (currentDistance - dist) * (1.0f - influence));
                ownerTransform.getTranslation().set(v.addLocal(targetTransform.getTranslation()));
            } else if (currentDistance < dist) {
                v.normalizeLocal().multLocal(dist * influence);
                ownerTransform.getTranslation().set(targetTransform.getTranslation().add(v));
            }
            break;
        case LIMITDIST_OUTSIDE:
            if (currentDistance <= dist) {
                v = targetTransform.getTranslation().subtract(ownerTransform.getTranslation()).normalizeLocal().multLocal(dist * influence);
                ownerTransform.getTranslation().set(targetTransform.getTranslation().add(v));
            }
            break;
        default:
            throw new IllegalStateException("Unknown distance limit constraint mode: " + mode);
    }
}
 
Example 5
Source File: ShapeGeometryTest.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testCylinders() {
    Random random = new Random();
    
    // Create a cylinder, cast a random ray, and ensure everything goes well.
    Node scene = new Node("Scene Node");

    for (int i = 0; i < NUMBER_OF_TRIES; i++) {
        scene.detachAllChildren();

        Cylinder cylinder = new Cylinder(2, 8, 1, 1, true);
        Geometry geometry = new Geometry("cylinder", cylinder);
        geometry.rotate(FastMath.HALF_PI, 0, 0);
        scene.attachChild(geometry);

        // Cast a random ray, and count successes and IndexOutOfBoundsExceptions.
        Vector3f randomPoint = new Vector3f(random.nextFloat(), random.nextFloat(), random.nextFloat());
        Vector3f randomDirection = new Vector3f(random.nextFloat(), random.nextFloat(), random.nextFloat());
        randomDirection.normalizeLocal();

        Ray ray = new Ray(randomPoint, randomDirection);
        CollisionResults collisionResults = new CollisionResults();

        // If the geometry is invalid, this should throw various exceptions.
        scene.collideWith(ray, collisionResults);
    }
}
 
Example 6
Source File: BillboardControl.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Aligns this Billboard so that it points to the camera position.
 *
 * @param camera
 *            Camera
 */
private void rotateCameraAligned(Camera camera) {
    look.set(camera.getLocation()).subtractLocal(
            spatial.getWorldTranslation());
    // coopt left for our own purposes.
    Vector3f xzp = left;
    // The xzp vector is the projection of the look vector on the xz plane
    xzp.set(look.x, 0, look.z);

    // check for undefined rotation...
    if (xzp.equals(Vector3f.ZERO)) {
        return;
    }

    look.normalizeLocal();
    xzp.normalizeLocal();
    float cosp = look.dot(xzp);

    // compute the local orientation matrix for the billboard
    orient.set(0, 0, xzp.z);
    orient.set(0, 1, xzp.x * -look.y);
    orient.set(0, 2, xzp.x * cosp);
    orient.set(1, 0, 0);
    orient.set(1, 1, cosp);
    orient.set(1, 2, look.y);
    orient.set(2, 0, -xzp.x);
    orient.set(2, 1, xzp.z * -look.y);
    orient.set(2, 2, xzp.z * cosp);

    // The billboard must be oriented to face the camera before it is
    // transformed into the world.
    spatial.setLocalRotation(orient);
    fixRefreshFlags();
}
 
Example 7
Source File: RollingTheMonkey.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void simpleUpdate(float tpf) {
    // Update and position the score
    scoreText.setText("Score: " + score);
    scoreText.setLocalTranslation((cam.getWidth() - scoreText.getLineWidth()) / 2.0f,
            scoreText.getLineHeight(), 0.0f);
    
    // Rotate all the pickups
    float pickUpSpeed = PICKUP_SPEED * tpf;
    for(Spatial pickUp : pickUps.getChildren()) {
        pickUp.rotate(pickUpSpeed, pickUpSpeed, pickUpSpeed);
    }
    
    Vector3f centralForce = new Vector3f();
    
    if(keyForward) centralForce.addLocal(cam.getDirection());
    if(keyBackward) centralForce.addLocal(cam.getDirection().negate());
    if(keyLeft) centralForce.addLocal(cam.getLeft());
    if(keyRight) centralForce.addLocal(cam.getLeft().negate());
    
    if(!Vector3f.ZERO.equals(centralForce)) {
        centralForce.setY(0);                   // stop ball from pusing down or flying up
        centralForce.normalizeLocal();          // normalize force
        centralForce.multLocal(PLAYER_FORCE);   // scale vector to force

        player.applyCentralForce(centralForce); // apply force to player
    }
    
    cam.lookAt(player.getPhysicsLocation(), Vector3f.UNIT_Y);
}
 
Example 8
Source File: TestIssue1283.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Add a projectile to the scene and physics space. Its initial position and
 * velocity are determined by the camera the and mouse pointer.
 */
private void launchProjectile() {
    Vector2f screenXY = inputManager.getCursorPosition();
    float nearZ = 0f;
    Vector3f nearLocation = cam.getWorldCoordinates(screenXY, nearZ);
    float farZ = 1f;
    Vector3f farLocation = cam.getWorldCoordinates(screenXY, farZ);
    Vector3f direction = farLocation.subtract(nearLocation);
    direction.normalizeLocal();

    Geometry geometry = new Geometry("projectile", projectileMesh);
    rootNode.attachChild(geometry);
    geometry.setLocalTranslation(nearLocation);
    geometry.setMaterial(projectileMaterial);

    float mass = 1f;
    RigidBodyControl physicsControl = new RigidBodyControl(mass);
    geometry.addControl(physicsControl);

    physicsControl.setCcdMotionThreshold(0.01f);
    physicsControl.setCcdSweptSphereRadius(projectileRadius);
    physicsControl.setCollisionGroup(
            PhysicsCollisionObject.COLLISION_GROUP_02);
    physicsControl.setCollideWithGroups(
            PhysicsCollisionObject.COLLISION_GROUP_02);
    physicsControl.setRestitution(0.8f);

    float projectileSpeed = 250f; // physics-space units per second
    Vector3f initialVelocity = direction.mult(projectileSpeed);
    physicsControl.setLinearVelocity(initialVelocity);

    physicsSpace.add(physicsControl);
}
 
Example 9
Source File: BIHTriangle.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public Vector3f getNormal(){
    Vector3f normal = new Vector3f(pointb);
    normal.subtractLocal(pointa).crossLocal(pointc.x-pointa.x, pointc.y-pointa.y, pointc.z-pointa.z);
    normal.normalizeLocal();
    return normal;
}
 
Example 10
Source File: BIHTriangle.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public Vector3f getNormal(){
    Vector3f normal = new Vector3f(pointb);
    normal.subtractLocal(pointa).crossLocal(pointc.x-pointa.x, pointc.y-pointa.y, pointc.z-pointa.z);
    normal.normalizeLocal();
    return normal;
}
 
Example 11
Source File: TangentBinormalGenerator.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static TriangleData processTriangle(int[] index,
        Vector3f[] v, Vector2f[] t) {
    TempVars tmp = TempVars.get();
    try {
        Vector3f edge1 = tmp.vect1;
        Vector3f edge2 = tmp.vect2;
        Vector2f edge1uv = tmp.vect2d;
        Vector2f edge2uv = tmp.vect2d2;
        
        Vector3f tangent = tmp.vect3;
        Vector3f binormal = tmp.vect4;
        Vector3f normal = tmp.vect5;
        
        t[1].subtract(t[0], edge1uv);
        t[2].subtract(t[0], edge2uv);
        float det = edge1uv.x * edge2uv.y - edge1uv.y * edge2uv.x;
        
        boolean normalize = false;
        if (Math.abs(det) < ZERO_TOLERANCE) {
            log.log(Level.WARNING, "Colinear uv coordinates for triangle "
                    + "[{0}, {1}, {2}]; tex0 = [{3}, {4}], "
                    + "tex1 = [{5}, {6}], tex2 = [{7}, {8}]",
                    new Object[]{index[0], index[1], index[2],
                        t[0].x, t[0].y, t[1].x, t[1].y, t[2].x, t[2].y});
            det = 1;
            normalize = true;
        }
        
        v[1].subtract(v[0], edge1);
        v[2].subtract(v[0], edge2);
        
        tangent.set(edge1);
        tangent.normalizeLocal();
        binormal.set(edge2);
        binormal.normalizeLocal();
        
        if (Math.abs(Math.abs(tangent.dot(binormal)) - 1)
                < ZERO_TOLERANCE) {
            log.log(Level.WARNING, "Vertices are on the same line "
                    + "for triangle [{0}, {1}, {2}].",
                    new Object[]{index[0], index[1], index[2]});
        }
        
        float factor = 1 / det;
        tangent.x = (edge2uv.y * edge1.x - edge1uv.y * edge2.x) * factor;
        tangent.y = (edge2uv.y * edge1.y - edge1uv.y * edge2.y) * factor;
        tangent.z = (edge2uv.y * edge1.z - edge1uv.y * edge2.z) * factor;
        if (normalize) {
            tangent.normalizeLocal();
        }
        
        binormal.x = (edge1uv.x * edge2.x - edge2uv.x * edge1.x) * factor;
        binormal.y = (edge1uv.x * edge2.y - edge2uv.x * edge1.y) * factor;
        binormal.z = (edge1uv.x * edge2.z - edge2uv.x * edge1.z) * factor;
        if (normalize) {
            binormal.normalizeLocal();
        }
        
        tangent.cross(binormal, normal);
        normal.normalizeLocal();
        
        return new TriangleData(
                tangent.clone(),
                binormal.clone(),
                normal.clone());
    } finally {
        tmp.release();
    }
}
 
Example 12
Source File: LODGeomap.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public FloatBuffer writeNormalArray(FloatBuffer store, Vector3f scale) {
    if (!isLoaded()) {
        throw new NullPointerException();
    }

    if (store != null) {
        if (store.remaining() < getWidth() * getHeight() * 3) {
            throw new BufferUnderflowException();
        }
    } else {
        store = BufferUtils.createFloatBuffer(getWidth() * getHeight() * 3);
    }
    store.rewind();

    TempVars vars = TempVars.get();
    
    Vector3f rootPoint = vars.vect1;
    Vector3f rightPoint = vars.vect2;
    Vector3f leftPoint = vars.vect3;
    Vector3f topPoint = vars.vect4;
    Vector3f bottomPoint = vars.vect5;
    
    Vector3f tmp1 = vars.vect6;

    // calculate normals for each polygon
    for (int r = 0; r < getHeight(); r++) {
        for (int c = 0; c < getWidth(); c++) {

            rootPoint.set(0, getValue(c, r), 0);
            Vector3f normal = vars.vect8;

            if (r == 0) { // first row
                if (c == 0) { // first column
                    rightPoint.set(1, getValue(c + 1, r), 0);
                    bottomPoint.set(0, getValue(c, r + 1), 1);
                    getNormal(bottomPoint, rootPoint, rightPoint, scale, normal);
                } else if (c == getWidth() - 1) { // last column
                    leftPoint.set(-1, getValue(c - 1, r), 0);
                    bottomPoint.set(0, getValue(c, r + 1), 1);
                    getNormal(leftPoint, rootPoint, bottomPoint, scale, normal);
                } else { // all middle columns
                    leftPoint.set(-1, getValue(c - 1, r), 0);
                    rightPoint.set(1, getValue(c + 1, r), 0);
                    bottomPoint.set(0, getValue(c, r + 1), 1);
                    
                    normal.set( getNormal(leftPoint, rootPoint, bottomPoint, scale, tmp1) );
                    normal.addLocal( getNormal(bottomPoint, rootPoint, rightPoint, scale, tmp1) );
                }
            } else if (r == getHeight() - 1) { // last row
                if (c == 0) { // first column
                    topPoint.set(0, getValue(c, r - 1), -1);
                    rightPoint.set(1, getValue(c + 1, r), 0);
                    getNormal(rightPoint, rootPoint, topPoint, scale, normal);
                } else if (c == getWidth() - 1) { // last column
                    topPoint.set(0, getValue(c, r - 1), -1);
                    leftPoint.set(-1, getValue(c - 1, r), 0);
                    getNormal(topPoint, rootPoint, leftPoint, scale, normal);
                } else { // all middle columns
                    topPoint.set(0, getValue(c, r - 1), -1);
                    leftPoint.set(-1, getValue(c - 1, r), 0);
                    rightPoint.set(1, getValue(c + 1, r), 0);
                    
                    normal.set( getNormal(topPoint, rootPoint, leftPoint, scale, tmp1) );
                    normal.addLocal( getNormal(rightPoint, rootPoint, topPoint, scale, tmp1) );
                }
            } else { // all middle rows
                if (c == 0) { // first column
                    topPoint.set(0, getValue(c, r - 1), -1);
                    rightPoint.set(1, getValue(c + 1, r), 0);
                    bottomPoint.set(0, getValue(c, r + 1), 1);
                    
                    normal.set( getNormal(rightPoint, rootPoint, topPoint, scale, tmp1) );
                    normal.addLocal( getNormal(bottomPoint, rootPoint, rightPoint, scale, tmp1) );
                } else if (c == getWidth() - 1) { // last column
                    topPoint.set(0, getValue(c, r - 1), -1);
                    leftPoint.set(-1, getValue(c - 1, r), 0);
                    bottomPoint.set(0, getValue(c, r + 1), 1);

                    normal.set( getNormal(topPoint, rootPoint, leftPoint, scale, tmp1) );
                    normal.addLocal( getNormal(leftPoint, rootPoint, bottomPoint, scale, tmp1) );
                } else { // all middle columns
                    topPoint.set(0, getValue(c, r - 1), -1);
                    leftPoint.set(-1, getValue(c - 1, r), 0);
                    rightPoint.set(1, getValue(c + 1, r), 0);
                    bottomPoint.set(0, getValue(c, r + 1), 1);
                    
                    normal.set( getNormal(topPoint,  rootPoint, leftPoint, scale, tmp1 ) );
                    normal.addLocal( getNormal(leftPoint, rootPoint, bottomPoint, scale, tmp1) );
                    normal.addLocal( getNormal(bottomPoint, rootPoint, rightPoint, scale, tmp1) );
                    normal.addLocal( getNormal(rightPoint, rootPoint, topPoint, scale, tmp1) );
                }
            }
            normal.normalizeLocal();
            BufferUtils.setInBuffer(normal, store, (r * getWidth() + c)); // save the normal
        }
    }
    vars.release();
    
    return store;
}
 
Example 13
Source File: SilentTangentBinormalGenerator.java    From OpenRTS with MIT License 4 votes vote down vote up
public static TriangleData processTriangle(int[] index, Vector3f[] v, Vector2f[] t) {
		Vector3f edge1 = new Vector3f();
		Vector3f edge2 = new Vector3f();
		Vector2f edge1uv = new Vector2f();
		Vector2f edge2uv = new Vector2f();

		Vector3f tangent = new Vector3f();
		Vector3f binormal = new Vector3f();
		Vector3f normal = new Vector3f();

		t[1].subtract(t[0], edge1uv);
		t[2].subtract(t[0], edge2uv);
		float det = edge1uv.x * edge2uv.y - edge1uv.y * edge2uv.x;

		boolean normalize = false;
		if (Math.abs(det) < ZERO_TOLERANCE) {
//			log.log(Level.WARNING, "Colinear uv coordinates for triangle " + "[{0}, {1}, {2}]; tex0 = [{3}, {4}], " + "tex1 = [{5}, {6}], tex2 = [{7}, {8}]",
//					new Object[] { index[0], index[1], index[2], t[0].x, t[0].y, t[1].x, t[1].y, t[2].x, t[2].y });
			det = 1;
			normalize = true;
		}

		v[1].subtract(v[0], edge1);
		v[2].subtract(v[0], edge2);

		tangent.set(edge1);
		tangent.normalizeLocal();
		binormal.set(edge2);
		binormal.normalizeLocal();

		if (Math.abs(Math.abs(tangent.dot(binormal)) - 1) < ZERO_TOLERANCE) {
//			log.log(Level.WARNING, "Vertices are on the same line " + "for triangle [{0}, {1}, {2}].", new Object[] { index[0], index[1], index[2] });
		}

		float factor = 1 / det;
		tangent.x = (edge2uv.y * edge1.x - edge1uv.y * edge2.x) * factor;
		tangent.y = (edge2uv.y * edge1.y - edge1uv.y * edge2.y) * factor;
		tangent.z = (edge2uv.y * edge1.z - edge1uv.y * edge2.z) * factor;
		if (normalize) {
			tangent.normalizeLocal();
		}

		binormal.x = (edge1uv.x * edge2.x - edge2uv.x * edge1.x) * factor;
		binormal.y = (edge1uv.x * edge2.y - edge2uv.x * edge1.y) * factor;
		binormal.z = (edge1uv.x * edge2.z - edge2uv.x * edge1.z) * factor;
		if (normalize) {
			binormal.normalizeLocal();
		}

		tangent.cross(binormal, normal);
		normal.normalizeLocal();

		return new TriangleData(tangent, binormal, normal);
	}
 
Example 14
Source File: LODGeomap.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public FloatBuffer writeNormalArray(FloatBuffer store, Vector3f scale) {
    if (!isLoaded()) {
        throw new NullPointerException();
    }

    if (store != null) {
        if (store.remaining() < getWidth() * getHeight() * 3) {
            throw new BufferUnderflowException();
        }
    } else {
        store = BufferUtils.createFloatBuffer(getWidth() * getHeight() * 3);
    }
    store.rewind();

    TempVars vars = TempVars.get();
    
    Vector3f rootPoint = vars.vect1;
    Vector3f rightPoint = vars.vect2;
    Vector3f leftPoint = vars.vect3;
    Vector3f topPoint = vars.vect4;
    Vector3f bottomPoint = vars.vect5;
    
    Vector3f tmp1 = vars.vect6;

    // calculate normals for each polygon
    for (int r = 0; r < getHeight(); r++) {
        for (int c = 0; c < getWidth(); c++) {

            rootPoint.set(0, getValue(c, r), 0);
            Vector3f normal = vars.vect8;

            if (r == 0) { // first row
                if (c == 0) { // first column
                    rightPoint.set(1, getValue(c + 1, r), 0);
                    bottomPoint.set(0, getValue(c, r + 1), 1);
                    getNormal(bottomPoint, rootPoint, rightPoint, scale, normal);
                } else if (c == getWidth() - 1) { // last column
                    leftPoint.set(-1, getValue(c - 1, r), 0);
                    bottomPoint.set(0, getValue(c, r + 1), 1);
                    getNormal(leftPoint, rootPoint, bottomPoint, scale, normal);
                } else { // all middle columns
                    leftPoint.set(-1, getValue(c - 1, r), 0);
                    rightPoint.set(1, getValue(c + 1, r), 0);
                    bottomPoint.set(0, getValue(c, r + 1), 1);
                    
                    normal.set( getNormal(leftPoint, rootPoint, bottomPoint, scale, tmp1) );
                    normal.addLocal( getNormal(bottomPoint, rootPoint, rightPoint, scale, tmp1) );
                }
            } else if (r == getHeight() - 1) { // last row
                if (c == 0) { // first column
                    topPoint.set(0, getValue(c, r - 1), -1);
                    rightPoint.set(1, getValue(c + 1, r), 0);
                    getNormal(rightPoint, rootPoint, topPoint, scale, normal);
                } else if (c == getWidth() - 1) { // last column
                    topPoint.set(0, getValue(c, r - 1), -1);
                    leftPoint.set(-1, getValue(c - 1, r), 0);
                    getNormal(topPoint, rootPoint, leftPoint, scale, normal);
                } else { // all middle columns
                    topPoint.set(0, getValue(c, r - 1), -1);
                    leftPoint.set(-1, getValue(c - 1, r), 0);
                    rightPoint.set(1, getValue(c + 1, r), 0);
                    
                    normal.set( getNormal(topPoint, rootPoint, leftPoint, scale, tmp1) );
                    normal.addLocal( getNormal(rightPoint, rootPoint, topPoint, scale, tmp1) );
                }
            } else { // all middle rows
                if (c == 0) { // first column
                    topPoint.set(0, getValue(c, r - 1), -1);
                    rightPoint.set(1, getValue(c + 1, r), 0);
                    bottomPoint.set(0, getValue(c, r + 1), 1);
                    
                    normal.set( getNormal(rightPoint, rootPoint, topPoint, scale, tmp1) );
                    normal.addLocal( getNormal(bottomPoint, rootPoint, rightPoint, scale, tmp1) );
                } else if (c == getWidth() - 1) { // last column
                    topPoint.set(0, getValue(c, r - 1), -1);
                    leftPoint.set(-1, getValue(c - 1, r), 0);
                    bottomPoint.set(0, getValue(c, r + 1), 1);

                    normal.set( getNormal(topPoint, rootPoint, leftPoint, scale, tmp1) );
                    normal.addLocal( getNormal(leftPoint, rootPoint, bottomPoint, scale, tmp1) );
                } else { // all middle columns
                    topPoint.set(0, getValue(c, r - 1), -1);
                    leftPoint.set(-1, getValue(c - 1, r), 0);
                    rightPoint.set(1, getValue(c + 1, r), 0);
                    bottomPoint.set(0, getValue(c, r + 1), 1);
                    
                    normal.set( getNormal(topPoint,  rootPoint, leftPoint, scale, tmp1 ) );
                    normal.addLocal( getNormal(leftPoint, rootPoint, bottomPoint, scale, tmp1) );
                    normal.addLocal( getNormal(bottomPoint, rootPoint, rightPoint, scale, tmp1) );
                    normal.addLocal( getNormal(rightPoint, rootPoint, topPoint, scale, tmp1) );
                }
            }
            normal.normalizeLocal();
            BufferUtils.setInBuffer(normal, store, (r * getWidth() + c)); // save the normal
        }
    }
    vars.release();
    
    return store;
}
 
Example 15
Source File: TangentBinormalGenerator.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static TriangleData processTriangle(int[] index,
        Vector3f[] v, Vector2f[] t)
{
    Vector3f edge1 = new Vector3f();
    Vector3f edge2 = new Vector3f();
    Vector2f edge1uv = new Vector2f();
    Vector2f edge2uv = new Vector2f();

    Vector3f tangent = new Vector3f();
    Vector3f binormal = new Vector3f();
    Vector3f normal = new Vector3f();

    t[1].subtract(t[0], edge1uv);
    t[2].subtract(t[0], edge2uv);
    float det = edge1uv.x*edge2uv.y - edge1uv.y*edge2uv.x;

    boolean normalize = false;
    if (Math.abs(det) < ZERO_TOLERANCE) {
        log.log(Level.WARNING, "Colinear uv coordinates for triangle " +
                "[{0}, {1}, {2}]; tex0 = [{3}, {4}], " +
                "tex1 = [{5}, {6}], tex2 = [{7}, {8}]",
                new Object[]{ index[0], index[1], index[2],
                t[0].x, t[0].y, t[1].x, t[1].y, t[2].x, t[2].y });
        det = 1;
        normalize = true;
    }

    v[1].subtract(v[0], edge1);
    v[2].subtract(v[0], edge2);

    tangent.set(edge1);
    tangent.normalizeLocal();
    binormal.set(edge2);
    binormal.normalizeLocal();

    if (Math.abs(Math.abs(tangent.dot(binormal)) - 1)
                    < ZERO_TOLERANCE)
    {
        log.log(Level.WARNING, "Vertices are on the same line " +
                "for triangle [{0}, {1}, {2}].",
                new Object[]{ index[0], index[1], index[2] });
    }

    float factor = 1/det;
    tangent.x = (edge2uv.y*edge1.x - edge1uv.y*edge2.x)*factor;
    tangent.y = (edge2uv.y*edge1.y - edge1uv.y*edge2.y)*factor;
    tangent.z = (edge2uv.y*edge1.z - edge1uv.y*edge2.z)*factor;
    if (normalize) tangent.normalizeLocal();

    binormal.x = (edge1uv.x*edge2.x - edge2uv.x*edge1.x)*factor;
    binormal.y = (edge1uv.x*edge2.y - edge2uv.x*edge1.y)*factor;
    binormal.z = (edge1uv.x*edge2.z - edge2uv.x*edge1.z)*factor;
    if (normalize) binormal.normalizeLocal();

    tangent.cross(binormal, normal);
    normal.normalizeLocal();

    return new TriangleData(
                    tangent,
                    binormal,
                    normal,
                    index[0], index[1], index[2]
                );
}
 
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;
}
 
Example 17
Source File: LODGeomap.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * 
 * @param v Takes 3 vertices: root, right, bottom
 * @param t Takes 3 tex coords: root, right, bottom
 * @param tangent that will store the result
 * @return the tangent store
 */
public static Vector3f calculateTangent(Vector3f[] v, Vector2f[] t, Vector3f tangent, Vector3f binormal) {
    Vector3f edge1 = new Vector3f(); // y=0
    Vector3f edge2 = new Vector3f(); // x=0
    Vector2f edge1uv = new Vector2f(); // y=0
    Vector2f edge2uv = new Vector2f(); // x=0

    t[2].subtract(t[0], edge2uv);
    t[1].subtract(t[0], edge1uv);

    float det = edge1uv.x * edge2uv.y;// - edge1uv.y*edge2uv.x;  = 0

    boolean normalize = true;
    if (Math.abs(det) < 0.0000001f) {
        det = 1;
        normalize = true;
    }

    v[1].subtract(v[0], edge1);
    v[2].subtract(v[0], edge2);

    tangent.set(edge1);
    tangent.normalizeLocal();
    binormal.set(edge2);
    binormal.normalizeLocal();

    float factor = 1 / det;
    tangent.x = (edge2uv.y * edge1.x) * factor;
    tangent.y = 0;
    tangent.z = (edge2uv.y * edge1.z) * factor;
    if (normalize) {
        tangent.normalizeLocal();
    }

    binormal.x = 0;
    binormal.y = (edge1uv.x * edge2.y) * factor;
    binormal.z = (edge1uv.x * edge2.z) * factor;
    if (normalize) {
        binormal.normalizeLocal();
    }

    return tangent;
}
 
Example 18
Source File: JMonkeyEngineTest.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
@Test
public void testVector() {
    Vector3f v = Vector3f.UNIT_X;
    v = v.add(0f, 2f, 0f);
    v.normalizeLocal();
}
 
Example 19
Source File: BufferUtils.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
/**
 * Normalize a Vector3f in-buffer.
 *
 * @param buf
 *            the buffer to find the Vector3f within
 * @param index
 *            the position (in terms of vectors, not floats) of the vector
 *            to normalize
 */
public static void normalizeVector3(FloatBuffer buf, int index) {
    TempVars vars = TempVars.get();
    Vector3f tempVec3 = vars.vect1;
    populateFromBuffer(tempVec3, buf, index);
    tempVec3.normalizeLocal();
    setInBuffer(tempVec3, buf, index);
    vars.release();
}
 
Example 20
Source File: BufferUtils.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 3 votes vote down vote up
/**
 * Normalize a Vector3f in-buffer.
 *
 * @param buf
 *            the buffer to find the Vector3f within
 * @param index
 *            the position (in terms of vectors, not floats) of the vector
 *            to normalize
 */
public static void normalizeVector3(FloatBuffer buf, int index) {
    TempVars vars = TempVars.get();
    Vector3f tempVec3 = vars.vect1;
    populateFromBuffer(tempVec3, buf, index);
    tempVec3.normalizeLocal();
    setInBuffer(tempVec3, buf, index);
    vars.release();
}