Java Code Examples for com.jme3.scene.Spatial#setLocalTranslation()

The following examples show how to use com.jme3.scene.Spatial#setLocalTranslation() . 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: EditorRenderer.java    From OpenRTS with MIT License 6 votes vote down vote up
private void drawHeightPencil() {
	List<Tile> tiles = ToolManager.getHeightTool().pencil.getNodes();
	int index = 0;
	for (Spatial s : HeightPencilNode.getChildren()) {
		if (index < tiles.size()) {
			Point3D start = tiles.get(index).getPos();
			Point3D end = tiles.get(index).getPos().getAddition(0, 0, 0.5);
			Line l = new Line(TranslateUtil.toVector3f(start), TranslateUtil.toVector3f(end));
			l.setLineWidth(PENCIL_THICKNESS);
			((Geometry) s).setMesh(l);
			s.setLocalTranslation(Vector3f.ZERO);
			// s.setLocalTranslation(Translator.toVector3f(tiles.get(index).getPos2D(), (float)toolManager.selector.getElevation()+0.1f));
		} else {
			s.setLocalTranslation(new Vector3f(-1000, -1000, 0));
		}
		index++;
	}
}
 
Example 2
Source File: SceneEditorController.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void doAddModel(Spatial file, Node selected, Vector3f location) {
    ProgressHandle progressHandle = ProgressHandleFactory.createHandle("Adding Model..");
    progressHandle.start();
    try {
        if (file != null) {
            selected.attachChild(file);
            if (location != null) {
                Vector3f localVec = new Vector3f();
                selected.worldToLocal(location, localVec);
                file.setLocalTranslation(localVec);
            }
        }
        refreshSelected();
        addSpatialUndo(selected, file, null, selectedSpat);
    } catch (Exception ex) {
        Confirmation msg = new NotifyDescriptor.Confirmation(
                "Error importing " + file.getName() + "\n" + ex.toString(),
                NotifyDescriptor.OK_CANCEL_OPTION,
                NotifyDescriptor.ERROR_MESSAGE);
        DialogDisplayer.getDefault().notifyLater(msg);
    }
    progressHandle.finish();
    
}
 
Example 3
Source File: RigidBodyMotionState.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * applies the current transform to the given jme Node if the location has been updated on the physics side
 * @param spatial
 */
public boolean applyTransform(Spatial spatial) {
    if (!physicsLocationDirty) {
        return false;
    }
    if (!applyPhysicsLocal && spatial.getParent() != null) {
        localLocation.set(worldLocation).subtractLocal(spatial.getParent().getWorldTranslation());
        localLocation.divideLocal(spatial.getParent().getWorldScale());
        tmp_inverseWorldRotation.set(spatial.getParent().getWorldRotation()).inverseLocal().multLocal(localLocation);

        localRotationQuat.set(worldRotationQuat);
        tmp_inverseWorldRotation.set(spatial.getParent().getWorldRotation()).inverseLocal().mult(localRotationQuat, localRotationQuat);

        spatial.setLocalTranslation(localLocation);
        spatial.setLocalRotation(localRotationQuat);
    } else {
        spatial.setLocalTranslation(worldLocation);
        spatial.setLocalRotation(worldRotationQuat);
    }
    physicsLocationDirty = false;
    return true;
}
 
Example 4
Source File: MapDrawer.java    From OpenRTS with MIT License 5 votes vote down vote up
private void attachManmadeCliff(Cliff c) {
	Node n = new Node();
	tilesSpatial.get(c.getTile()).add(n);
	castAndReceiveNode.attachChild(n);

	ManmadeFace face = (ManmadeFace) (c.face);
	Spatial s = getModel(face.modelPath);
	if (s == null) {
		logger.warning("Can't find model " + face.modelPath);
		return;
	}
	switch (c.type) {
		case Orthogonal:
			s.rotate(0, 0, (float) (c.angle + AngleUtil.RIGHT));
			break;
		case Salient:
			s.rotate(0, 0, (float) (c.angle + AngleUtil.RIGHT));
			break;
		case Corner:
			s.rotate(0, 0, (float) (c.angle));
			break;
		default:
			break;
	}
	s.scale(0.005f);
	s.setLocalTranslation((float)c.getTile().getCoord().x + 0.5f, (float)c.getTile().getCoord().y + 0.5f, (float) (c.level * Tile.STAGE_HEIGHT) + 0.1f);
	n.attachChild(s);
}
 
