com.jme3.export.binary.BinaryExporter Java Examples

The following examples show how to use com.jme3.export.binary.BinaryExporter. 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: SaveGame.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
     * Saves a savable in a system-dependent way. Note that only small amounts of data can be saved.
     * @param gamePath A unique path for this game, e.g. com/mycompany/mygame
     * @param dataName A unique name for this savegame, e.g. "save_001"
     * @param data The Savable to save
     */
    public static void saveGame(String gamePath, String dataName, Savable data) {
        Preferences prefs = Preferences.userRoot().node(gamePath);
        BinaryExporter ex = BinaryExporter.getInstance();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            GZIPOutputStream zos = new GZIPOutputStream(out);
            ex.save(data, zos);
            zos.close();
        } catch (IOException ex1) {
            Logger.getLogger(SaveGame.class.getName()).log(Level.SEVERE, "Error saving data: {0}", ex1);
            ex1.printStackTrace();
        }
        UUEncoder enc = new UUEncoder();
        String dataString = enc.encodeBuffer(out.toByteArray());
//        System.out.println(dataString);
        if (dataString.length() > Preferences.MAX_VALUE_LENGTH) {
            throw new IllegalStateException("SaveGame dataset too large");
        }
        prefs.put(dataName, dataString);
    }
 
Example #2
Source File: SceneMatParamOverrideTest.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testOverrides_SaveAndLoad_KeepsMPOs() {
    MatParamOverride override = mpoInt("val", 5);
    Node scene = createDummyScene();
    scene.getChild("A").addMatParamOverride(override);

    AssetManager assetManager = TestUtil.createAssetManager();
    Node loadedScene = BinaryExporter.saveAndLoad(assetManager, scene);

    Node root = new Node("Root Node");
    root.attachChild(loadedScene);
    validateScene(root);
    validateScene(scene);

    assertNotSame(override, loadedScene.getChild("A").getLocalMatParamOverrides().get(0));
    assertEquals(override, loadedScene.getChild("A").getLocalMatParamOverrides().get(0));
}
 
Example #3
Source File: TestParticleExportingCloning.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void simpleInitApp() {
    ParticleEmitter emit = new ParticleEmitter("Emitter", Type.Triangle, 200);
    emit.setShape(new EmitterSphereShape(Vector3f.ZERO, 1f));
    emit.setGravity(0, 0, 0);
    emit.setLowLife(5);
    emit.setHighLife(10);
    emit.getParticleInfluencer().setInitialVelocity(new Vector3f(0, 0, 0));
    emit.setImagesX(15);
    Material mat = new Material(assetManager, "Common/MatDefs/Misc/Particle.j3md");
    mat.setTexture("Texture", assetManager.loadTexture("Effects/Smoke/Smoke.png"));
    emit.setMaterial(mat);

    ParticleEmitter emit2 = emit.clone();
    emit2.move(3, 0, 0);
    
    rootNode.attachChild(emit);
    rootNode.attachChild(emit2);
    
    ParticleEmitter emit3 = BinaryExporter.saveAndLoad(assetManager, emit);
    emit3.move(-3, 0, 0);
    rootNode.attachChild(emit3);
}
 
Example #4
Source File: TestOgreConvert.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void simpleInitApp() {
    Spatial ogreModel = assetManager.loadModel("Models/Oto/Oto.mesh.xml");

    DirectionalLight dl = new DirectionalLight();
    dl.setColor(ColorRGBA.White);
    dl.setDirection(new Vector3f(0,-1,-1).normalizeLocal());
    rootNode.addLight(dl);

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BinaryExporter exp = new BinaryExporter();
        exp.save(ogreModel, baos);

        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        BinaryImporter imp = new BinaryImporter();
        imp.setAssetManager(assetManager);
        Node ogreModelReloaded = (Node) imp.load(bais, null, null);

        AnimComposer composer = ogreModelReloaded.getControl(AnimComposer.class);
        composer.setCurrentAction("Walk");

        rootNode.attachChild(ogreModelReloaded);
    } catch (IOException ex){
        ex.printStackTrace();
    }
}
 
