com.jme3.math.Vector3f Java Examples

The following examples show how to use com.jme3.math.Vector3f. 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: AbstractBox.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Gets the array or vectors representing the 8 vertices of the box.
 *
 * @return a newly created array of vertex vectors.
 */
protected final Vector3f[] computeVertices() {
    Vector3f[] axes = {
            Vector3f.UNIT_X.mult(xExtent),
            Vector3f.UNIT_Y.mult(yExtent),
            Vector3f.UNIT_Z.mult(zExtent)
    };
    return new Vector3f[] {
            center.subtract(axes[0]).subtractLocal(axes[1]).subtractLocal(axes[2]),
            center.add(axes[0]).subtractLocal(axes[1]).subtractLocal(axes[2]),
            center.add(axes[0]).addLocal(axes[1]).subtractLocal(axes[2]),
            center.subtract(axes[0]).addLocal(axes[1]).subtractLocal(axes[2]),
            center.add(axes[0]).subtractLocal(axes[1]).addLocal(axes[2]),
            center.subtract(axes[0]).subtractLocal(axes[1]).addLocal(axes[2]),
            center.add(axes[0]).addLocal(axes[1]).addLocal(axes[2]),
            center.subtract(axes[0]).addLocal(axes[1]).addLocal(axes[2])
    };
}
 
Example #2
Source File: TestExplosionEffect.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void createFlash(){
    flash = new ParticleEmitter("Flash", EMITTER_TYPE, 24 * COUNT_FACTOR);
    flash.setSelectRandomImage(true);
    flash.setStartColor(new ColorRGBA(1f, 0.8f, 0.36f, (float) (1f / COUNT_FACTOR_F)));
    flash.setEndColor(new ColorRGBA(1f, 0.8f, 0.36f, 0f));
    flash.setStartSize(.1f);
    flash.setEndSize(3.0f);
    flash.setShape(new EmitterSphereShape(Vector3f.ZERO, .05f));
    flash.setParticlesPerSec(0);
    flash.setGravity(0, 0, 0);
    flash.setLowLife(.2f);
    flash.setHighLife(.2f);
    flash.setInitialVelocity(new Vector3f(0, 5f, 0));
    flash.setVelocityVariation(1);
    flash.setImagesX(2);
    flash.setImagesY(2);
    Material mat = new Material(assetManager, "Common/MatDefs/Misc/Particle.j3md");
    mat.setTexture("Texture", assetManager.loadTexture("Effects/Explosion/flash.png"));
    mat.setBoolean("PointSprite", POINT_SPRITE);
    flash.setMaterial(mat);
    explosionEffect.attachChild(flash);
}
 
Example #3
Source File: GeometryBatchFactory.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static void doTransformTangents(FloatBuffer inBuf, int offset, int components, FloatBuffer outBuf, Matrix4f transform) {
    Vector3f tan = new Vector3f();

    // offset is given in element units
    // convert to be in component units
    offset *= components;

    for (int i = 0; i < inBuf.limit() / components; i++) {
        tan.x = inBuf.get(i * components + 0);
        tan.y = inBuf.get(i * components + 1);
        tan.z = inBuf.get(i * components + 2);

        transform.multNormal(tan, tan);

        outBuf.put(offset + i * components + 0, tan.x);
        outBuf.put(offset + i * components + 1, tan.y);
        outBuf.put(offset + i * components + 2, tan.z);

        if (components == 4) {
            outBuf.put(offset + i * components + 3, inBuf.get(i * components + 3));
        }
    }
}
 
Example #4
Source File: RollingTheMonkey.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void reset() {
    // Reset the pickups
    for(Spatial pickUp : pickUps.getChildren()) {
        GhostControl pickUpControl = pickUp.getControl(GhostControl.class);
        if(pickUpControl != null) {
            pickUpControl.setEnabled(true);
        }
        pickUp.setLocalScale(1.0f);
    }
    // Reset the player
    player.setPhysicsLocation(PLAYER_START.clone());
    player.setAngularVelocity(Vector3f.ZERO.clone());
    player.setLinearVelocity(Vector3f.ZERO.clone());
    // Reset the score
    score = 0;
    // Reset the message
    messageText.setLocalScale(0.0f);
}
 