Example 5
Source File: RigidBodyMotionState.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
     * If the motion state has been updated, apply the new transform to the
     * specified spatial.
     *
     * @param spatial where to apply the physics transform (not null, modified)
     * @return true if changed
     */
    public boolean applyTransform(Spatial spatial) {
        Vector3f localLocation = spatial.getLocalTranslation();
        Quaternion localRotationQuat = spatial.getLocalRotation();
        boolean physicsLocationDirty = applyTransform(motionStateId, localLocation, localRotationQuat);
        if (!physicsLocationDirty) {
            return false;
        }
        if (!applyPhysicsLocal && spatial.getParent() != null) {
            localLocation.subtractLocal(spatial.getParent().getWorldTranslation());
            localLocation.divideLocal(spatial.getParent().getWorldScale());
            tmp_inverseWorldRotation.set(spatial.getParent().getWorldRotation()).inverseLocal().multLocal(localLocation);

//            localRotationQuat.set(worldRotationQuat);
            tmp_inverseWorldRotation.mult(localRotationQuat, localRotationQuat);

            spatial.setLocalTranslation(localLocation);
            spatial.setLocalRotation(localRotationQuat);
        } else {
            spatial.setLocalTranslation(localLocation);
            spatial.setLocalRotation(localRotationQuat);
//            spatial.setLocalTranslation(worldLocation);
//            spatial.setLocalRotation(worldRotationQuat);
        }
        if (vehicle != null) {
            vehicle.updateWheels();
        }
        return true;
    }
 
Example 6
Source File: TestSpotLight.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void setupSignpost(){
    Spatial signpost = assetManager.loadModel("Models/Sign Post/Sign Post.mesh.xml");
    Material mat = assetManager.loadMaterial("Models/Sign Post/Sign Post.j3m");
  //   mat.setBoolean("VertexLighting", true);
    signpost.setMaterial(mat);
    signpost.rotate(0, FastMath.HALF_PI, 0);
    signpost.setLocalTranslation(12, 3.5f, 30);
    signpost.setLocalScale(4);
    signpost.setShadowMode(ShadowMode.CastAndReceive);
    TangentBinormalGenerator.generate(signpost);
    rootNode.attachChild(signpost);
}
 
Example 7
Source File: MoveToolControl.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
/**
 * Process of moving objects.
 *
 * @param pickedAxis  the moving axis.
 * @param toTransform the moving object.
 * @param transform   the transform's center.
 * @param distance    the moving distance.
 */
private void translateObjects(@NotNull final PickedAxis pickedAxis, @NotNull final Spatial toTransform,
                              @NotNull final Transform transform, final float distance) {

    final Node parentNode = getParentNode();
    final Node childNode = getChildNode();

    final EditorTransformSupport editorControl = getEditorControl();
    final Quaternion rotation = parentNode.getLocalRotation();

    final LocalObjects local = LocalObjects.get();
    final Vector3f currentLocation = local.nextVector(parentNode.getLocalTranslation());

    if (Config.DEV_TRANSFORMS_DEBUG) {
        System.out.println("distance " + distance);
    }

    if (pickedAxis == PickedAxis.X) {
        currentLocation.addLocal(getLeft(rotation, local.nextVector()).multLocal(distance));
    } else if (pickedAxis == PickedAxis.Y) {
        currentLocation.addLocal(getUp(rotation, local.nextVector()).multLocal(distance));
    } else if (pickedAxis == PickedAxis.Z) {
        currentLocation.addLocal(getDirection(rotation, local.nextVector()).multLocal(distance));
    }

    parentNode.setLocalTranslation(currentLocation);

    toTransform.setLocalTranslation(childNode.getWorldTranslation());
    editorControl.notifyTransformed(toTransform);
}
 