Example #5
Source File: ClipboardSpatial.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public ClipboardSpatial(Spatial spat){
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        BinaryExporter.getInstance().save(spat, out);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
    data= out.toByteArray();
}
 
Example #6
Source File: CompactVector3ArrayTest.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void testRead() throws IOException {
    File file = File.createTempFile("compactArray", "test"); 
    BinaryImporter importer = new BinaryImporter();
    BinaryExporter exporter = new BinaryExporter();
    compact.add(objArray1);
    compact.add(objArray2);
    exporter.save(compact, file);
    compact = (CompactVector3Array) importer.load(file);
    _testSize();
    _testCompactIndex();
    _testGet();
    file.delete();
}
 
Example #7
Source File: TestOgreConvert.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void simpleInitApp() {
    Spatial ogreModel = assetManager.loadModel("Models/Oto/Oto.mesh.xml");

    DirectionalLight dl = new DirectionalLight();
    dl.setColor(ColorRGBA.White);
    dl.setDirection(new Vector3f(0,-1,-1).normalizeLocal());
    rootNode.addLight(dl);

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BinaryExporter exp = new BinaryExporter();
        exp.save(ogreModel, baos);

        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        BinaryImporter imp = new BinaryImporter();
        imp.setAssetManager(assetManager);
        Node ogreModelReloaded = (Node) imp.load(bais, null, null);
        
        AnimControl control = ogreModelReloaded.getControl(AnimControl.class);
        AnimChannel chan = control.createChannel();
        chan.setAnim("Walk");

        rootNode.attachChild(ogreModelReloaded);
    } catch (IOException ex){
        ex.printStackTrace();
    }
}
 
Example #8
Source File: TestParticleExportingCloning.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void simpleInitApp() {
    ParticleEmitter emit = new ParticleEmitter("Emitter", Type.Triangle, 200);
    emit.setShape(new EmitterSphereShape(Vector3f.ZERO, 1f));
    emit.setGravity(0, 0, 0);
    emit.setLowLife(5);
    emit.setHighLife(10);
    emit.setInitialVelocity(new Vector3f(0, 0, 0));
    emit.setImagesX(15);
    Material mat = new Material(assetManager, "Common/MatDefs/Misc/Particle.j3md");
    mat.setTexture("Texture", assetManager.loadTexture("Effects/Smoke/Smoke.png"));
    emit.setMaterial(mat);

    ParticleEmitter emit2 = emit.clone();
    emit2.move(3, 0, 0);
    
    rootNode.attachChild(emit);
    rootNode.attachChild(emit2);
    
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        BinaryExporter.getInstance().save(emit, out);
        
        BinaryImporter imp = new BinaryImporter();
        imp.setAssetManager(assetManager);
        ParticleEmitter emit3 = (ParticleEmitter) imp.load(out.toByteArray());
        
        emit3.move(-3, 0, 0);
        rootNode.attachChild(emit3);
    } catch (IOException ex) {
        ex.printStackTrace();
    }

        //        Camera cam2 = cam.clone();
//        cam.setViewPortTop(0.5f);
//        cam2.setViewPortBottom(0.5f);
//        ViewPort vp = renderManager.createMainView("SecondView", cam2);
//        viewPort.setClearEnabled(false);
//        vp.attachScene(rootNode);
}
 
Example #9
Source File: TerrainTestReadWrite.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void onAction(String name, boolean pressed, float tpf) {
    if (name.equals("save") && !pressed) {

        FileOutputStream fos = null;
        try {
            long start = System.currentTimeMillis();
            fos = new FileOutputStream(new File("terrainsave.jme"));

            // we just use the exporter and pass in the terrain
            BinaryExporter.getInstance().save((Savable)terrain, new BufferedOutputStream(fos));

            fos.flush();
            float duration = (System.currentTimeMillis() - start) / 1000.0f;
            System.out.println("Save took " + duration + " seconds");
        } catch (IOException ex) {
            Logger.getLogger(TerrainTestReadWrite.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                Logger.getLogger(TerrainTestReadWrite.class.getName()).log(Level.SEVERE, null, e);
            }
        }
    }
}
 