Example #5
Source File: VehicleWheel.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void read(JmeImporter im) throws IOException {
    InputCapsule capsule = im.getCapsule(this);
    wheelSpatial = (Spatial) capsule.readSavable("wheelSpatial", null);
    frontWheel = capsule.readBoolean("frontWheel", false);
    location = (Vector3f) capsule.readSavable("wheelLocation", new Vector3f());
    direction = (Vector3f) capsule.readSavable("wheelDirection", new Vector3f());
    axle = (Vector3f) capsule.readSavable("wheelAxle", new Vector3f());
    suspensionStiffness = capsule.readFloat("suspensionStiffness", 20.0f);
    wheelsDampingRelaxation = capsule.readFloat("wheelsDampingRelaxation", 2.3f);
    wheelsDampingCompression = capsule.readFloat("wheelsDampingCompression", 4.4f);
    frictionSlip = capsule.readFloat("frictionSlip", 10.5f);
    rollInfluence = capsule.readFloat("rollInfluence", 1.0f);
    maxSuspensionTravelCm = capsule.readFloat("maxSuspensionTravelCm", 500f);
    maxSuspensionForce = capsule.readFloat("maxSuspensionForce", 6000f);
    radius = capsule.readFloat("wheelRadius", 0.5f);
    restLength = capsule.readFloat("restLength", 1f);
}
 
Example #6
Source File: TestTriangleStrip.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void simpleInitApp() {
    Geometry teaGeom = (Geometry) assetManager.loadModel("Models/Teapot/Teapot.obj");
    Mesh teaMesh = teaGeom.getMesh();
    ModelConverter.generateStrips(teaMesh, true, false, 24, 0);

    // show normals as material
    Material mat = new Material(assetManager, "Common/MatDefs/Misc/ShowNormals.j3md");

    for (int y = -10; y < 10; y++){
        for (int x = -10; x < 10; x++){
            Geometry teaClone = new Geometry("teapot", teaMesh);
            teaClone.setMaterial(mat);

            teaClone.setLocalTranslation(x * .5f, 0, y * .5f);
            teaClone.setLocalScale(.5f);

            rootNode.attachChild(teaClone);
        }
    }

    cam.setLocation(new Vector3f(8.378951f, 5.4324f, 8.795956f));
    cam.setRotation(new Quaternion(-0.083419204f, 0.90370524f, -0.20599906f, -0.36595422f));
}
 
Example #7
Source File: PhysicsRigidBody.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void write(JmeExporter e) throws IOException {
    super.write(e);
    OutputCapsule capsule = e.getCapsule(this);

    capsule.write(getMass(), "mass", 1.0f);

    capsule.write(getGravity(), "gravity", Vector3f.ZERO);
    capsule.write(getFriction(), "friction", 0.5f);
    capsule.write(getRestitution(), "restitution", 0);
    capsule.write(getAngularFactor(), "angularFactor", 1);
    capsule.write(kinematic, "kinematic", false);

    capsule.write(getLinearDamping(), "linearDamping", 0);
    capsule.write(getAngularDamping(), "angularDamping", 0);
    capsule.write(getLinearSleepingThreshold(), "linearSleepingThreshold", 0.8f);
    capsule.write(getAngularSleepingThreshold(), "angularSleepingThreshold", 1.0f);

    capsule.write(getCcdMotionThreshold(), "ccdMotionThreshold", 0);
    capsule.write(getCcdSweptSphereRadius(), "ccdSweptSphereRadius", 0);

    capsule.write(getPhysicsLocation(new Vector3f()), "physicsLocation", new Vector3f());
    capsule.write(getPhysicsRotationMatrix(new Matrix3f()), "physicsRotation", new Matrix3f());

    capsule.writeSavableArrayList(joints, "joints", null);
}
 
Example #8
Source File: SceneEditorController.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void moveUndo(final Spatial spatial, final Vector3f before, final Vector3f after, final AbstractSceneExplorerNode parentNode) {
    if (spatial != null && before != null) {
        Lookup.getDefault().lookup(SceneUndoRedoManager.class).addEdit(this, new AbstractUndoableSceneEdit() {
            
            @Override
            public void sceneUndo() throws CannotUndoException {
                //undo stuff here
                spatial.setLocalTranslation(before);
            }
            
            @Override
            public void sceneRedo() throws CannotRedoException {
                //redo stuff here
                spatial.setLocalTranslation(after);
            }
        });
    }
}
 