Example 8
Source File: TestTextureAtlas.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void simpleInitApp() {
    flyCam.setMoveSpeed(50);
    Node scene = new Node("Scene");
    Spatial obj1 = assetManager.loadModel("Models/Ferrari/Car.scene");
    obj1.setLocalTranslation(-4, 0, 0);
    Spatial obj2 = assetManager.loadModel("Models/Oto/Oto.mesh.xml");
    obj2.setLocalTranslation(-2, 0, 0);
    Spatial obj3 = assetManager.loadModel("Models/Ninja/Ninja.mesh.xml");
    obj3.setLocalTranslation(-0, 0, 0);
    Spatial obj4 = assetManager.loadModel("Models/Sinbad/Sinbad.mesh.xml");
    obj4.setLocalTranslation(2, 0, 0);
    Spatial obj5 = assetManager.loadModel("Models/Tree/Tree.mesh.j3o");
    obj5.setLocalTranslation(4, 0, 0);
    scene.attachChild(obj1);
    scene.attachChild(obj2);
    scene.attachChild(obj3);
    scene.attachChild(obj4);
    scene.attachChild(obj5);

    Geometry geom = TextureAtlas.makeAtlasBatch(scene, assetManager, 2048);

    AmbientLight al = new AmbientLight();
    rootNode.addLight(al);

    DirectionalLight sun = new DirectionalLight();
    sun.setDirection(new Vector3f(0.69077975f, -0.6277887f, -0.35875428f).normalizeLocal());
    sun.setColor(ColorRGBA.White.clone().multLocal(2));
    rootNode.addLight(sun);

    rootNode.attachChild(geom);

    //quad to display material
    Geometry box = new Geometry("displayquad", new Quad(4, 4));
    box.setMaterial(geom.getMaterial());
    box.setLocalTranslation(0, 1, 3);
    rootNode.attachChild(box);
}
 
Example 9
Source File: TestPostFilters.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void setupSignpost() {
    Spatial signpost = assetManager.loadModel("Models/Sign Post/Sign Post.mesh.xml");
    Material mat = assetManager.loadMaterial("Models/Sign Post/Sign Post.j3m");
    signpost.setMaterial(mat);
    signpost.rotate(0, FastMath.HALF_PI, 0);
    signpost.setLocalTranslation(12, 3.5f, 30);
    signpost.setLocalScale(4);
    signpost.setShadowMode(ShadowMode.CastAndReceive);
    rootNode.attachChild(signpost);
}
 
Example 10
Source File: TestEverything.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void setupSignpost(){
    Spatial signpost = assetManager.loadModel("Models/Sign Post/Sign Post.mesh.xml");
    Material mat = assetManager.loadMaterial("Models/Sign Post/Sign Post.j3m");
    signpost.setMaterial(mat);
    signpost.rotate(0, FastMath.HALF_PI, 0);
    signpost.setLocalTranslation(12, 3.5f, 30);
    signpost.setLocalScale(4);
    signpost.setShadowMode(ShadowMode.CastAndReceive);
    rootNode.attachChild(signpost);
}
 