Example #10
Source File: TestModelExportingCloning.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void simpleInitApp() {
    cam.setLocation(new Vector3f(10f, 3f, 40f));
    cam.lookAtDirection(Vector3f.UNIT_Z.negate(), Vector3f.UNIT_Y);

    DirectionalLight dl = new DirectionalLight();
    dl.setDirection(new Vector3f(-0.1f, -0.7f, -1).normalizeLocal());
    dl.setColor(new ColorRGBA(1f, 1f, 1f, 1.0f));
    rootNode.addLight(dl);

    AnimComposer composer;

    Spatial originalModel = assetManager.loadModel("Models/Oto/Oto.mesh.xml");
    composer = originalModel.getControl(AnimComposer.class);
    composer.setCurrentAction("Walk");
    composer.setGlobalSpeed(1.5f);
    rootNode.attachChild(originalModel);
    
    Spatial clonedModel = originalModel.clone();
    clonedModel.move(10, 0, 0);
    composer = clonedModel.getControl(AnimComposer.class);
    composer.setCurrentAction("push");
    System.out.println("clonedModel: globalSpeed=" + composer.getGlobalSpeed());
    rootNode.attachChild(clonedModel);
    
    Spatial exportedModel = BinaryExporter.saveAndLoad(assetManager, originalModel);
    exportedModel.move(20, 0, 0);
    composer = exportedModel.getControl(AnimComposer.class);
    composer.setCurrentAction("pull");
    System.out.println("exportedModel: globalSpeed=" + composer.getGlobalSpeed());
    rootNode.attachChild(exportedModel);
}
 
Example #11
Source File: TerrainTestReadWrite.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void onAction(String name, boolean pressed, float tpf) {
    if (name.equals("save") && !pressed) {

        FileOutputStream fos = null;
        try {
            long start = System.currentTimeMillis();
            fos = new FileOutputStream(new File("terrainsave.jme"));

            // we just use the exporter and pass in the terrain
            BinaryExporter.getInstance().save((Savable)terrain, new BufferedOutputStream(fos));

            fos.flush();
            float duration = (System.currentTimeMillis() - start) / 1000.0f;
            System.out.println("Save took " + duration + " seconds");
        } catch (IOException ex) {
            Logger.getLogger(TerrainTestReadWrite.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                Logger.getLogger(TerrainTestReadWrite.class.getName()).log(Level.SEVERE, null, e);
            }
        }
    }
}
 
Example #12
Source File: EmptySceneCreator.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
@Override
@BackgroundThread
protected void writeData(@NotNull final Path resultFile) throws IOException {
    super.writeData(resultFile);

    final BinaryExporter exporter = BinaryExporter.getInstance();
    final SceneNode newNode = createScene();

    try (final OutputStream out = Files.newOutputStream(resultFile, WRITE, TRUNCATE_EXISTING, CREATE)) {
        exporter.save(newNode, out);
    }
}
 
Example #13
Source File: EmptyModelCreator.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
@Override
@BackgroundThread
protected void writeData(@NotNull final Path resultFile) throws IOException {
    super.writeData(resultFile);

    final BinaryExporter exporter = BinaryExporter.getInstance();
    final Node newNode = new Node("Model root");

    try (final OutputStream out = Files.newOutputStream(resultFile, WRITE, TRUNCATE_EXISTING, CREATE)) {
        exporter.save(newNode, out);
    }
}
 