Example #9
Source File: CohesionBehavior.java    From MonkeyBrains with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * @see AbstractSteeringBehavior#calculateSteering()
 */
@Override
protected Vector3f calculateRawSteering() {
    // steering accumulator and count of neighbors, both initially zero
    Vector3f steering = new Vector3f();
    int realNeighbors = 0;

    // for each of the other vehicles...
    for (GameEntity neighbour : this.neighbours) {
        if (this.agent.inBoidNeighborhood(neighbour, this.agent.getRadius() * 3, this.maxDistance, this.maxAngle)) {
            // accumulate sum of neighbor's positions
            steering = steering.add(neighbour.getLocalTranslation());
            realNeighbors++;
        }
    }

    // divide by neighbors, subtract off current position to get error-correcting direction
    if (realNeighbors > 0) {
        steering = steering.divide(realNeighbors);
        steering = this.agent.offset(steering);
    }
    return steering;
}
 
Example #10
Source File: SceneToolController.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected void attachSelectionShape(Spatial spat) {
    if (selectionShape != null) {
        selectionShape.removeFromParent();
        selectionShape = null;
    }
    selctionShapeOffset.set(Vector3f.ZERO);
    if (spat instanceof ParticleEmitter) {
        attachBoxSelection(spat);

    } else if (spat instanceof Geometry) {
        attachGeometrySelection((Geometry) spat);
    } else if (spat.getControl(PhysicsControl.class) != null) {
        attachPhysicsSelection(spat);
    } else {
        attachBoxSelection(spat);
    }
}
 
Example #11
Source File: TestReverb.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void simpleUpdate(float tpf) {
  time += tpf;

  if (time > nextTime) {
    Vector3f v = new Vector3f();
    v.setX(FastMath.nextRandomFloat());
    v.setY(FastMath.nextRandomFloat());
    v.setZ(FastMath.nextRandomFloat());
    v.multLocal(40, 2, 40);
    v.subtractLocal(20, 1, 20);

    audioSource.setLocalTranslation(v);
    audioSource.playInstance();
    time = 0;
    nextTime = FastMath.nextRandomFloat() * 2 + 0.5f;
  }
}
 
Example #12
Source File: SceneToolController.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected void attachBoxSelection(Spatial geom) {
    BoundingVolume bound = geom.getWorldBound();
    if (bound instanceof BoundingBox) {
        BoundingBox bbox = (BoundingBox) bound;
        Vector3f extent = new Vector3f();
        bbox.getExtent(extent);
        WireBox wireBox = new WireBox();
        wireBox.fromBoundingBox(bbox);
        selctionShapeOffset.set(bbox.getCenter()).subtractLocal(geom.getWorldTranslation());
        Geometry selectionGeometry = new Geometry("selection_geometry_sceneviewer", wireBox);
        selectionGeometry.setMaterial(blueMat);
        selectionGeometry.setLocalTransform(geom.getWorldTransform());
        selectionGeometry.setLocalTranslation(bbox.getCenter());
        toolsNode.attachChild(selectionGeometry);
        selectionShape = selectionGeometry;

    }
}
 
Example #13
Source File: PhysicsCharacter.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * De-serialize this character from the specified importer, for example when
 * loading from a J3O file.
 *
 * @param e importer (not null)
 * @throws IOException from importer
 */
@Override
public void read(JmeImporter e) throws IOException {
    super.read(e);
    InputCapsule capsule = e.getCapsule(this);
    stepHeight = capsule.readFloat("stepHeight", 1.0f);
    buildObject();
    setGravity(capsule.readFloat("gravity", 9.8f * 3));
    setMaxSlope(capsule.readFloat("maxSlope", 1.0f));
    setFallSpeed(capsule.readFloat("fallSpeed", 55.0f));
    setJumpSpeed(capsule.readFloat("jumpSpeed", 10.0f));
    setUpAxis(capsule.readInt("upAxis", 1));
    setCcdMotionThreshold(capsule.readFloat("ccdMotionThreshold", 0));
    setCcdSweptSphereRadius(capsule.readFloat("ccdSweptSphereRadius", 0));
    setPhysicsLocation((Vector3f) capsule.readSavable("physicsLocation", new Vector3f()));
}
 
