Java Code Examples for com.badlogic.gdx.files.FileHandle

The following examples show how to use com.badlogic.gdx.files.FileHandle. These examples are extracted from open source projects. 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 Project: bladecoder-adventure-engine   Source File: UI.java    License: Apache License 2.0 6 votes vote down vote up
private void loadAssets() {
	FileHandle skinFile = EngineAssetManager.getInstance().getAsset(SKIN_FILENAME);
	TextureAtlas atlas = new TextureAtlas(EngineAssetManager.getInstance()
			.getResAsset(SKIN_FILENAME.substring(0, SKIN_FILENAME.lastIndexOf('.')) + ".atlas"));
	skin = new BladeSkin(atlas);

	((BladeSkin) skin).addStyleTag(VerbUI.VerbUIStyle.class);
	((BladeSkin) skin).addStyleTag(TextManagerUI.TextManagerUIStyle.class);
	((BladeSkin) skin).addStyleTag(DialogUI.DialogUIStyle.class);
	((BladeSkin) skin).addStyleTag(InventoryUI.InventoryUIStyle.class);
	((BladeSkin) skin).addStyleTag(CreditsScreen.CreditScreenStyle.class);
	((BladeSkin) skin).addStyleTag(LoadSaveScreen.LoadSaveScreenStyle.class);
	((BladeSkin) skin).addStyleTag(MenuScreen.MenuScreenStyle.class);

	skin.load(skinFile);

	if (!Config.getInstance().getProperty(Config.CHARACTER_ICON_ATLAS, "").equals("")) {
		EngineAssetManager.getInstance().loadAtlas(Config.getInstance().getProperty(Config.CHARACTER_ICON_ATLAS, null));
		EngineAssetManager.getInstance().finishLoading();
	}
}
 
Example 2
Source Project: gdx-proto   Source File: Terrain.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Return a heightmap chunk
 * TODO NOT IMPLEMENTED! 
 * @param heightmap
 * @param tex
 * @param width
 * @param height
 * @return
 */
public static TerrainChunk CreateHeightMapChunk (FileHandle heightmap, Texture tex, int width, int height) {
	HeightMap hp = new HeightMap(heightmap, 10, 10, false, 3);
	
	HeightMapModel md = new HeightMapModel(hp);
	//Model model = md.ground;
	 md.ground.materials.get(0).set(TextureAttribute.createDiffuse(tex));
	 
	//btCollisionObject obj = new btCollisionObject();
	//btCollisionShape shape = new btBvhTriangleMeshShape(model.meshParts);
	//obj.setCollisionShape(shape);
	////Physics.applyStaticGeometryCollisionFlags(obj);
	//Physics.inst.addStaticGeometryToWorld(obj);
	TerrainChunk ch = new  TerrainChunk();
	ch.setModelInstance(md.ground);
	
	return ch;
}
 
Example 3
Source Project: skin-composer   Source File: Dialog9Patch.java    License: MIT License 6 votes vote down vote up
private void showLoadPatchesDialog() {
    Runnable runnable = () -> {
        String defaultPath = main.getProjectData().getLastDrawablePath();

        String[] filterPatterns = null;
        if (!Utils.isMac()) {
            filterPatterns = new String[]{"*.9.png;"};
        }

        File file = main.getDesktopWorker().openDialog("Load Patches from File...", defaultPath, filterPatterns, "Nine Patch files");
        if (file != null) {
            Gdx.app.postRunnable(() -> {
                var fileHandle = new FileHandle(file);
                loadPatches(fileHandle);
            });
        }
    };

    main.getDialogFactory().showDialogLoading(runnable);
}
 