Example #14
Source File: TestPhysicsReadWrite.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void simpleInitApp() {
    bulletAppState = new BulletAppState();
    stateManager.attach(bulletAppState);
    bulletAppState.setDebugEnabled(true);
    physicsRootNode=new Node("PhysicsRootNode");
    rootNode.attachChild(physicsRootNode);

    // Add a physics sphere to the world
    Node physicsSphere = PhysicsTestHelper.createPhysicsTestNode(assetManager, new SphereCollisionShape(1), 1);
    physicsSphere.getControl(RigidBodyControl.class).setPhysicsLocation(new Vector3f(3, 6, 0));
    rootNode.attachChild(physicsSphere);
    getPhysicsSpace().add(physicsSphere);

    // Add a physics sphere to the world using the collision shape from sphere one
    Node physicsSphere2 = PhysicsTestHelper.createPhysicsTestNode(assetManager, physicsSphere.getControl(RigidBodyControl.class).getCollisionShape(), 1);
    physicsSphere2.getControl(RigidBodyControl.class).setPhysicsLocation(new Vector3f(4, 8, 0));
    rootNode.attachChild(physicsSphere2);
    getPhysicsSpace().add(physicsSphere2);

    // Add a physics box to the world
    Node physicsBox = PhysicsTestHelper.createPhysicsTestNode(assetManager, new BoxCollisionShape(new Vector3f(1, 1, 1)), 1);
    physicsBox.getControl(RigidBodyControl.class).setFriction(0.1f);
    physicsBox.getControl(RigidBodyControl.class).setPhysicsLocation(new Vector3f(.6f, 4, .5f));
    rootNode.attachChild(physicsBox);
    getPhysicsSpace().add(physicsBox);

    // Add a physics cylinder to the world
    Node physicsCylinder = PhysicsTestHelper.createPhysicsTestNode(assetManager, new CylinderCollisionShape(new Vector3f(1f, 1f, 1.5f)), 1);
    physicsCylinder.getControl(RigidBodyControl.class).setPhysicsLocation(new Vector3f(2, 2, 0));
    rootNode.attachChild(physicsCylinder);
    getPhysicsSpace().add(physicsCylinder);

    // an obstacle mesh, does not move (mass=0)
    Node node2 = PhysicsTestHelper.createPhysicsTestNode(assetManager, new MeshCollisionShape(new Sphere(16, 16, 1.2f)), 0);
    node2.getControl(RigidBodyControl.class).setPhysicsLocation(new Vector3f(2.5f, -4, 0f));
    rootNode.attachChild(node2);
    getPhysicsSpace().add(node2);

    // the floor mesh, does not move (mass=0)
    Node node3 = PhysicsTestHelper.createPhysicsTestNode(assetManager, new PlaneCollisionShape(new Plane(new Vector3f(0, 1, 0), 0)), 0);
    node3.getControl(RigidBodyControl.class).setPhysicsLocation(new Vector3f(0f, -6, 0f));
    rootNode.attachChild(node3);
    getPhysicsSpace().add(node3);

    // Join the physics objects with a Point2Point joint
    HingeJoint joint=new HingeJoint(physicsSphere.getControl(RigidBodyControl.class), physicsBox.getControl(RigidBodyControl.class), new Vector3f(-2,0,0), new Vector3f(2,0,0), Vector3f.UNIT_Z,Vector3f.UNIT_Z);
    getPhysicsSpace().add(joint);

    //save and load the physicsRootNode
    try {
        //remove all physics objects from physics space
        getPhysicsSpace().removeAll(physicsRootNode);
        physicsRootNode.removeFromParent();
        //export to byte array
        ByteArrayOutputStream bout=new ByteArrayOutputStream();
        BinaryExporter.getInstance().save(physicsRootNode, bout);
        //import from byte array
        ByteArrayInputStream bin=new ByteArrayInputStream(bout.toByteArray());
        BinaryImporter imp=BinaryImporter.getInstance();
        imp.setAssetManager(assetManager);
        Node newPhysicsRootNode=(Node)imp.load(bin);
        //add all physics objects to physics space
        getPhysicsSpace().addAll(newPhysicsRootNode);
        rootNode.attachChild(newPhysicsRootNode);
    } catch (IOException ex) {
        Logger.getLogger(TestPhysicsReadWrite.class.getName()).log(Level.SEVERE, null, ex);
    }

}
 
