Java Code Examples for com.jme3.export.binary.BinaryExporter#save()

The following examples show how to use com.jme3.export.binary.BinaryExporter#save() . 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: 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 3
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 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: 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 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: 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 8
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 9
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 10
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 11
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);
    }
}