Example 4
Source Project: Cubes   Source File: Screenshot.java    License: MIT License 6 votes vote down vote up
private static void writeScreenshot(final Pixmap pixmap) {
  FileHandle dir = Compatibility.get().getBaseFolder().child("screenshots");
  dir.mkdirs();
  final FileHandle f = dir.child(System.currentTimeMillis() + ".png");
  Log.info("Writing screenshot '" + f.file().getAbsolutePath() + "'");
  Executor.executeNotSided(new Runnable() {
    @Override
    public void run() {
      long start = System.currentTimeMillis();
      try {
        PixmapIO.PNG writer = new PixmapIO.PNG((int) (pixmap.getWidth() * pixmap.getHeight() * 1.5f));
        try {
          writer.setFlipY(true);
          writer.write(f, pixmap);
        } finally {
          writer.dispose();
        }
      } catch (IOException ex) {
        throw new CubesException("Error writing PNG: " + f, ex);
      } finally {
        pixmap.dispose();
      }
      Log.debug("Finished writing screenshot '" + f.file().getAbsolutePath() + "' (took " + (System.currentTimeMillis() - start) + "ms)");
    }
  });
}
 
Example 5
Source Project: gdx-texture-packer-gui   Source File: GlobalActions.java    License: Apache License 2.0 6 votes vote down vote up
@LmlAction("openProject") public void openProject() {
      final ProjectModel project = getProject();
      FileHandle dir = fileChooserHistory.getLastDir(FileChooserHistory.Type.PROJECT);
      if (FileUtils.fileExists(project.getProjectFile())) {
          dir = project.getProjectFile().parent();
      }

      final FileChooser fileChooser = new FileChooser(dir, FileChooser.Mode.OPEN);
      fileChooser.setIconProvider(new AppIconProvider(fileChooser));
      fileChooser.setSelectionMode(FileChooser.SelectionMode.FILES);
fileChooser.setFileTypeFilter(new FileUtils.FileTypeFilterBuilder(true)
	.rule(getString("projectFileDescription", AppConstants.PROJECT_FILE_EXT), AppConstants.PROJECT_FILE_EXT).get());
      fileChooser.setListener(new FileChooserAdapter() {
          @Override
          public void selected (Array<FileHandle> file) {
              final FileHandle chosenFile = file.first();
              commonDialogs.checkUnsavedChanges(new Runnable() {
                  @Override
                  public void run() {
                      loadProject(chosenFile);
                  }
              });
          }
      });
      getStage().addActor(fileChooser.fadeIn());
  }
 
Example 6
Source Project: uracer-kotd   Source File: ReplayUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean pruneReplay (ReplayInfo info) {
	if (info != null && ReplayUtils.areValidIds(info)) {
		String rid = info.getId();
		if (rid.length() > 0) {
			String path = getFullPath(info);
			if (path.length() > 0) {
				FileHandle hf = Gdx.files.external(path);
				if (hf.exists()) {
					hf.delete();
					Gdx.app.log("ReplayUtils", "Pruned #" + rid);
					return true;
				} else {
					Gdx.app.error("ReplayUtils", "Couldn't prune #" + rid);
				}
			}
		}
	}

	return false;
}
 
Example 7
Source Project: talos   Source File: ProjectController.java    License: Apache License 2.0 6 votes vote down vote up
public void reportProjectFileInterraction(FileHandle handle) {
    Preferences prefs = TalosMain.Instance().Prefs();
    String data = prefs.getString("recents");
    Array<RecentsEntry> list = new Array<>();
    //read
    Json json = new Json();
    try {
        if (data != null && !data.isEmpty()) {
            list = json.fromJson(list.getClass(), data);
        }
    } catch( Exception e) {

    }
    RecentsEntry newEntry = new RecentsEntry(handle.path(), TimeUtils.millis());
    list.removeValue(newEntry, false);
    list.add(newEntry);
    //sort
    list.sort(recentsEntryComparator);
    //write
    String result = json.toJson(list);
    prefs.putString("recents", result);
    prefs.flush();
    updateRecentsList();
}
 