Example #15
Source File: ModelImportDialog.java    From jmonkeybuilder with Apache License 2.0 4 votes vote down vote up
/**
 * Import the external model in a background thread.
 */
@BackgroundThread
private void importModel() {

    final Path modelFile = notNull(getFileToCreate());

    final Path parent = modelFile.getParent();
    final VarTable vars = getVars();

    final Path importedFile = vars.get(PROP_FILE);

    final AssetManager assetManager = EditorUtil.getAssetManager();
    final Spatial model;

    FolderAssetLocator.setIgnore(true);
    try {
        model = assetManager.loadModel(importedFile.toString());
    } finally {
        FolderAssetLocator.setIgnore(false);
    }

    if (EDITOR_CONFIG.getBoolean(PREF_TANGENT_GENERATION, PREF_DEFAULT_TANGENT_GENERATION)) {
        TangentGenerator.useMikktspaceGenerator(model);
    }

    final Path texturesFolder = vars.get(PROP_TEXTURES_FOLDER, parent);
    final boolean overwriteTextures = vars.getBoolean(PROP_OVERWRITE_TEXTURES);

    final boolean needExportMaterials = vars.getBoolean(PROP_NEED_MATERIALS_EXPORT);
    final Path materialsFolder = vars.get(PROP_MATERIALS_FOLDER, parent);
    final boolean overwriteMaterials = vars.getBoolean(PROP_OVERWRITE_MATERIALS, false);

    final Array<Texture> textures = ArrayFactory.newArray(Texture.class);
    final Array<Geometry> geometries = ArrayFactory.newArray(Geometry.class);

    NodeUtils.visitGeometry(model, geometry -> {

        final Material material = geometry.getMaterial();
        if (needExportMaterials) geometries.add(geometry);

        material.getParams().stream()
                .filter(MatParamTexture.class::isInstance)
                .map(MatParam::getValue)
                .filter(Texture.class::isInstance)
                .map(Texture.class::cast)
                .filter(texture -> texture.getKey() != null)
                .forEach(textures::add);
    });

    copyTextures(texturesFolder, overwriteTextures, textures);

    if (needExportMaterials) {
        exportMaterials(materialsFolder, overwriteMaterials, geometries);
    }

    final Path assetFile = notNull(getAssetFile(modelFile));
    final String assetPath = toAssetPath(assetFile);

    model.setName(assetPath);

    final BinaryExporter exporter = BinaryExporter.getInstance();

    try (final OutputStream out = Files.newOutputStream(modelFile, WRITE, TRUNCATE_EXISTING, CREATE)) {
        exporter.save(model, out);
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }

    notifyFileCreated(modelFile, true);
}
 
Example #16
Source File: TestAnimMorphSerialization.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void simpleInitApp() {
    setTimer(new EraseTimer());
    //cam.setFrustumPerspective(90f, (float) cam.getWidth() / cam.getHeight(), 0.01f, 10f);
    viewPort.setBackgroundColor(ColorRGBA.DarkGray);
    //rootNode.addLight(new DirectionalLight(new Vector3f(-1, -1, -1).normalizeLocal()));
    //rootNode.addLight(new AmbientLight(ColorRGBA.DarkGray));
    Node probeNode = (Node) assetManager.loadModel("Scenes/defaultProbe.j3o");
    rootNode.attachChild(probeNode);
    Spatial model = assetManager.loadModel("Models/gltf/zophrac/scene.gltf");

    File storageFolder = JmeSystem.getStorageFolder();
    file = new File(storageFolder.getPath() + File.separator + "zophrac.j3o");
    BinaryExporter be = new BinaryExporter();
    try {
        be.save(model, file);
    } catch (IOException e) {
        e.printStackTrace();
    }

    assetManager.registerLocator(storageFolder.getPath(), FileLocator.class);
    Spatial model2 = assetManager.loadModel("zophrac.j3o");
    model2.setLocalScale(0.1f);
    probeNode.attachChild(model2);

    debugAppState = new ArmatureDebugAppState();
    stateManager.attach(debugAppState);

    setupModel(model2);

    flyCam.setEnabled(false);

    Node target = new Node("CamTarget");
    //target.setLocalTransform(model.getLocalTransform());
    target.move(0, 0, 0);
    ChaseCameraAppState chaseCam = new ChaseCameraAppState();
    chaseCam.setTarget(target);
    getStateManager().attach(chaseCam);
    chaseCam.setInvertHorizontalAxis(true);
    chaseCam.setInvertVerticalAxis(true);
    chaseCam.setZoomSpeed(0.5f);
    chaseCam.setMinVerticalRotation(-FastMath.HALF_PI);
    chaseCam.setRotationSpeed(3);
    chaseCam.setDefaultDistance(3);
    chaseCam.setMinDistance(0.01f);
    chaseCam.setZoomSpeed(0.01f);
    chaseCam.setDefaultVerticalRotation(0.3f);

    initInputs();
}
 
