Java源码示例:com.jme3.scene.Spatial
示例1
@Override
public int collideWith(Collidable other, CollisionResults results){
int total = 0;
if (other instanceof Ray)
return collideWithRay((Ray)other, results);
// if it didn't collide with this bbox, return
if (other instanceof BoundingVolume)
if (!this.getWorldBound().intersects((BoundingVolume)other))
return total;
for (Spatial child : children){
total += child.collideWith(other, results);
}
return total;
}
示例2
/**
* Apply the specified location and orientation to the specified spatial.
*
* @param worldLocation location vector (in physics-space coordinates, not
* null, unaffected)
* @param worldRotation orientation (in physics-space coordinates, not null,
* unaffected)
* @param spatial where to apply (may be null)
*/
protected void applyPhysicsTransform(Vector3f worldLocation, Quaternion worldRotation, Spatial spatial) {
if (spatial != null) {
Vector3f localLocation = spatial.getLocalTranslation();
Quaternion localRotationQuat = spatial.getLocalRotation();
if (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(worldRotation);
tmp_inverseWorldRotation.set(spatial.getParent().getWorldRotation()).inverseLocal().mult(localRotationQuat, localRotationQuat);
spatial.setLocalTranslation(localLocation);
spatial.setLocalRotation(localRotationQuat);
} else {
spatial.setLocalTranslation(worldLocation);
spatial.setLocalRotation(worldRotation);
}
}
}
示例3
@Override
@FxThread
protected void handleRemovedObject(@NotNull final Spatial model) {
super.handleRemovedObject(model);
if (!(model instanceof SceneNode)) {
return;
}
final SceneNode sceneNode = (SceneNode) model;
final SceneEditor3DPart editor3DState = getEditor3DPart();
sceneNode.getFilters().stream()
.filter(ScenePresentable.class::isInstance)
.forEach(filter -> editor3DState.removePresentable((ScenePresentable) filter));
sceneNode.getAppStates().stream()
.filter(ScenePresentable.class::isInstance)
.forEach(state -> editor3DState.removePresentable((ScenePresentable) state));
}
示例4
protected void dragStopped( CursorButtonEvent event, CursorMotionEvent lastMotion,
Spatial target, Spatial capture ) {
if( !draggingActive ) {
return;
}
if( log.isTraceEnabled() ) {
log.trace("dragStopped(" + event + ", " + target + ", " + capture + ")");
}
draggingActive = false;
DefaultDragSession session = clearSession(event);
if( session == null ) {
// There was no active session... but then why did we get a stopped?
log.warn("dragStopped() called with no active session, event:" + event
+ ", target:" + target
+ ", capture:" + capture);
return;
}
session.close(new DragEvent(session, lastMotion, session.getDropCollision()));
}
示例5
/**
* This method clone the Track and search for the cloned counterpart of the
* original audio node in the given cloned spatial. The spatial is assumed
* to be the Spatial holding the AnimControl controling the animation using
* this Track.
*
* @param spatial the Spatial holding the AnimControl
* @return the cloned Track with proper reference
*/
public Track cloneForSpatial(Spatial spatial) {
AudioTrack audioTrack = new AudioTrack();
audioTrack.length = this.length;
audioTrack.startOffset = this.startOffset;
//searching for the newly cloned AudioNode
audioTrack.audio = findAudio(spatial);
if (audioTrack.audio == null) {
logger.log(Level.WARNING, "{0} was not found in {1} or is not bound to this track", new Object[]{audio.getName(), spatial.getName()});
audioTrack.audio = audio;
}
//setting user data on the new AudioNode and marking it with a reference to the cloned Track.
setUserData(audioTrack);
return audioTrack;
}
示例6
public void actionPerformed(ActionEvent ev) {
ProjectAssetManager pm = context.getLookup().lookup(ProjectAssetManager.class);
if (pm == null) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "AssetManager not found!");
return;
}
Element assetElement = context.getLookup().lookup(Element.class);
com.jme3.scene.Node node = new com.jme3.scene.Node("PreviewRootNode");
Spatial model = null;
model = AssetPackLoader.loadAssetPackModel(pm, new AssetConfiguration(assetElement));
node.attachChild(model);
JmeNode jmeNode = NodeUtility.createNode(node);
SceneApplication app = SceneApplication.getApplication();
SceneRequest request = new SceneRequest(app, jmeNode, pm);
try {
request.setDataObject(DataObject.find(context.getLookup().lookup(Project.class).getProjectDirectory()));
} catch (DataObjectNotFoundException ex) {
Exceptions.printStackTrace(ex);
}
request.setWindowTitle("AssetPack - PreView Model");
app.requestScene(request);
}
示例7
/**
* Helper function used to recursively populate the outputGeometryList
* with geometry children of scene node
*
* @param camera
* @param scene
* @param outputGeometryList
*/
private static void addGeometriesInCamFrustumFromNode(Camera camera, Node scene, RenderQueue.ShadowMode mode, GeometryList outputGeometryList) {
if (scene.getCullHint() == Spatial.CullHint.Always) return;
camera.setPlaneState(0);
if (camera.contains(scene.getWorldBound()) != Camera.FrustumIntersect.Outside) {
for (Spatial child: scene.getChildren()) {
if (child instanceof Node) addGeometriesInCamFrustumFromNode(camera, (Node)child, mode, outputGeometryList);
else if (child instanceof Geometry && child.getCullHint() != Spatial.CullHint.Always) {
camera.setPlaneState(0);
if (checkShadowMode(child.getShadowMode(), mode) &&
!((Geometry)child).isGrouped() &&
camera.contains(child.getWorldBound()) != Camera.FrustumIntersect.Outside) {
outputGeometryList.add((Geometry)child);
}
}
}
}
}
示例8
public static void generate(Spatial scene, boolean splitMirrored) {
if (scene instanceof Node) {
Node node = (Node) scene;
for (Spatial child : node.getChildren()) {
generate(child, splitMirrored);
}
} else {
Geometry geom = (Geometry) scene;
Mesh mesh = geom.getMesh();
// Check to ensure mesh has texcoords and normals before generating
if (mesh.getBuffer(Type.TexCoord) != null && mesh.getBuffer(Type.Normal) != null) {
generate(geom.getMesh(), true, splitMirrored);
}
}
}
示例9
/**
* Get the observer final position within the scene.
* @return the observer position.
* @see #getFinalObserverRotation()
*/
public Vector3f getFinalObserverPosition() {
if( environment.getVRViewManager() == null ) {
if( environment.getObserver() == null ) {
return environment.getCamera().getLocation();
} else{
return ((Spatial)environment.getObserver()).getWorldTranslation();
}
}
Vector3f pos = environment.getVRHardware().getPosition();
if( environment.getObserver() == null ) {
environment.getDummyCamera().getRotation().mult(pos, pos);
return pos.addLocal(environment.getDummyCamera().getLocation());
} else {
((Spatial)environment.getObserver()).getWorldRotation().mult(pos, pos);
return pos.addLocal(((Spatial)environment.getObserver()).getWorldTranslation());
}
}
示例10
/**
* This method clone the Track and search for the cloned counterpart of the
* original emmitter in the given cloned spatial. The spatial is assumed to
* be the Spatial holding the AnimControl controling the animation using
* this Track.
*
* @param spatial the Spatial holding the AnimControl
* @return the cloned Track with proper reference
*/
public Track cloneForSpatial(Spatial spatial) {
EffectTrack effectTrack = new EffectTrack();
effectTrack.particlesPerSeconds = this.particlesPerSeconds;
effectTrack.length = this.length;
effectTrack.startOffset = this.startOffset;
//searching for the newly cloned ParticleEmitter
effectTrack.emitter = findEmitter(spatial);
if (effectTrack.emitter == null) {
logger.log(Level.WARNING, "{0} was not found in {1} or is not bound to this track", new Object[]{emitter.getName(), spatial.getName()});
effectTrack.emitter = emitter;
}
removeUserData(this);
//setting user data on the new emmitter and marking it with a reference to the cloned Track.
setUserData(effectTrack);
effectTrack.emitter.setParticlesPerSec(0);
return effectTrack;
}
示例11
public void resultChanged(LookupEvent ev) {
boolean cleared = false;
for (Iterator<? extends JmeSpatial> it = result.allInstances().iterator(); it.hasNext();) {
JmeSpatial jmeSpatial = it.next();
selectedSpat = jmeSpatial;
Spatial spat = jmeSpatial.getLookup().lookup(Spatial.class);
toolController.updateSelection(spat);
Geometry geom = jmeSpatial.getLookup().lookup(Geometry.class);
if (geom != null) {
if (!cleared) {
list.clear();
cleared = true;
}
Logger.getLogger(VehicleEditorController.class.getName()).log(Level.INFO, "adding:" + jmeSpatial.getName());
list.add(geom);
}
}
}
示例12
/**
* Notify about added a spatial.
*
* @param spatial the spatial.
*/
@FxThread
public void notifyAdded(@NotNull final Spatial spatial) {
spatial.depthFirstTraversal(child -> {
final SceneLayer layer = SceneLayer.getLayer(child);
if (layer == SceneLayer.NO_LAYER) {
return;
}
final TreeItem<TreeNode<?>> newLayerItem = findItemForValue(getTreeView(), layer);
final TreeItem<TreeNode<?>> treeItem = findItemForValue(getTreeView(), child);
if (newLayerItem != null && treeItem == null) {
final TreeNode<?> objectNode = FACTORY_REGISTRY.createFor(child);
newLayerItem.getChildren().add(new TreeItem<>(objectNode));
}
}, Spatial.DFSMode.POST_ORDER);
}
示例13
@Override
@FxThread
public @NotNull Array<TreeNode<?>> getChildren(@NotNull final NodeTree<?> nodeTree) {
final SceneLayer element = getElement();
final Array<TreeNode<?>> result = ArrayFactory.newArray(TreeNode.class);
final ModelChangeConsumer changeConsumer = (ModelChangeConsumer) notNull(nodeTree.getChangeConsumer());
final Spatial currentModel = changeConsumer.getCurrentModel();
currentModel.depthFirstTraversal(spatial -> {
final SceneLayer layer = SceneLayer.getLayer(spatial);
if(layer == element) {
result.add(FACTORY_REGISTRY.createFor(spatial));
}
});
return result;
}
示例14
protected void attachPhysicsSelection(Spatial geom) {
PhysicsCollisionObject control = geom.getControl(RigidBodyControl.class);
if (control == null) {
control = geom.getControl(VehicleControl.class);
}
if (control == null) {
control = geom.getControl(GhostControl.class);
}
if (control == null) {
control = geom.getControl(CharacterControl.class);
}
if (control == null) {
return;
}
Spatial selectionGeometry = DebugShapeFactory.getDebugShape(control.getCollisionShape());
if (selectionGeometry != null) {
selectionGeometry.setMaterial(blueMat);
selectionGeometry.setLocalTransform(geom.getWorldTransform());
toolsNode.attachChild(selectionGeometry);
selectionShape = selectionGeometry;
}
}
示例15
@Override
@FxThread
public void notifyFxAddedChild(@NotNull final Object parent, @NotNull final Object added, final int index,
final boolean needSelect) {
super.notifyFxAddedChild(parent, added, index, needSelect);
final ModelEditor3DPart editor3DState = getEditor3DPart();
if (added instanceof Spatial) {
final Spatial spatial = (Spatial) added;
final boolean isSky = spatial.getQueueBucket() == RenderQueue.Bucket.Sky;
if (isSky) {
editor3DState.addCustomSky(spatial);
editor3DState.updateLightProbe();
}
}
EXECUTOR_MANAGER.addFxTask(() -> getBulletState().notifyAdded(added));
}
示例16
/**
* adds an object to the physics space
* @param obj the PhysicsControl or Spatial with PhysicsControl to add
*/
public void add(Object obj) {
if (obj instanceof PhysicsControl) {
((PhysicsControl) obj).setPhysicsSpace(this);
} else if (obj instanceof Spatial) {
Spatial node = (Spatial) obj;
PhysicsControl control = node.getControl(PhysicsControl.class);
control.setPhysicsSpace(this);
} else if (obj instanceof PhysicsCollisionObject) {
addCollisionObject((PhysicsCollisionObject) obj);
} else if (obj instanceof PhysicsJoint) {
addJoint((PhysicsJoint) obj);
} else {
throw (new UnsupportedOperationException("Cannot add this kind of object to the physics space."));
}
}
示例17
public CursorMotionEvent( ViewPort view, Spatial target, float x, float y,
int scroll, int scrollDelta, CollisionResult collision ) {
super(view, target, x, y, collision);
this.scroll = scroll;
this.scrollDelta = scrollDelta;
}
示例18
@Override
public void simpleInitApp() {
File file = new File("wildhouse.zip");
if (!file.exists()) {
useHttp = true;
}
this.flyCam.setMoveSpeed(10);
// load sky
rootNode.attachChild(SkyFactory.createSky(assetManager,
"Textures/Sky/Bright/BrightSky.dds",
SkyFactory.EnvMapType.CubeMap));
// create the geometry and attach it
// load the level from zip or http zip
if (useHttp) {
assetManager.registerLocator("https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/jmonkeyengine/wildhouse.zip", HttpZipLocator.class);
} else {
assetManager.registerLocator("wildhouse.zip", ZipLocator.class);
}
Spatial scene = assetManager.loadModel("main.scene");
AmbientLight al = new AmbientLight();
scene.addLight(al);
DirectionalLight sun = new DirectionalLight();
sun.setDirection(new Vector3f(0.69077975f, -0.6277887f, -0.35875428f).normalizeLocal());
sun.setColor(ColorRGBA.White.clone().multLocal(2));
scene.addLight(sun);
rootNode.attachChild(scene);
}
示例19
protected void navigate( TraversalDirection dir ) {
Spatial current = getCurrentFocus();
if( current == null ) {
return;
}
requestChangeFocus(current, dir);
}
示例20
/**
* Create a texture atlas for the given root node, containing DiffuseMap, NormalMap and SpecularMap.
* @param root The rootNode to create the atlas for.
* @param atlasSize The size of the atlas (width and height).
* @return Null if the atlas cannot be created because not all textures fit.
*/
public static TextureAtlas createAtlas(Spatial root, int atlasSize) {
List<Geometry> geometries = new ArrayList<Geometry>();
GeometryBatchFactory.gatherGeoms(root, geometries);
TextureAtlas atlas = new TextureAtlas(atlasSize, atlasSize);
for (Geometry geometry : geometries) {
if (!atlas.addGeometry(geometry)) {
logger.log(Level.WARNING, "Texture atlas size too small, cannot add all textures");
return null;
}
}
return atlas;
}
示例21
@Override
public void mouseEntered( MouseMotionEvent event, Spatial target, Spatial capture ) {
if( !isEnabled() )
return;
if( capture == Button.this || (target == Button.this && capture == null) ) {
showHighlight(true);
commandMap.runCommands(ButtonAction.HighlightOn);
runEffect(EFFECT_ACTIVATE);
}
}
示例22
@Override
public Control cloneForSpatial(Spatial spatial) {
KillParticleControl c = new KillParticleControl();
//this control should be removed as it shouldn't have been persisted in the first place
//In the quest to find the less hackish solution to achieve this,
//making it remove itself from the spatial in the first update loop when loaded was the less bad.
c.remove = true;
c.setSpatial(spatial);
return c;
}
示例23
/**
* Validate a model for use with DynamicAnimControl.
*
* @param model the model to validate (not null, unaffected)
*/
static void validate(Spatial model) {
List<Geometry> geometries = listGeometries(model, null);
if (geometries.isEmpty()) {
throw new IllegalArgumentException("No meshes in the model.");
}
for (Geometry geometry : geometries) {
if (geometry.isIgnoreTransform()) {
throw new IllegalArgumentException(
"A model geometry ignores transforms.");
}
}
}
示例24
/**
* This method creates a hull shape for the given Spatial.<br>
* If you want to have mesh-accurate dynamic shapes (CPU intense!!!) use GImpact shapes, its probably best to do so with a low-poly version of your model.
* @return A HullCollisionShape or a CompoundCollisionShape with HullCollisionShapes as children if the supplied spatial is a Node.
*/
public static CollisionShape createDynamicMeshShape(Spatial spatial) {
if (spatial instanceof Geometry) {
return createSingleDynamicMeshShape((Geometry) spatial, spatial);
} else if (spatial instanceof Node) {
return createCompoundShape((Node) spatial, (Node) spatial, new CompoundCollisionShape(), true, true);
} else {
throw new IllegalArgumentException("Supplied spatial must either be Node or Geometry!");
}
}
示例25
@Override
public void read(JmeImporter im) throws IOException {
super.read(im);
InputCapsule ic = im.getCapsule(this);
enabled = ic.readBoolean("enabled", true);
kinematicSpatial = ic.readBoolean("kinematicSpatial", true);
spatial = (Spatial) ic.readSavable("spatial", null);
motionState.setApplyPhysicsLocal(ic.readBoolean("applyLocalPhysics", false));
setUserObject(spatial);
}
示例26
@Override
public Quaternion getFinalObserverRotation(int index) {
if (environment != null) {
VRViewManager vrvm = environment.getVRViewManager();
if (vrvm != null) {
if (isInputDeviceTracking(index) == false) {
return null;
}
Object obs = environment.getObserver();
if (obs instanceof Camera) {
tempq.set(((Camera) obs).getRotation());
} else {
tempq.set(((Spatial) obs).getWorldRotation());
}
return tempq.multLocal(getOrientation(index));
} else {
throw new IllegalStateException("VR environment has no valid view manager.");
}
} else {
throw new IllegalStateException("VR input is not attached to a VR environment.");
}
}
示例27
@Override
public void simpleInitApp() {
final Node buggy = (Node) assetManager.loadModel("Models/Buggy/Buggy.j3o");
TextureKey key = new TextureKey("Textures/Sky/Bright/BrightSky.dds", true);
key.setGenerateMips(true);
key.setAsCube(true);
final Texture tex = assetManager.loadTexture(key);
for (Spatial geom : buggy.getChildren()) {
if (geom instanceof Geometry) {
Material m = ((Geometry) geom).getMaterial();
m.setTexture("EnvMap", tex);
m.setVector3("FresnelParams", new Vector3f(0.05f, 0.18f, 0.11f));
}
}
flyCam.setEnabled(false);
ChaseCamera chaseCam = new ChaseCamera(cam, inputManager);
chaseCam.setLookAtOffset(new Vector3f(0,0.5f,-1.0f));
buggy.addControl(chaseCam);
rootNode.attachChild(buggy);
rootNode.attachChild(SkyFactory.createSky(assetManager, tex, false));
FilterPostProcessor fpp = new FilterPostProcessor(assetManager);
BloomFilter bf = new BloomFilter(BloomFilter.GlowMode.Objects);
bf.setBloomIntensity(2.3f);
bf.setExposurePower(0.6f);
fpp.addFilter(bf);
viewPort.addProcessor(fpp);
}
示例28
/**
* @see AlignmentBehavior#AlignmentBehavior(com.jme3.ai.agents.Agent,
* java.util.List)
* @see AlignmentBehavior#AlignmentBehavior(com.jme3.ai.agents.Agent,
* java.util.List, float, float)
*/
public AlignmentBehavior(Agent agent, List<GameEntity> neighbours, float maxDistance, float maxAngle, Spatial spatial) {
super(agent, spatial);
this.validateMaxDistance(maxDistance);
this.neighbours = neighbours;
this.maxDistance = maxDistance;
this.maxAngle = maxAngle;
}
示例29
/**
* Neighbours of agent will be his team members.
*
* @param maxDistance In order to consider a neighbour inside the
* neighbourhood
* @param maxAngle In order to consider a neighbour inside the neighbourhood
* Neighbours of agent will be his team members.
* @param spatial active spatial during excecution of behavior
* @param agent
*/
public AlignmentBehavior(Agent agent, float maxDistance, float maxAngle, Spatial spatial) {
super(agent, spatial);
try {
this.validateMaxDistance(maxDistance);
this.maxDistance = maxDistance;
this.maxAngle = maxAngle;
neighbours = convertToGameEntities(agent.getTeam().getMembers());
} catch (NullPointerException npe) {
throw new AgentExceptions.TeamNotFoundException(agent);
}
}
示例30
public static void setLayer( Spatial s, int layer ) {
if( layer == 0 ) {
s.setUserData(LAYER, null);
} else {
s.setUserData(LAYER, layer);
}
}