Example 8
Source Project: ud406   Source File: FileLoading.java    License: MIT License 6 votes vote down vote up
@Override
public void create() {
    batch = new SpriteBatch();
    img = new Texture("badlogic.jpg");

    String encryptedPunchline = encrypt("Very Carefully");
    Gdx.app.log(TAG, encryptedPunchline);

    Gdx.app.log(TAG, "How does GigaGal tie her shoelaces when her arms are cannons?");

    // TODO: Go find the text file in the android/assets directory
    // TODO: Get a FileHandle using Gdx.files.internal()
    FileHandle file = Gdx.files.internal("punchline");

    // TODO: Read the file using FileHandle.readString()
    String encrypted = file.readString();

    // TODO: Decrypt the punchline
    String punchline = decrypt(encrypted);

    // TODO: Log the rest of the joke
    Gdx.app.log(TAG, punchline);
}
 
Example 9
Source Project: Mundus   Source File: MG3dModelLoader.java    License: Apache License 2.0 6 votes vote down vote up
public ModelData parseModel(FileHandle handle) {
    JsonValue json = reader.parse(handle);
    ModelData model = new ModelData();
    JsonValue version = json.require("version");
    model.version[0] = version.getShort(0);
    model.version[1] = version.getShort(1);
    if (model.version[0] != VERSION_HI || model.version[1] != VERSION_LO)
        throw new GdxRuntimeException("Model version not supported");

    model.id = json.getString("id", "");
    parseMeshes(model, json);
    parseMaterials(model, json, handle.parent().path());
    parseNodes(model, json);
    parseAnimations(model, json);
    return model;
}
 
Example 10
@LmlAction("pickOutputDir") void pickOutputDir() {
    FileHandle dir = FileUtils.obtainIfExists(edtOutputDir.getText());
    if (dir == null && FileUtils.fileExists(edtAtlasPath.getText())) {
        dir = FileUtils.obtainIfExists(edtAtlasPath.getText()).parent();
    }

    FileChooser fileChooser = new FileChooser(dir, FileChooser.Mode.OPEN);
    fileChooser.setIconProvider(new AppIconProvider(fileChooser));
    fileChooser.setSelectionMode(FileChooser.SelectionMode.DIRECTORIES);
    fileChooser.setListener(new FileChooserAdapter() {
        @Override
        public void selected (Array<FileHandle> file) {
            FileHandle chosenFile = file.first();
            edtOutputDir.setText(chosenFile.path());
        }
    });
    stage.addActor(fileChooser.fadeIn());
}
 
Example 11
Source Project: talos   Source File: BatchConvertDialog.java    License: Apache License 2.0 6 votes vote down vote up
private void startConversion() {
    String inputPath = inputPathField.getText();
    outputPath = outputPathField.getText();
    String extension = inputFilterField.getText();

    fileList.clear();

    FileHandle input = Gdx.files.absolute(inputPath);

    if(input.isDirectory() && input.exists()) {
        traverseFolder(input, fileList, extension, 0);
    }

    isConverting = true;
    logArea.clearItems();
}
 
Example 12
Source Project: gdx-soundboard   Source File: FileChooser.java    License: MIT License 6 votes vote down vote up
/**
 * Create file picking dialog.
 * 
 * @param title
 * @param skin
 * @param path
 * @return
 */
public static FileChooser createPickDialog(String title, final Skin skin, final FileHandle path) {
    final FileChooser pick = new FileChooser(title, skin, path) {
        @Override
        protected void result(Object object) {

            if (resultListener == null) {
                return;
            }

            final boolean success = (Boolean) object;
            resultListener.result(success, getResult());
        }
    }.setOkButtonText("Select");

    return pick;
}
 
Example 13
Source Project: skin-composer   Source File: DialogImageFont.java    License: MIT License 6 votes vote down vote up
private void loadSettings(FileHandle file) {
    var imagePath = ((TextField) findActor("imagepath")).getText();
    var targetPath = ((TextField) findActor("targetpath")).getText();
    
    json.setOutputType(JsonWriter.OutputType.json);
    settings = json.fromJson(ImageFontSettings.class, file.readString("utf-8"));
    refreshTable();
    previewStyle.fontColor = settings.previewColor;
    previewStyle.background = ((NinePatchDrawable) previewStyle.background).tint(settings.previewBackgroundColor);
    previewStyle.focusedBackground = ((NinePatchDrawable) previewStyle.focusedBackground).tint(settings.previewBackgroundColor);
    
    if (targetPath != null && !targetPath.equals("")) {
        processSaveFile(targetPath);
    }
    
    if (imagePath != null && !imagePath.equals("")) {
        processSourceFile(Gdx.files.absolute(imagePath), false);
    }
}
 