Example #17
Source File: TestAnimSerialization.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void simpleInitApp() {
    setTimer(new EraseTimer());
    //cam.setFrustumPerspective(90f, (float) cam.getWidth() / cam.getHeight(), 0.01f, 10f);
    viewPort.setBackgroundColor(ColorRGBA.DarkGray);
    rootNode.addLight(new DirectionalLight(new Vector3f(-1, -1, -1).normalizeLocal()));
    rootNode.addLight(new AmbientLight(ColorRGBA.DarkGray));

    Spatial model = assetManager.loadModel("Models/Jaime/Jaime.j3o");

    AnimMigrationUtils.migrate(model);

    File storageFolder = JmeSystem.getStorageFolder();
    file = new File(storageFolder.getPath() + File.separator + "newJaime.j3o");
    BinaryExporter be = new BinaryExporter();
    try {
        be.save(model, file);
    } catch (IOException e) {
        e.printStackTrace();
    }

    assetManager.registerLocator(storageFolder.getPath(), FileLocator.class);
    model = assetManager.loadModel("newJaime.j3o");

    rootNode.attachChild(model);

    debugAppState = new ArmatureDebugAppState();
    stateManager.attach(debugAppState);

    setupModel(model);

    flyCam.setEnabled(false);

    Node target = new Node("CamTarget");
    //target.setLocalTransform(model.getLocalTransform());
    target.move(0, 1, 0);
    ChaseCameraAppState chaseCam = new ChaseCameraAppState();
    chaseCam.setTarget(target);
    getStateManager().attach(chaseCam);
    chaseCam.setInvertHorizontalAxis(true);
    chaseCam.setInvertVerticalAxis(true);
    chaseCam.setZoomSpeed(0.5f);
    chaseCam.setMinVerticalRotation(-FastMath.HALF_PI);
    chaseCam.setRotationSpeed(3);
    chaseCam.setDefaultDistance(3);
    chaseCam.setMinDistance(0.01f);
    chaseCam.setZoomSpeed(0.01f);
    chaseCam.setDefaultVerticalRotation(0.3f);

    initInputs();
}
 