Example #14
Source File: EmitterMeshFaceShape.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void setMeshes(List<Mesh> meshes) {
    this.vertices = new ArrayList<List<Vector3f>>(meshes.size());
    this.normals = new ArrayList<List<Vector3f>>(meshes.size());
    for (Mesh mesh : meshes) {
        Vector3f[] vertexTable = BufferUtils.getVector3Array(mesh.getFloatBuffer(Type.Position));
        int[] indices = new int[3];
        List<Vector3f> vertices = new ArrayList<Vector3f>(mesh.getTriangleCount() * 3);
        List<Vector3f> normals = new ArrayList<Vector3f>(mesh.getTriangleCount());
        for (int i = 0; i < mesh.getTriangleCount(); ++i) {
            mesh.getTriangle(i, indices);
            vertices.add(vertexTable[indices[0]]);
            vertices.add(vertexTable[indices[1]]);
            vertices.add(vertexTable[indices[2]]);
            normals.add(FastMath.computeNormal(vertexTable[indices[0]], vertexTable[indices[1]], vertexTable[indices[2]]));
        }
        this.vertices.add(vertices);
        this.normals.add(normals);
    }
}
 
Example #15
Source File: HelloPhysics.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void simpleInitApp() {
  /** Set up Physics Game */
  bulletAppState = new BulletAppState();
  stateManager.attach(bulletAppState);
  //bulletAppState.getPhysicsSpace().enableDebug(assetManager);
  /** Configure cam to look at scene */
  cam.setLocation(new Vector3f(0, 4f, 6f));
  cam.lookAt(new Vector3f(2, 2, 0), Vector3f.UNIT_Y);
  /** Initialize the scene, materials, inputs, and physics space */
  initInputs();
  initMaterials();
  initWall();
  initFloor();
  initCrossHairs();
}
 
Example #16
Source File: BetterCharacterControl.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * This checks if the character can go from ducked to unducked state by
 * doing a ray test.
 */
protected boolean checkCanUnDuck() {
    TempVars vars = TempVars.get();
    Vector3f location = vars.vect1;
    Vector3f rayVector = vars.vect2;
    location.set(localUp).multLocal(FastMath.ZERO_TOLERANCE).addLocal(this.location);
    rayVector.set(localUp).multLocal(height + FastMath.ZERO_TOLERANCE).addLocal(location);
    List<PhysicsRayTestResult> results = space.rayTest(location, rayVector);
    vars.release();
    for (PhysicsRayTestResult physicsRayTestResult : results) {
        if (!physicsRayTestResult.getCollisionObject().equals(rigidBody)) {
            return false;
        }
    }
    return true;
}
 
Example #17
Source File: TestIssue877.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void simpleUpdate(float tpf) {
    if (timeToNextPrint > 0f) {
        timeToNextPrint -= tpf;
        return;
    }

    if (numFalling > 0) {
        Vector3f fallingLocation = falling[0].getWorldTranslation();
        System.out.printf("  falling[0] location(x=%f, z=%f)",
                fallingLocation.x, fallingLocation.z);
        /*
         * If an object is falling vertically, its X- and Z-coordinates 
         * should not change.
         */
    }
    if (numPendulums > 0) {
        Vector3f bobLocation = bobs[0].getWorldTranslation();
        Vector3f pivotLocation = pivots[0].getWorldTranslation();
        float distance = bobLocation.distance(pivotLocation);
        System.out.printf("  bob[0] distance=%f", distance);
        /*
         * If the hinge is working properly, the distance from the
         * pivot to the bob should remain roughly constant.
         */
    }
    System.out.println();
    timeToNextPrint = 1f;
}
 