Example 14
Source Project: vis-ui   Source File: FileHistoryManager.java    License: Apache License 2.0 5 votes vote down vote up
public void historyForward () {
	FileHandle dir = historyForward.pop();
	history.add(callback.getCurrentDirectory());

	if (setDirectoryFromHistory(dir) == false)
		history.pop();

	if (!hasHistoryForward()) forwardButton.setDisabled(true);

	backButton.setDisabled(false);
}
 
Example 15
Source Project: Cubes   Source File: Compatibility.java    License: MIT License 5 votes vote down vote up
public void makeBaseFolder() {
  FileHandle baseFolder = getBaseFolder();
  baseFolder.mkdirs();
  if (!baseFolder.isDirectory()) {
    FileHandle parent = baseFolder.parent();
    if (!parent.isDirectory()) Log.error("Parent directory '" + parent.path() + "' doesn't exist!");
    throw new CubesException("Failed to make Cubes folder! '" + baseFolder.path() + "'");
  }
}
 
Example 16
Source Project: gdx-vfx   Source File: VfxGLUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static ShaderProgram compileShader(FileHandle vertexFile, FileHandle fragmentFile, String defines) {
    if (fragmentFile == null) {
        throw new IllegalArgumentException("Vertex shader file cannot be null.");
    }
    if (vertexFile == null) {
        throw new IllegalArgumentException("Fragment shader file cannot be null.");
    }
    if (defines == null) {
        throw new IllegalArgumentException("Defines cannot be null.");
    }

    StringBuilder sb = new StringBuilder();
    sb.append("Compiling \"").append(vertexFile.name()).append('/').append(fragmentFile.name()).append('\"');
    if (defines.length() > 0) {
        sb.append(" w/ (").append(defines.replace("\n", ", ")).append(")");
    }
    sb.append("...");
    Gdx.app.log(TAG, sb.toString());

    String prependVert = prependVertexCode + defines;
    String prependFrag = prependFragmentCode + defines;
    String srcVert = vertexFile.readString();
    String srcFrag = fragmentFile.readString();

    ShaderProgram shader = new ShaderProgram(prependVert + "\n" + srcVert, prependFrag + "\n" + srcFrag);

    if (!shader.isCompiled()) {
        throw new GdxRuntimeException("Shader compile error: " + vertexFile.name() + "/" + fragmentFile.name() + "\n" + shader.getLog());
    }
    return shader;
}
 
Example 17
Source Project: gdx-pd   Source File: PdAudioBakery.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Add a new baking task.
 * @param patchFile patch file to bake.
 * @param array destination array to write to.
 * @param sampleRate sample rate to use.
 * @param time destination duration.
 */
public void addTask(FileHandle patchFile, String array, int sampleRate, float time){
	if(bakingThread != null){
		throw new GdxRuntimeException("addTask should only be called before baking process.");
	}
	Baking baking = new Baking();
	baking.patchFile = patchFile;
	baking.array = array;
	baking.sampleRate = sampleRate;
	baking.time = time;
	pendingBakings.add(baking);
}
 
Example 18
Source Project: vis-ui   Source File: FileChooser.java    License: Apache License 2.0 5 votes vote down vote up
private void showOverwriteQuestion (final Array<FileHandle> filesList) {
	String text = filesList.size == 1 ? POPUP_FILE_EXIST_OVERWRITE.get() : POPUP_MULTIPLE_FILE_EXIST_OVERWRITE.get();
	Dialogs.showOptionDialog(getChooserStage(), POPUP_TITLE.get(), text, OptionDialogType.YES_NO, new OptionDialogAdapter() {
		@Override
		public void yes () {
			notifyListenerAndCloseDialog(filesList);
		}
	});
}
 