Example #18
Source File: TestPhysicsReadWrite.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public void simpleInitApp() {
    bulletAppState = new BulletAppState();
    stateManager.attach(bulletAppState);
    bulletAppState.getPhysicsSpace().enableDebug(assetManager);
    physicsRootNode=new Node("PhysicsRootNode");
    rootNode.attachChild(physicsRootNode);

    // Add a physics sphere to the world
    Node physicsSphere = PhysicsTestHelper.createPhysicsTestNode(assetManager, new SphereCollisionShape(1), 1);
    physicsSphere.getControl(RigidBodyControl.class).setPhysicsLocation(new Vector3f(3, 6, 0));
    rootNode.attachChild(physicsSphere);
    getPhysicsSpace().add(physicsSphere);

    // Add a physics sphere to the world using the collision shape from sphere one
    Node physicsSphere2 = PhysicsTestHelper.createPhysicsTestNode(assetManager, physicsSphere.getControl(RigidBodyControl.class).getCollisionShape(), 1);
    physicsSphere2.getControl(RigidBodyControl.class).setPhysicsLocation(new Vector3f(4, 8, 0));
    rootNode.attachChild(physicsSphere2);
    getPhysicsSpace().add(physicsSphere2);

    // Add a physics box to the world
    Node physicsBox = PhysicsTestHelper.createPhysicsTestNode(assetManager, new BoxCollisionShape(new Vector3f(1, 1, 1)), 1);
    physicsBox.getControl(RigidBodyControl.class).setFriction(0.1f);
    physicsBox.getControl(RigidBodyControl.class).setPhysicsLocation(new Vector3f(.6f, 4, .5f));
    rootNode.attachChild(physicsBox);
    getPhysicsSpace().add(physicsBox);

    // Add a physics cylinder to the world
    Node physicsCylinder = PhysicsTestHelper.createPhysicsTestNode(assetManager, new CylinderCollisionShape(new Vector3f(1f, 1f, 1.5f)), 1);
    physicsCylinder.getControl(RigidBodyControl.class).setPhysicsLocation(new Vector3f(2, 2, 0));
    rootNode.attachChild(physicsCylinder);
    getPhysicsSpace().add(physicsCylinder);

    // an obstacle mesh, does not move (mass=0)
    Node node2 = PhysicsTestHelper.createPhysicsTestNode(assetManager, new MeshCollisionShape(new Sphere(16, 16, 1.2f)), 0);
    node2.getControl(RigidBodyControl.class).setPhysicsLocation(new Vector3f(2.5f, -4, 0f));
    rootNode.attachChild(node2);
    getPhysicsSpace().add(node2);

    // the floor mesh, does not move (mass=0)
    Node node3 = PhysicsTestHelper.createPhysicsTestNode(assetManager, new PlaneCollisionShape(new Plane(new Vector3f(0, 1, 0), 0)), 0);
    node3.getControl(RigidBodyControl.class).setPhysicsLocation(new Vector3f(0f, -6, 0f));
    rootNode.attachChild(node3);
    getPhysicsSpace().add(node3);

    // Join the physics objects with a Point2Point joint
    HingeJoint joint=new HingeJoint(physicsSphere.getControl(RigidBodyControl.class), physicsBox.getControl(RigidBodyControl.class), new Vector3f(-2,0,0), new Vector3f(2,0,0), Vector3f.UNIT_Z,Vector3f.UNIT_Z);
    getPhysicsSpace().add(joint);

    //save and load the physicsRootNode
    try {
        //remove all physics objects from physics space
        getPhysicsSpace().removeAll(physicsRootNode);
        physicsRootNode.removeFromParent();
        //export to byte array
        ByteArrayOutputStream bout=new ByteArrayOutputStream();
        BinaryExporter.getInstance().save(physicsRootNode, bout);
        //import from byte array
        ByteArrayInputStream bin=new ByteArrayInputStream(bout.toByteArray());
        BinaryImporter imp=BinaryImporter.getInstance();
        imp.setAssetManager(assetManager);
        Node newPhysicsRootNode=(Node)imp.load(bin);
        //add all physics objects to physics space
        getPhysicsSpace().addAll(newPhysicsRootNode);
        rootNode.attachChild(newPhysicsRootNode);
    } catch (IOException ex) {
        Logger.getLogger(TestPhysicsReadWrite.class.getName()).log(Level.SEVERE, null, ex);
    }

}
 
Example #19
Source File: AbstractModelFileConverter.java    From jmonkeybuilder with Apache License 2.0 4 votes vote down vote up
/**
 * Convert a file using settings from the dialog.
 */