Example #18
Source File: SixDofJoint.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void write(JmeExporter ex) throws IOException {
    super.write(ex);
    OutputCapsule capsule = ex.getCapsule(this);
    capsule.write(angularUpperLimit, "angularUpperLimit", new Vector3f(Vector3f.POSITIVE_INFINITY));
    capsule.write(angularLowerLimit, "angularLowerLimit", new Vector3f(Vector3f.NEGATIVE_INFINITY));
    capsule.write(linearUpperLimit, "linearUpperLimit", new Vector3f(Vector3f.POSITIVE_INFINITY));
    capsule.write(linearLowerLimit, "linearLowerLimit", new Vector3f(Vector3f.NEGATIVE_INFINITY));
    int i = 0;
    for (Iterator<RotationalLimitMotor> it = rotationalMotors.iterator(); it.hasNext();) {
        RotationalLimitMotor rotationalLimitMotor = it.next();
        capsule.write(rotationalLimitMotor.getBounce(), "rotMotor" + i + "_Bounce", 0.0f);
        capsule.write(rotationalLimitMotor.getDamping(), "rotMotor" + i + "_Damping", 1.0f);
        capsule.write(rotationalLimitMotor.getERP(), "rotMotor" + i + "_ERP", 0.5f);
        capsule.write(rotationalLimitMotor.getHiLimit(), "rotMotor" + i + "_HiLimit", Float.POSITIVE_INFINITY);
        capsule.write(rotationalLimitMotor.getLimitSoftness(), "rotMotor" + i + "_LimitSoftness", 0.5f);
        capsule.write(rotationalLimitMotor.getLoLimit(), "rotMotor" + i + "_LoLimit", Float.NEGATIVE_INFINITY);
        capsule.write(rotationalLimitMotor.getMaxLimitForce(), "rotMotor" + i + "_MaxLimitForce", 300.0f);
        capsule.write(rotationalLimitMotor.getMaxMotorForce(), "rotMotor" + i + "_MaxMotorForce", 0.1f);
        capsule.write(rotationalLimitMotor.getTargetVelocity(), "rotMotor" + i + "_TargetVelocity", 0);
        capsule.write(rotationalLimitMotor.isEnableMotor(), "rotMotor" + i + "_EnableMotor", false);
        i++;
    }
    capsule.write(getTranslationalLimitMotor().getAccumulatedImpulse(), "transMotor_AccumulatedImpulse", Vector3f.ZERO);
    capsule.write(getTranslationalLimitMotor().getDamping(), "transMotor_Damping", 1.0f);
    capsule.write(getTranslationalLimitMotor().getLimitSoftness(), "transMotor_LimitSoftness", 0.7f);
    capsule.write(getTranslationalLimitMotor().getLowerLimit(), "transMotor_LowerLimit", Vector3f.ZERO);
    capsule.write(getTranslationalLimitMotor().getRestitution(), "transMotor_Restitution", 0.5f);
    capsule.write(getTranslationalLimitMotor().getUpperLimit(), "transMotor_UpperLimit", Vector3f.ZERO);
}
 
Example #19
Source File: TestNormalMapping.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void simpleUpdate(float tpf){
    angle += tpf * 0.25f;
    angle %= FastMath.TWO_PI;

    pl.setPosition(new Vector3f(FastMath.cos(angle) * 4f, 0.5f, FastMath.sin(angle) * 4f));
    lightMdl.setLocalTranslation(pl.getPosition());
}
 
Example #20
Source File: TestBrickWall.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void initFloor() {
    Box floorBox = new Box(Vector3f.ZERO, 10f, 0.1f, 5f);
    floorBox.scaleTextureCoordinates(new Vector2f(3, 6));

    Geometry floor = new Geometry("floor", floorBox);
    floor.setMaterial(mat3);
    floor.setShadowMode(ShadowMode.Receive);
    floor.setLocalTranslation(0, -0.1f, 0);
    floor.addControl(new RigidBodyControl(new BoxCollisionShape(new Vector3f(10f, 0.1f, 5f)), 0));
    this.rootNode.attachChild(floor);
    this.getPhysicsSpace().add(floor);
}
 
Example #21
Source File: SpotLight.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void write(JmeExporter ex) throws IOException {
    super.write(ex);
    OutputCapsule oc = ex.getCapsule(this);
    oc.write(direction, "direction", new Vector3f());
    oc.write(position, "position", new Vector3f());
    oc.write(spotInnerAngle, "spotInnerAngle", FastMath.QUARTER_PI / 8);
    oc.write(spotOuterAngle, "spotOuterAngle", FastMath.QUARTER_PI / 6);
    oc.write(spotRange, "spotRange", 100);
}
 