Example 19
Source Project: gdx-fireapp   Source File: StorageTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void upload() {
    // Given
    Storage storage = new Storage();

    // When
    storage.upload("test", Mockito.mock(FileHandle.class)).subscribe();

    // Then
    Mockito.verify(Gdx.app, VerificationModeFactory.times(1)).error(Mockito.anyString(), Mockito.anyString());
}
 
Example 20
Source Project: Cubes   Source File: ModManager.java    License: MIT License 5 votes vote down vote up
private static List<FileHandle> getModFiles() {
  FileHandle base = Compatibility.get().getBaseFolder().child("mods");
  base.mkdirs();
  Compatibility.get().nomedia(base);
  ArrayList<FileHandle> fileHandles = new ArrayList<FileHandle>();
  fileHandles.addAll(extraMods);
  Collections.addAll(fileHandles, base.list(new FileFilter() {
    @Override
    public boolean accept(File pathname) {
      String s = pathname.getName().toLowerCase();
      return s.endsWith(".cm");
    }
  }));
  return fileHandles;
}
 
Example 21
Source Project: Cubes   Source File: JsonLoader.java    License: MIT License 5 votes vote down vote up
public static void loadCore() {
  AssetManager core = Assets.getCoreAssetManager();
  HashMap<String, FileHandle> map = new HashMap<String, FileHandle>();
  for (Asset j : core.getAssets("json/")) {
    map.put(j.getPath().substring(5), j.getFileHandle());
  }
  try {
    coreMap = load(map);
  } catch (IOException e) {
    throw new CubesException("Failed to load core json", e);
  }
}
 
Example 22
Source Project: Cubes   Source File: SaveAreaIO.java    License: MIT License 5 votes vote down vote up
public static FileHandle file(Save save, int x, int z) {
  FileHandle folderArea = save.folderArea();
  FileHandle xMostSignificant = folderArea.child(Integer.toString(x & 0xFFFF0000));
  FileHandle xLeastSignificant = xMostSignificant.child(Integer.toString(x & 0xFFFF));
  FileHandle zMostSignificant = xLeastSignificant.child(Integer.toString(z & 0xFFFF0000));
  zMostSignificant.mkdirs();
  Compatibility.get().nomedia(zMostSignificant);
  
  return zMostSignificant.child(Integer.toString(z & 0xFFFF));
}
 
Example 23
Source Project: mini2Dx   Source File: Mini2DxOpenALAudio.java    License: Apache License 2.0 5 votes vote down vote up
public Mini2DxOpenALSound newSound (FileHandle file) {
	if (file == null) throw new IllegalArgumentException("file cannot be null.");
	Class<? extends Mini2DxOpenALSound> soundClass = extensionToSoundClass.get(file.extension().toLowerCase());
	if (soundClass == null) throw new GdxRuntimeException("Unknown file extension for sound: " + file);
	try {
		return soundClass.getConstructor(new Class[] {Mini2DxOpenALAudio.class, FileHandle.class}).newInstance(this, file);
	} catch (Exception ex) {
		throw new GdxRuntimeException("Error creating sound " + soundClass.getName() + " for file: " + file, ex);
	}
}
 
Example 24
Source Project: gdx-texture-packer-gui   Source File: AtlasModel.java    License: Apache License 2.0 5 votes vote down vote up
public AtlasModel(FileHandle atlasFile) {
    this.atlasFile = atlasFile;
    this.atlasData = new TextureAtlasData(atlasFile, atlasFile.parent(), false);
    atlasPath = atlasFile.file().getAbsolutePath();

    generatePages(atlasData);
}
 
Example 25
Source Project: uracer-kotd   Source File: UAtlasTmxMapLoader.java    License: Apache License 2.0 5 votes vote down vote up
/** May return null. */
protected FileHandle loadAtlas (Element root, FileHandle tmxFile) throws IOException {
	Element e = root.getChildByName("properties");

	if (e != null) {
		for (Element property : e.getChildrenByName("property")) {
			String name = property.getAttribute("name", null);
			String value = property.getAttribute("value", null);
			if (name.equals("atlas")) {
				if (value == null) {
					value = property.getText();
				}

				if (value == null || value.length() == 0) {
					// keep trying until there are no more atlas properties
					continue;
				}

				return getRelativeFileHandle(tmxFile, value);
			}
		}
	} else {
		FileHandle atlasFile = tmxFile.sibling(tmxFile.nameWithoutExtension() + ".atlas");
		return atlasFile.exists() ? atlasFile : null;
	}

	return null;
}
 