@BackgroundThread
private void convertImpl(@NotNull final Path source, @NotNull final VarTable vars) throws IOException {

    final String filename = vars.getString(PROP_RESULT_NAME);
    final Path destinationFolder = notNull(getRealFile(vars.get(PROP_DESTINATION, Path.class)));
    final Path destination = destinationFolder.resolve(filename + "." + FileExtensions.JME_OBJECT);
    final boolean isOverwrite = Files.exists(destination);

    final Path assetFile = notNull(getAssetFile(source), "Not found asset file for " + source);
    final ModelKey modelKey = new ModelKey(toAssetPath(assetFile));

    final AssetManager assetManager = EditorUtil.getAssetManager();
    final Spatial model = assetManager.loadAsset(modelKey);

    if (EDITOR_CONFIG.getBoolean(PREF_TANGENT_GENERATION, PREF_DEFAULT_TANGENT_GENERATION)) {
        TangentGenerator.useMikktspaceGenerator(model);
    }

    if (vars.getBoolean(PROP_EXPORT_MATERIALS)) {

        final Array<Geometry> geometries = ArrayFactory.newArray(Geometry.class);
        final ObjectDictionary<String, Geometry> mapping = DictionaryFactory.newObjectDictionary();

        final Path materialsFolder = vars.get(PROP_MATERIALS_FOLDER);
        final boolean canOverwrite = vars.getBoolean(PROP_OVERWRITE_MATERIALS);

        NodeUtils.visitGeometry(model, geometry -> checkAndAdd(geometries, geometry));
        geometries.forEach(geometry -> generateNames(mapping, geometry));
        mapping.forEach((materialName, geometry) -> storeMaterials(materialsFolder, canOverwrite, materialName, geometry));
    }

    final BinaryExporter exporter = BinaryExporter.getInstance();

    try (final OutputStream out = Files.newOutputStream(destination, WRITE, TRUNCATE_EXISTING, CREATE)) {
        exporter.save(model, out);
    }

    if (isOverwrite) {
        notifyFileChanged(destination);
    } else {
        notifyFileCreated(destination);
    }
}
 
Example #20
Source File: OgreXMLDataObject.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void saveAsset() throws IOException {
    ProjectAssetManager mgr = getLookup().lookup(ProjectAssetManager.class);
    if (mgr == null) {
        return;
    }
    String name = getPrimaryFile().getName();
    int idx = name.toLowerCase().indexOf(".mesh");
    if(idx!=-1){
        name = name.substring(0, idx);
    }
    
    ProgressHandle progressHandle = ProgressHandleFactory.createHandle("Saving File..");
    progressHandle.start();
    BinaryExporter exp = BinaryExporter.getInstance();
    FileLock lock = null;
    OutputStream out = null;
    try {
        if (saveExtension == null) {
            out = getPrimaryFile().getOutputStream();
        } else {
            FileObject outFileObject = getPrimaryFile().getParent().getFileObject(name, saveExtension);
            if (outFileObject == null) {
                outFileObject = getPrimaryFile().getParent().createData(name, saveExtension);
            }
            out = outFileObject.getOutputStream();
            outFileObject.getParent().refresh();
        }
        exp.save(savable, out);
    } finally {
        if (lock != null) {
            lock.releaseLock();
        }
        if (out != null) {
            out.close();
        }
    }
    progressHandle.finish();
    StatusDisplayer.getDefault().setStatusText(getPrimaryFile().getNameExt() + " saved.");
    setModified(false);
    
    FileObject outFile = null;
    if (saveExtension == null) {
        outFile = getPrimaryFile();
    } else {
        outFile = getPrimaryFile().getParent().getFileObject(name, saveExtension);
        if (outFile == null) {
            Logger.getLogger(SpatialAssetDataObject.class.getName()).log(Level.SEVERE, "Could not locate saved file.");
            return;
        }
    }
    try {
        DataObject targetModel = DataObject.find(outFile);
        AssetData properties = targetModel.getLookup().lookup(AssetData.class);
        if (properties != null) {
            properties.loadProperties();
            properties.setProperty("ORIGINAL_PATH", mgr.getRelativeAssetPath(outFile.getPath()));
            properties.saveProperties();
        }
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    }
}