Example #22
Source File: TestRenderToTexture.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public Texture setupOffscreenView(){
    Camera offCamera = new Camera(512, 512);

    offView = renderManager.createPreView("Offscreen View", offCamera);
    offView.setClearFlags(true, true, true);
    offView.setBackgroundColor(ColorRGBA.DarkGray);

    // create offscreen framebuffer
    FrameBuffer offBuffer = new FrameBuffer(512, 512, 1);

    //setup framebuffer's cam
    offCamera.setFrustumPerspective(45f, 1f, 1f, 1000f);
    offCamera.setLocation(new Vector3f(0f, 0f, -5f));
    offCamera.lookAt(new Vector3f(0f, 0f, 0f), Vector3f.UNIT_Y);

    //setup framebuffer's texture
    Texture2D offTex = new Texture2D(512, 512, Format.RGBA8);
    offTex.setMinFilter(Texture.MinFilter.Trilinear);
    offTex.setMagFilter(Texture.MagFilter.Bilinear);

    //setup framebuffer to use texture
    offBuffer.setDepthBuffer(Format.Depth);
    offBuffer.setColorTexture(offTex);
    
    //set viewport to render to offscreen framebuffer
    offView.setOutputFrameBuffer(offBuffer);

    // setup framebuffer's scene
    Box boxMesh = new Box(1, 1, 1);
    Material material = assetManager.loadMaterial("Interface/Logo/Logo.j3m");
    offBox = new Geometry("box", boxMesh);
    offBox.setMaterial(material);

    // attach the scene to the viewport to be rendered
    offView.attachScene(offBox);
    
    return offTex;
}
 
Example #23
Source File: SkeletonWire.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void updateGeometry(){
    VertexBuffer vb = getBuffer(Type.Position);
    FloatBuffer posBuf = getFloatBuffer(Type.Position);
    posBuf.clear();
    for (int i = 0; i < skeleton.getBoneCount(); i++){
        Bone bone = skeleton.getBone(i);
        Vector3f bonePos = bone.getModelSpacePosition();

        posBuf.put(bonePos.getX()).put(bonePos.getY()).put(bonePos.getZ());
    }
    posBuf.flip();
    vb.updateData(posBuf);

    updateBound();
}
 
Example #24
Source File: DirectionalLightShadowRenderer.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void init(int nbSplits, int shadowMapSize) {
    nbShadowMaps = Math.max(Math.min(nbSplits, 4), 1);
    if (nbShadowMaps != nbSplits) {
        throw new IllegalArgumentException("Number of splits must be between 1 and 4. Given value : " + nbSplits);
    }
    splits = new ColorRGBA();
    splitsArray = new float[nbSplits + 1];
    shadowCam = new Camera(shadowMapSize, shadowMapSize);
    shadowCam.setParallelProjection(true);
    for (int i = 0; i < points.length; i++) {
        points[i] = new Vector3f();
    }
}
 
Example #25
Source File: Slider.java    From Lemur with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 *  Returns the slider range value for the specified location
 *  in the slider's local coordinate system.  (For example,
 *  for world space location use slider.worldToLocal() first.)
 */
public double getValueForLocation( Vector3f loc ) {

    Vector3f relative = loc.subtract(range.getLocalTranslation());

    // Components always grow down from their location
    // so we'll invert y
    relative.y *= -1;
            
    Vector3f axisDir = axis.getDirection();
    double projection = relative.dot(axisDir);
    if( projection < 0 ) {
        if( axis == Axis.Y ) {
            return model.getMaximum();
        } else {
            return model.getMinimum();
        }
    }
    
    Vector3f rangeSize = range.getSize().clone();
     
    double rangeLength = rangeSize.dot(axisDir);
    projection = Math.min(projection, rangeLength);
    double part = projection / rangeLength;       
    double rangeDelta = model.getMaximum() - model.getMinimum();
    
    // For the y-axis, the slider is inverted from the direction
    // that the component's grow... so our part is backwards
    if( axis == Axis.Y ) {
        part = 1 - part;
    }
 
    return model.getMinimum() + rangeDelta * part;        
}
 