Example 11
Source File: HelloAssets.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void simpleInitApp() {

    /** Load a teapot model (OBJ file from test-data) */
    Spatial teapot = assetManager.loadModel("Models/Teapot/Teapot.obj");
    Material mat_default = new Material( assetManager, "Common/MatDefs/Misc/ShowNormals.j3md");
    teapot.setMaterial(mat_default);
    rootNode.attachChild(teapot);

    /** Create a wall (Box with material and texture from test-data) */
    Box box = new Box(2.5f, 2.5f, 1.0f);
    Spatial wall = new Geometry("Box", box );
    Material mat_brick = new Material( assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
    mat_brick.setTexture("ColorMap", assetManager.loadTexture("Textures/Terrain/BrickWall/BrickWall.jpg"));
    wall.setMaterial(mat_brick);
    wall.setLocalTranslation(2.0f,-2.5f,0.0f);
    rootNode.attachChild(wall);

    /** Display a line of text (default font from test-data) */
    setDisplayStatView(false);
    guiFont = assetManager.loadFont("Interface/Fonts/Default.fnt");
    BitmapText helloText = new BitmapText(guiFont, false);
    helloText.setSize(guiFont.getCharSet().getRenderedSize());
    helloText.setText("Hello World");
    helloText.setLocalTranslation(300, helloText.getLineHeight(), 0);
    guiNode.attachChild(helloText);

    /** Load a Ninja model (OgreXML + material + texture from test_data) */
    Spatial ninja = assetManager.loadModel("Models/Ninja/Ninja.mesh.xml");
    ninja.scale(0.05f, 0.05f, 0.05f);
    ninja.rotate(0.0f, -3.0f, 0.0f);
    ninja.setLocalTranslation(0.0f, -5.0f, -2.0f);
    rootNode.attachChild(ninja);
    /** You must add a light to make the model visible */
    DirectionalLight sun = new DirectionalLight();
    sun.setDirection(new Vector3f(-0.1f, -0.7f, -1.0f).normalizeLocal());
    rootNode.addLight(sun);
}
 
Example 12
Source File: TestMousePick.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected Spatial makeCharacter() {
    // load a character from jme3test-test-data
    Spatial golem = assetManager.loadModel("Models/Oto/Oto.mesh.xml");
    golem.scale(0.5f);
    golem.setLocalTranslation(-1.0f, -1.5f, -0.6f);

    // We must add a light to make the model visible
    DirectionalLight sun = new DirectionalLight();
    sun.setDirection(new Vector3f(-0.1f, -0.7f, -1.0f).normalizeLocal());
    golem.addLight(sun);
    return golem;
}
 
Example 13
Source File: TestMousePick.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected Spatial makeCharacter() {
    // load a character from jme3test-test-data
    Spatial golem = assetManager.loadModel("Models/Oto/Oto.mesh.xml");
    golem.scale(0.5f);
    golem.setLocalTranslation(-1.0f, -1.5f, -0.6f);

    // We must add a light to make the model visible
    DirectionalLight sun = new DirectionalLight();
    sun.setDirection(new Vector3f(-0.1f, -0.7f, -1.0f).normalizeLocal());
    golem.addLight(sun);
    return golem;
}
 
Example 14
Source File: TerrainGridAlphaMapTest.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void updateMarkerElevations() {
    for (Spatial s : markers.getChildren()) {
        float h = terrain.getHeight(new Vector2f(s.getLocalTranslation().x, s.getLocalTranslation().z));
        s.setLocalTranslation(s.getLocalTranslation().x, h+1, s.getLocalTranslation().z);
    }
}
 
Example 15
Source File: TestShadowBug.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void simpleInitApp() {
  flyCam.setMoveSpeed(100f);
  rootNode.attachChild(makeFloor());

  Node characters = new Node("Characters");
  characters.setShadowMode(ShadowMode.Cast);
  rootNode.attachChild(characters);

  Spatial golem = assetManager.loadModel("Models/Oto/Oto.mesh.xml");
  golem.scale(0.5f);
  golem.setLocalTranslation(200.0f, -6f, 200f);
  golem.setShadowMode(ShadowMode.CastAndReceive);
  characters.attachChild(golem);

  DirectionalLight sun = new DirectionalLight();
  sun.setDirection(new Vector3f(-1f, -1f, 1f));
  sun.setColor(ColorRGBA.White.mult(1.3f));
  rootNode.addLight(sun);
  characters.addLight(sun);

  SpotLight spot = new SpotLight();
  spot.setSpotRange(13f);                           // distance
  spot.setSpotInnerAngle(15f * FastMath.DEG_TO_RAD); // inner light cone (central beam)
  spot.setSpotOuterAngle(20f * FastMath.DEG_TO_RAD); // outer light cone (edge of the light)
  spot.setColor(ColorRGBA.White.mult(1.3f));         // light color
  spot.setPosition(new Vector3f(192.0f, -1f, 192f));
  spot.setDirection(new Vector3f(1, -0.5f, 1));
  rootNode.addLight(spot);

  PointLight lamp_light = new PointLight();
  lamp_light.setColor(ColorRGBA.Yellow);
  lamp_light.setRadius(20f);
  lamp_light.setPosition(new Vector3f(210.0f, 0f, 210f));
  rootNode.addLight(lamp_light);

  SpotLightShadowRenderer slsr = new SpotLightShadowRenderer(assetManager, 512);
  slsr.setLight(spot);
  slsr.setEdgeFilteringMode(EdgeFilteringMode.Nearest);
  slsr.setShadowIntensity(0.6f);
  viewPort.addProcessor(slsr);

  PointLightShadowRenderer plsr = new PointLightShadowRenderer(assetManager, 512);
  plsr.setLight(lamp_light);
  plsr.setShadowIntensity(0.6f);
  plsr.setEdgeFilteringMode(EdgeFilteringMode.Nearest);
  viewPort.addProcessor(plsr);

  viewPort.getCamera().setLocation(new Vector3f(192.0f, 10f, 192f));
  float[] angles = new float[]{3.14f/2, 3.14f/2, 0};
  viewPort.getCamera().setRotation(new Quaternion(angles));
}
 
Example 16
Source File: EditorRenderer.java    From OpenRTS with MIT License 4 votes vote down vote up
private void drawAtlasPencil() {
	Pencil s = ToolManager.getActualTool().pencil;
	PointRing pr = new PointRing();
	Point2D center = ToolManager.getActualTool().pencil.getCoord();

	if (s.shape == Pencil.SHAPE.Square || s.shape == Pencil.SHAPE.Diamond) {
		for (double i = -s.size / 2; i < s.size / 2; i += QUAD_PENCIL_SAMPLE_LENGTH) {
			pr.add(center.getAddition(i, -s.size / 2));
		}
		for (double i = -s.size / 2; i < s.size / 2; i += QUAD_PENCIL_SAMPLE_LENGTH) {
			pr.add(center.getAddition(s.size / 2, i));
		}
		for (double i = s.size / 2; i > -s.size / 2; i -= QUAD_PENCIL_SAMPLE_LENGTH) {
			pr.add(center.getAddition(i, s.size / 2));
		}
		for (double i = s.size / 2; i > -s.size / 2; i -= QUAD_PENCIL_SAMPLE_LENGTH) {
			pr.add(center.getAddition(-s.size / 2, i));
		}
		if (s.shape == Pencil.SHAPE.Diamond) {
			PointRing newPR = new PointRing();
			for (Point2D p : pr) {
				newPR.add(p.getRotation(AngleUtil.RIGHT / 2, center));
			}
			pr = newPR;
		}
	} else {
		Point2D revol = center.getAddition(s.size / 2, 0);
		for (int i = 0; i < CIRCLE_PENCIL_SAMPLE_COUNT; i++) {
			pr.add(revol.getRotation(AngleUtil.FLAT * 2 * i / CIRCLE_PENCIL_SAMPLE_COUNT, center));
		}
	}

	int index = 0;
	for (Spatial spatial : AtlasPencilNode.getChildren()) {
		if (index < pr.size() && ModelManager.getBattlefield().getMap().isInBounds(pr.get(index))
				&& ModelManager.getBattlefield().getMap().isInBounds(pr.getNext(index))) {
			Point3D start = pr.get(index).get3D(ModelManager.getBattlefield().getMap().getAltitudeAt(pr.get(index)) + 0.1);
			Point3D end = pr.getNext(index).get3D(ModelManager.getBattlefield().getMap().getAltitudeAt(pr.getNext(index)) + 0.1);
			Line l = new Line(TranslateUtil.toVector3f(start), TranslateUtil.toVector3f(end));
			l.setLineWidth(PENCIL_THICKNESS);
			((Geometry) spatial).setMesh(l);
			spatial.setLocalTranslation(Vector3f.ZERO);
		} else {
			spatial.setLocalTranslation(new Vector3f(-1000, -1000, 0));
		}
		index++;
	}
}
 
Example 17
Source File: KinematicRagdollControl.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Create spatial-dependent data. Invoked when this control is added to a
 * scene.
 *
 * @param model the controlled spatial (not null)
 */
@Override
protected void createSpatialData(Spatial model) {
    targetModel = model;
    Node parent = model.getParent();


    Vector3f initPosition = model.getLocalTranslation().clone();
    Quaternion initRotation = model.getLocalRotation().clone();
    initScale = model.getLocalScale().clone();

    model.removeFromParent();
    model.setLocalTranslation(Vector3f.ZERO);
    model.setLocalRotation(Quaternion.IDENTITY);
    model.setLocalScale(1);
    //HACK ALERT change this
    //I remove the skeletonControl and readd it to the spatial to make sure it's after the ragdollControl in the stack
    //Find a proper way to order the controls.
    SkeletonControl sc = model.getControl(SkeletonControl.class);
    if(sc == null){
        throw new IllegalArgumentException("The root node of the model should have a SkeletonControl. Make sure the control is there and that it's not on a sub node.");
    }
    model.removeControl(sc);
    model.addControl(sc);

    if (boneList.isEmpty()) {
        // add all bones to the list
        skeleton = sc.getSkeleton();
        for (int boneI = 0; boneI < skeleton.getBoneCount(); boneI++) {
            String boneName = skeleton.getBone(boneI).getName();
            boneList.add(boneName);
        }
    }
    // filter out bones without vertices
    filterBoneList(sc);

    if (boneList.isEmpty()) {
        throw new IllegalArgumentException(
                "No suitable bones were found in the model's skeleton.");
    }

    // put into bind pose and compute bone transforms in model space
    // maybe don't reset to ragdoll out of animations?
    scanSpatial(model);


    if (parent != null) {
        parent.attachChild(model);

    }
    model.setLocalTranslation(initPosition);
    model.setLocalRotation(initRotation);
    model.setLocalScale(initScale);

    if (added) {
        addPhysics(space);
    }
    logger.log(Level.FINE, "Created physics ragdoll for skeleton {0}", skeleton);
}
 
Example 18
Source File: SpatialTrack.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * 
 * Modify the spatial which this track modifies.
 * 
 * @param time
 *            the current time of the animation
 */
@Override
public void setTime(float time, float weight, AnimControl control, AnimChannel channel, TempVars vars) {
    Spatial spatial = trackSpatial;
    if (spatial == null) {
        spatial = control.getSpatial();
    }

    Vector3f tempV = vars.vect1;
    Vector3f tempS = vars.vect2;
    Quaternion tempQ = vars.quat1;
    Vector3f tempV2 = vars.vect3;
    Vector3f tempS2 = vars.vect4;
    Quaternion tempQ2 = vars.quat2;
    
    int lastFrame = times.length - 1;
    if (time < 0 || lastFrame == 0) {
        if (rotations != null)
            rotations.get(0, tempQ);
        if (translations != null)
            translations.get(0, tempV);
        if (scales != null) {
            scales.get(0, tempS);
        }
    } else if (time >= times[lastFrame]) {
        if (rotations != null)
            rotations.get(lastFrame, tempQ);
        if (translations != null)
            translations.get(lastFrame, tempV);
        if (scales != null) {
            scales.get(lastFrame, tempS);
        }
    } else {
        int startFrame = 0;
        int endFrame = 1;
        // use lastFrame so we never overflow the array
        for (int i = 0; i < lastFrame && times[i] < time; ++i) {
            startFrame = i;
            endFrame = i + 1;
        }

        float blend = (time - times[startFrame]) / (times[endFrame] - times[startFrame]);

        if (rotations != null)
            rotations.get(startFrame, tempQ);
        if (translations != null)
            translations.get(startFrame, tempV);
        if (scales != null) {
            scales.get(startFrame, tempS);
        }
        if (rotations != null)
            rotations.get(endFrame, tempQ2);
        if (translations != null)
            translations.get(endFrame, tempV2);
        if (scales != null) {
            scales.get(endFrame, tempS2);
        }
        tempQ.nlerp(tempQ2, blend);
        tempV.interpolateLocal(tempV2, blend);
        tempS.interpolateLocal(tempS2, blend);
    }

    if (translations != null) {
        spatial.setLocalTranslation(tempV);
    }
    if (rotations != null) {
        spatial.setLocalRotation(tempQ);
    }
    if (scales != null) {
        spatial.setLocalScale(tempS);
    }
}
 
Example 19
Source File: TestCollisionShapeFactory.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void randomizeTransform(Spatial spat){
    spat.setLocalTranslation((float) Math.random() * 10, (float) Math.random() * 10, (float) Math.random() * 10);
    spat.setLocalTranslation((float) Math.random() * 10, (float) Math.random() * 10, (float) Math.random() * 10);
    spat.setLocalScale((float) Math.random() * 2, (float) Math.random() * 2, (float) Math.random() * 2);
}
 
Example 20
Source File: SpawnToolControl.java    From jmonkeybuilder with Apache License 2.0 4 votes vote down vote up
/**
 * Spawn models.
 *
 * @param brushRotation the brush rotation.
 * @param contactPoint  the contact point.
 */
@JmeThread
protected void spawn(@NotNull Quaternion brushRotation, @NotNull Vector3f contactPoint) {

    var brushSize = getBrushSize();

    var random = ThreadLocalRandom.current();
    var local = getLocalObjects();
    var spawnPosition = local.nextVector();

    var paintedModel = getPaintedModel();
    var direction = GeomUtils.getDirection(brushRotation, local.nextVector())
            .negateLocal()
            .multLocal(10);

    var sourcePoint = contactPoint.subtract(direction, local.nextVector());
    var ray = local.nextRay();
    ray.setOrigin(sourcePoint);

    var minScale = getMinScale();
    var maxScale = getMaxScale();
    var padding = getPadding();

    var resultPosition = local.nextVector();
    var collisions = local.nextCollisionResults();
    var spawnedCollisions = local.nextCollisionResults();
    var resultScale = local.nextVector();
    var needCalculateScale = !minScale.equals(maxScale);

    var maxCount = (int) Math.max(getBrushPower() / 2F, 1F);
    var spawnedModels = getSpawnedModels();

    for(var count = 0; count < maxCount; count++) {
        for (var attempts = 0; attempts < 10; attempts++, attempts++) {

            collisions.clear();
            spawnedCollisions.clear();

            var x = nextOffset(brushSize, random);
            var y = nextOffset(brushSize, random);
            var z = nextOffset(brushSize, random);

            spawnPosition.set(x, y, z)
                    .addLocal(contactPoint)
                    .subtractLocal(sourcePoint)
                    .normalizeLocal();

            ray.setDirection(spawnPosition);

            paintedModel.collideWith(ray, collisions);

            var closest = collisions.getClosestCollision();
            if (closest == null || contactPoint.distance(closest.getContactPoint()) > brushSize / 2) {
                continue;
            }

            resultPosition.set(closest.getContactPoint())
                    .subtractLocal(paintedModel.getWorldTranslation());

            Spatial clone = examples.get(random.nextInt(0, examples.size())).clone();
            clone.setUserData(KEY_IGNORE_RAY_CAST, Boolean.TRUE);
            clone.setLocalTranslation(resultPosition);

            if (needCalculateScale) {
                clone.setLocalScale(nextScale(minScale, maxScale, resultScale, random));
            } else {
                clone.setLocalScale(minScale);
            }

            clone.updateModelBound();

            var worldBound = clone.getWorldBound();

            if (!Vector3f.ZERO.equals(padding)) {
                worldBound = addPadding(worldBound, padding);
            }

            if (paintedModel.collideWith(worldBound, spawnedCollisions) > 2) {
                continue;
            }

            spawnedModels.add(clone);
            paintedModel.attachChild(clone);
            break;
        }
    }
}