Example 26
Source Project: riiablo   Source File: BinGenerationTool.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void generate(FileHandle txt, FileHandle bin, Class<Excel> excelClass) throws Exception {
  Gdx.app.log(TAG, bin.toString());
  Excel<Excel.Entry> excel = Excel.load(excelClass, txt, Excel.EXPANSION);
  OutputStream out = null;
  try {
    out = bin.write(false, 8192);
    LittleEndianDataOutputStream dos = new LittleEndianDataOutputStream(out);
    excel.writeBin(dos);
  } catch (Throwable t) {
    Gdx.app.error(TAG, t.getMessage(), t);
  } finally {
    IOUtils.closeQuietly(out);
  }

  if (VALIDATE_BIN) {
    Class<Excel.Entry> entryClass = getEntryClass(excelClass);
    String binClassName = excelClass.getName() + "Bin";
    Class binClass = Class.forName(binClassName);
    Method equals = binClass.getMethod("equals", entryClass, entryClass);
    Excel binExcel = Excel.load(excelClass, txt, bin, null);
    if (binExcel.size() != excel.size()) Gdx.app.error(TAG, "excel sizes do not match!");
    for (Excel.Entry e1 : excel) {
      Excel.Entry eq = getEqual(equals, e1, binExcel);
      if (eq == null) {
        Gdx.app.log(TAG, "ERROR at index " + e1);
        //break;
      } else {
        //Gdx.app.log(TAG, e1 + "=" + eq);
      }
    }
  }
}
 
Example 27
Source Project: Cubes   Source File: Save.java    License: MIT License 5 votes vote down vote up
public Player readPlayer(UUID uuid, ClientIdentifier clientIdentifier) {
  if (fileHandle == null) return null;
  FileHandle folder = folderPlayer();
  FileHandle file = folder.child(uuid.toString());
  if (!file.exists()) return null;
  try {
    DataGroup data = (DataGroup) Data.input(file.file());
    Player player = new Player(data.getString("username"), uuid, clientIdentifier);
    player.read(data);
    return player;
  } catch (Exception e) {
    Log.warning("Failed to read player", e);
    return null;
  }
}
 
Example 28
Source Project: gdx-gltf   Source File: GLTFExporter.java    License: Apache License 2.0 5 votes vote down vote up
/** convenient method to export a single scene */
public void export(SceneModel scene, FileHandle file) {
	GLTFScene glScene = beginSingleScene(file);
	
	exportScene(glScene, scene);
	
	end(file);
}
 
Example 29
Source Project: mini2Dx   Source File: Mini2DxOpenALAudio.java    License: Apache License 2.0 5 votes vote down vote up
public Mini2DxOpenALSound newSound(FileHandle file) {
	if (file == null)
		throw new IllegalArgumentException("file cannot be null.");
	Class<? extends Mini2DxOpenALSound> soundClass = extensionToSoundClass.get(file.extension().toLowerCase());
	if (soundClass == null)
		throw new GdxRuntimeException("Unknown file extension for sound: " + file);
	try {
		return soundClass.getConstructor(new Class[] { Mini2DxOpenALAudio.class, FileHandle.class }).newInstance(this,
				file);
	} catch (Exception ex) {
		throw new GdxRuntimeException("Error creating sound " + soundClass.getName() + " for file: " + file, ex);
	}
}
 
Example 30
Source Project: riiablo   Source File: BitmapFontLoader.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public FontTBL.BitmapFont loadSync(AssetManager assets, String fileName, FileHandle file, Params params) {
  FontTBL.BitmapFont font = new FontTBL.BitmapFont(data);
  name = null;
  dc6 = null;
  data = null;
  return font;
}