Example #26
Source File: TestRagdollCharacter.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void initWall(float bLength, float bWidth, float bHeight) {
    Box brick = new Box(bLength, bHeight, bWidth);
    brick.scaleTextureCoordinates(new Vector2f(1f, 0.5f));
    Material mat2 = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
    TextureKey key = new TextureKey("Textures/Terrain/BrickWall/BrickWall.jpg");
    key.setGenerateMips(true);
    Texture tex = assetManager.loadTexture(key);
    mat2.setTexture("ColorMap", tex);

    float startpt = bLength / 4f;
    float height = -5f;
    for (int j = 0; j < 15; j++) {
        for (int i = 0; i < 4; i++) {
            Vector3f ori = new Vector3f(i * bLength * 2f + startpt, bHeight + height, -10f);
            Geometry reBoxg = new Geometry("brick", brick);
            reBoxg.setMaterial(mat2);
            reBoxg.setLocalTranslation(ori);
            //for geometry with sphere mesh the physics system automatically uses a sphere collision shape
            reBoxg.addControl(new RigidBodyControl(1.5f));
            reBoxg.setShadowMode(ShadowMode.CastAndReceive);
            reBoxg.getControl(RigidBodyControl.class).setFriction(0.6f);
            this.rootNode.attachChild(reBoxg);
            physicsSpace.add(reBoxg);
        }
        startpt = -startpt;
        height += 2f * bHeight;
    }
}
 
Example #27
Source File: HelloPicking.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void onAction(String name, boolean keyPressed, float tpf) {
  if (name.equals("Shoot") && !keyPressed) {
    // 1. Reset results list.
    CollisionResults results = new CollisionResults();
    // 2. Aim the ray from cam loc to cam direction.
    Ray ray = new Ray(cam.getLocation(), cam.getDirection());
    // 3. Collect intersections between Ray and Shootables in results list.
    shootables.collideWith(ray, results);
    // 4. Print the results
    System.out.println("----- Collisions? " + results.size() + "-----");
    for (int i = 0; i < results.size(); i++) {
      // For each hit, we know distance, impact point, name of geometry.
      float dist = results.getCollision(i).getDistance();
      Vector3f pt = results.getCollision(i).getContactPoint();
      String hit = results.getCollision(i).getGeometry().getName();
      System.out.println("* Collision #" + i);
      System.out.println("  You shot " + hit + " at " + pt + ", " + dist + " wu away.");
    }
    // 5. Use the results (we mark the hit object)
    if (results.size() > 0) {
      // The closest collision point is what was truly hit:
      CollisionResult closest = results.getClosestCollision();
      // Let's interact - we mark the hit with a red dot.
      mark.setLocalTranslation(closest.getContactPoint());
      rootNode.attachChild(mark);
    } else {
      // No hits? Then remove the red mark.
      rootNode.detachChild(mark);
    }
  }
}
 
Example #28
Source File: HideBehavior.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 = Vector3f.ZERO;

    GameEntity closestObstacle = null;
    float closestDistanceFromAgent = Float.POSITIVE_INFINITY;

    for (GameEntity obstacle : this.obstacles) {
        if (obstacle != this.agent) {
            float distanceFromAgent = this.agent.distanceRelativeToGameEntity(obstacle);

            if (distanceFromAgent < closestDistanceFromAgent && obstacle.getRadius() >= this.agent.getRadius()) {
                closestObstacle = obstacle;
                closestDistanceFromAgent = distanceFromAgent;
            }
        }
    }

    if (closestObstacle != null && this.agent.distanceRelativeToGameEntity(closestObstacle) > closestObstacle.getRadius()) {
        Vector3f targetToObstacleOffset = this.target.offset(closestObstacle);
        Vector3f seekPos = this.target.getLocalTranslation().add(targetToObstacleOffset).add(
                targetToObstacleOffset.normalize().mult(this.separationFromObstacle));

        SeekBehavior seek = new SeekBehavior(this.agent, seekPos);
        return seek.calculateRawSteering();
    }

    return steer;
}
 
Example #29
Source File: VehicleWheel.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public VehicleWheel(Vector3f location, Vector3f direction, Vector3f axle,
        float restLength, float radius, boolean frontWheel) {
    this.location.set(location);
    this.direction.set(direction);
    this.axle.set(axle);
    this.frontWheel = frontWheel;
    this.restLength = restLength;
    this.radius = radius;
}
 
Example #30
Source File: GImpactCollisionShape.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void createCollisionMesh(Mesh mesh, Vector3f worldScale) {
    this.worldScale = worldScale;
    bulletMesh = Converter.convert(mesh);
    this.numVertices = bulletMesh.numVertices;
    this.numTriangles = bulletMesh.numTriangles;
    this.vertexStride = bulletMesh.vertexStride;
    this.triangleIndexStride = bulletMesh.triangleIndexStride;
    this.triangleIndexBase = bulletMesh.triangleIndexBase;
    this.vertexBase = bulletMesh.vertexBase;
    createShape();
}