List of usage examples for com.badlogic.gdx.files FileHandle parent
public FileHandle parent()
From source file:br.com.questingsoftware.libgdx.g3db.G3DBConverter.java
License:Apache License
/** <p> * Convert all G3DJ files inside a folder to G3DB format (binary JSON). * </p>//from w w w.j a va 2 s . c o m * * * @param g3djFolder Folder containing files with the {@code g3dj} extension. Ths method will not recursively navigate folders. * * @param overwrite If {@code true} and there's already a file with the same name and the {@code g3db} extension, the file will * be overwritten. Otherwise a counter will be appended at the end of the file. * * @throws IOException If there's an exception while reading the input file or writing the output file. */ public void convertFolder(FileHandle g3djFolder, boolean overwrite) throws IOException { ArrayList<FileHandle> g3djFiles = new ArrayList<FileHandle>(); if (g3djFolder != null) { if (g3djFolder.isDirectory()) { for (FileHandle handle : g3djFolder.list()) { if (handle.name().toLowerCase().endsWith(".g3dj")) { g3djFiles.add(handle); } } } else if (g3djFolder.name().toLowerCase().endsWith(".g3dj")) { FileHandle g3djFile = g3djFolder; g3djFolder = g3djFolder.parent(); g3djFiles.add(g3djFile); } } for (FileHandle handle : g3djFiles) { convert(handle, overwrite); } }
From source file:by.aleks.christmasboard.data.BitmapFontWriter.java
License:Apache License
/** A utility method which writes the given font data to a file. * /*from w ww .ja v a2 s .c om*/ * The specified pixmaps are written to the parent directory of <tt>outFntFile</tt>, using that file's name without an * extension for the PNG file name(s). * * The specified FontInfo is optional, and can be null. * * Typical usage looks like this: * * <pre> * BitmapFontWriter.writeFont(myFontData, myFontPixmaps, Gdx.files.external("fonts/output.fnt"), new FontInfo("Arial", 16)); * </pre> * * @param fontData the font data * @param pages the pixmaps to write as PNGs * @param outFntFile the output file for the font definition * @param info the optional font info for the header file, can be null */ public static void writeFont(BitmapFontData fontData, Pixmap[] pages, FileHandle outFntFile, FontInfo info) { String[] pageRefs = writePixmaps(pages, outFntFile.parent(), outFntFile.nameWithoutExtension()); //write the font data writeFont(fontData, pageRefs, outFntFile, info, pages[0].getWidth(), pages[0].getHeight()); }
From source file:com.bladecoder.engine.assets.EngineResolutionFileResolver.java
License:Apache License
protected String resolve(FileHandle originalHandle, String suffix) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(originalHandle.parent()); stringBuilder.append("/"); stringBuilder.append(suffix);//from ww w.j a va 2 s. c o m stringBuilder.append("/"); stringBuilder.append(originalHandle.name()); return stringBuilder.toString(); }
From source file:com.blindtigergames.werescrewed.graphics.TextureAtlas.java
License:Apache License
/** * Loads the specified pack file, using the parent directory of the pack * file to find the page images.// ww w . j a v a 2 s . com */ public TextureAtlas(FileHandle packFile) { this(packFile, packFile.parent()); }
From source file:com.blindtigergames.werescrewed.graphics.TextureAtlas.java
License:Apache License
/** * @param flip// w w w. j a v a 2 s .c om * If true, all regions loaded will be flipped for use with a * perspective where 0,0 is the upper left corner. * @see #TextureAtlas(FileHandle) */ public TextureAtlas(FileHandle packFile, boolean flip) { this(packFile, packFile.parent(), flip); }
From source file:com.esotericsoftware.spine.SkeletonViewer.java
License:Open Source License
void loadSkeleton(FileHandle skeletonFile, boolean reload) { if (skeletonFile == null) return;//from w ww.j av a2 s . c o m // A regular texture atlas would normally usually be used. This returns a white image for images not found in the atlas. Pixmap pixmap = new Pixmap(32, 32, Format.RGBA8888); pixmap.setColor(new Color(1, 1, 1, 0.33f)); pixmap.fill(); final AtlasRegion fake = new AtlasRegion(new Texture(pixmap), 0, 0, 32, 32); pixmap.dispose(); String atlasFileName = skeletonFile.nameWithoutExtension(); if (atlasFileName.endsWith(".json")) atlasFileName = new FileHandle(atlasFileName).nameWithoutExtension(); FileHandle atlasFile = skeletonFile.sibling(atlasFileName + ".atlas"); if (!atlasFile.exists()) atlasFile = skeletonFile.sibling(atlasFileName + ".atlas.txt"); TextureAtlasData data = !atlasFile.exists() ? null : new TextureAtlasData(atlasFile, atlasFile.parent(), false); TextureAtlas atlas = new TextureAtlas(data) { public AtlasRegion findRegion(String name) { AtlasRegion region = super.findRegion(name); return region != null ? region : fake; } }; try { String extension = skeletonFile.extension(); if (extension.equalsIgnoreCase("json") || extension.equalsIgnoreCase("txt")) { SkeletonJson json = new SkeletonJson(atlas); json.setScale(ui.scaleSlider.getValue()); skeletonData = json.readSkeletonData(skeletonFile); } else { SkeletonBinary binary = new SkeletonBinary(atlas); binary.setScale(ui.scaleSlider.getValue()); skeletonData = binary.readSkeletonData(skeletonFile); } } catch (Exception ex) { ex.printStackTrace(); ui.toast("Error loading skeleton: " + skeletonFile.name()); lastModifiedCheck = 5; return; } skeleton = new Skeleton(skeletonData); skeleton.setToSetupPose(); skeleton = new Skeleton(skeleton); skeleton.updateWorldTransform(); state = new AnimationState(new AnimationStateData(skeletonData)); this.skeletonFile = skeletonFile; Preferences prefs = Gdx.app.getPreferences("spine-skeletontest"); prefs.putString("lastFile", skeletonFile.path()); prefs.flush(); lastModified = skeletonFile.lastModified(); lastModifiedCheck = checkModifiedInterval; // Populate UI. ui.skeletonLabel.setText(skeletonFile.name()); { Array<String> items = new Array(); for (Skin skin : skeletonData.getSkins()) items.add(skin.getName()); ui.skinList.setItems(items); } { Array<String> items = new Array(); for (Animation animation : skeletonData.getAnimations()) items.add(animation.getName()); ui.animationList.setItems(items); } // Configure skeleton from UI. skeleton.setSkin(ui.skinList.getSelected()); state.setAnimation(0, ui.animationList.getSelected(), ui.loopCheckbox.isChecked()); if (reload) ui.toast("Reloaded."); }
From source file:com.kevlanche.threedeetest.ScalableObjLoader.java
License:Apache License
protected ModelData loadModelData(FileHandle file, boolean flipV) { String line;//w ww . j a v a2s . c om String[] tokens; char firstChar; MtlLoader mtl = new MtlLoader(); // Create a "default" Group and set it as the active group, in case // there are no groups or objects defined in the OBJ file. Group activeGroup = new Group("default"); groups.add(activeGroup); BufferedReader reader = new BufferedReader(new InputStreamReader(file.read()), 4096); int id = 0; try { while ((line = reader.readLine()) != null) { tokens = line.split("\\s+"); if (tokens.length < 1) break; if (tokens[0].length() == 0) { continue; } else if ((firstChar = tokens[0].toLowerCase().charAt(0)) == '#') { continue; } else if (firstChar == 'v') { if (tokens[0].length() == 1) { verts.add(Float.parseFloat(tokens[1]) * this.objScale); verts.add(Float.parseFloat(tokens[2]) * this.objScale); verts.add(Float.parseFloat(tokens[3]) * this.objScale); } else if (tokens[0].charAt(1) == 'n') { norms.add(Float.parseFloat(tokens[1])); norms.add(Float.parseFloat(tokens[2])); norms.add(Float.parseFloat(tokens[3])); } else if (tokens[0].charAt(1) == 't') { uvs.add(Float.parseFloat(tokens[1])); uvs.add((flipV ? 1 - Float.parseFloat(tokens[2]) : Float.parseFloat(tokens[2]))); } } else if (firstChar == 'f') { String[] parts; Array<Integer> faces = activeGroup.faces; for (int i = 1; i < tokens.length - 2; i--) { parts = tokens[1].split("/"); faces.add(getIndex(parts[0], verts.size)); if (parts.length > 2) { if (i == 1) activeGroup.hasNorms = true; faces.add(getIndex(parts[2], norms.size)); } if (parts.length > 1 && parts[1].length() > 0) { if (i == 1) activeGroup.hasUVs = true; faces.add(getIndex(parts[1], uvs.size)); } parts = tokens[++i].split("/"); faces.add(getIndex(parts[0], verts.size)); if (parts.length > 2) faces.add(getIndex(parts[2], norms.size)); if (parts.length > 1 && parts[1].length() > 0) faces.add(getIndex(parts[1], uvs.size)); parts = tokens[++i].split("/"); faces.add(getIndex(parts[0], verts.size)); if (parts.length > 2) faces.add(getIndex(parts[2], norms.size)); if (parts.length > 1 && parts[1].length() > 0) faces.add(getIndex(parts[1], uvs.size)); activeGroup.numFaces++; } } else if (firstChar == 'o' || firstChar == 'g') { // This implementation only supports single object or group // definitions. i.e. "o group_a group_b" will set group_a // as the active group, while group_b will simply be // ignored. if (tokens.length > 1) activeGroup = setActiveGroup(tokens[1]); else activeGroup = setActiveGroup("default"); } else if (tokens[0].equals("mtllib")) { mtl.load(file.parent().child(tokens[1])); } else if (tokens[0].equals("usemtl")) { if (tokens.length == 1) activeGroup.materialName = "default"; else activeGroup.materialName = tokens[1]; } } reader.close(); } catch (IOException e) { return null; } // If the "default" group or any others were not used, get rid of them for (int i = 0; i < groups.size; i++) { if (groups.get(i).numFaces < 1) { groups.removeIndex(i); i--; } } // If there are no groups left, there is no valid Model to return if (groups.size < 1) return null; // Get number of objects/groups remaining after removing empty ones final int numGroups = groups.size; final ModelData data = new ModelData(); for (int g = 0; g < numGroups; g++) { Group group = groups.get(g); Array<Integer> faces = group.faces; final int numElements = faces.size; final int numFaces = group.numFaces; final boolean hasNorms = group.hasNorms; final boolean hasUVs = group.hasUVs; final float[] finalVerts = new float[(numFaces * 3) * (3 + (hasNorms ? 3 : 0) + (hasUVs ? 2 : 0))]; for (int i = 0, vi = 0; i < numElements;) { int vertIndex = faces.get(i++) * 3; finalVerts[vi++] = verts.get(vertIndex++); finalVerts[vi++] = verts.get(vertIndex++); finalVerts[vi++] = verts.get(vertIndex); if (hasNorms) { int normIndex = faces.get(i++) * 3; finalVerts[vi++] = norms.get(normIndex++); finalVerts[vi++] = norms.get(normIndex++); finalVerts[vi++] = norms.get(normIndex); } if (hasUVs) { int uvIndex = faces.get(i++) * 2; finalVerts[vi++] = uvs.get(uvIndex++); finalVerts[vi++] = uvs.get(uvIndex); } } final int numIndices = numFaces * 3 >= Short.MAX_VALUE ? 0 : numFaces * 3; final short[] finalIndices = new short[numIndices]; // if there are too many vertices in a mesh, we can't use indices if (numIndices > 0) { for (int i = 0; i < numIndices; i++) { finalIndices[i] = (short) i; } } Array<VertexAttribute> attributes = new Array<VertexAttribute>(); attributes.add(new VertexAttribute(Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE)); if (hasNorms) attributes.add(new VertexAttribute(Usage.Normal, 3, ShaderProgram.NORMAL_ATTRIBUTE)); if (hasUVs) attributes.add( new VertexAttribute(Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE + "0")); String nodeId = "node" + (++id); String meshId = "mesh" + id; String partId = "part" + id; ModelNode node = new ModelNode(); node.id = nodeId; node.meshId = meshId; node.scale = new Vector3(1, 1, 1); node.translation = new Vector3(); node.rotation = new Quaternion(); ModelNodePart pm = new ModelNodePart(); pm.meshPartId = partId; pm.materialId = group.materialName; node.parts = new ModelNodePart[] { pm }; ModelMeshPart part = new ModelMeshPart(); part.id = partId; part.indices = finalIndices; part.primitiveType = GL10.GL_TRIANGLES; ModelMesh mesh = new ModelMesh(); mesh.id = meshId; mesh.attributes = attributes.toArray(VertexAttribute.class); mesh.vertices = finalVerts; mesh.parts = new ModelMeshPart[] { part }; data.nodes.add(node); data.meshes.add(mesh); ModelMaterial mm = mtl.getMaterial(group.materialName); data.materials.add(mm); } //for (ModelMaterial m : mtl.materials) //data.materials.add(m); // An instance of ObjLoader can be used to load more than one OBJ. // Clearing the Array cache instead of instantiating new // Arrays should result in slightly faster load times for // subsequent calls to loadObj if (verts.size > 0) verts.clear(); if (norms.size > 0) norms.clear(); if (uvs.size > 0) uvs.clear(); if (groups.size > 0) groups.clear(); return data; }
From source file:com.kevlanche.threedeetest.ScalableObjLoader.java
License:Apache License
/** loads .mtl file */ public void load(FileHandle file) { String line;/* w w w.j a v a 2 s.c o m*/ String[] tokens; String curMatName = "default"; Color difcolor = Color.WHITE; Color speccolor = Color.WHITE; float opacity = 1.f; float shininess = 0.f; String texFilename = null; if (file == null || file.exists() == false) return; BufferedReader reader = new BufferedReader(new InputStreamReader(file.read()), 4096); try { while ((line = reader.readLine()) != null) { if (line.length() > 0 && line.charAt(0) == '\t') line = line.substring(1).trim(); tokens = line.split("\\s+"); if (tokens[0].length() == 0) { continue; } else if (tokens[0].charAt(0) == '#') continue; else { final String key = tokens[0].toLowerCase(); if (key.equals("newmtl")) { ModelMaterial mat = new ModelMaterial(); mat.id = curMatName; mat.diffuse = new Color(difcolor); mat.specular = new Color(speccolor); mat.opacity = opacity; mat.shininess = shininess; if (texFilename != null) { ModelTexture tex = new ModelTexture(); tex.usage = ModelTexture.USAGE_DIFFUSE; tex.fileName = new String(texFilename); if (mat.textures == null) mat.textures = new Array<ModelTexture>(1); mat.textures.add(tex); } materials.add(mat); if (tokens.length > 1) { curMatName = tokens[1]; curMatName = curMatName.replace('.', '_'); } else curMatName = "default"; difcolor = Color.WHITE; speccolor = Color.WHITE; opacity = 1.f; shininess = 0.f; } else if (key.equals("kd") || key.equals("ks")) // diffuse or specular { float r = Float.parseFloat(tokens[1]); float g = Float.parseFloat(tokens[2]); float b = Float.parseFloat(tokens[3]); float a = 1; if (tokens.length > 4) a = Float.parseFloat(tokens[4]); if (tokens[0].toLowerCase().equals("kd")) { difcolor = new Color(); difcolor.set(r, g, b, a); } else { speccolor = new Color(); speccolor.set(r, g, b, a); } } else if (key.equals("tr") || key.equals("d")) { opacity = Float.parseFloat(tokens[1]); } else if (key.equals("ns")) { shininess = Float.parseFloat(tokens[1]); } else if (key.equals("map_kd")) { texFilename = file.parent().child(tokens[1]).path(); } } } reader.close(); } catch (IOException e) { return; } // last material ModelMaterial mat = new ModelMaterial(); mat.id = curMatName; mat.diffuse = new Color(difcolor); mat.specular = new Color(speccolor); mat.opacity = opacity; mat.shininess = shininess; if (texFilename != null) { ModelTexture tex = new ModelTexture(); tex.usage = ModelTexture.USAGE_DIFFUSE; tex.fileName = new String(texFilename); if (mat.textures == null) mat.textures = new Array<ModelTexture>(1); mat.textures.add(tex); } materials.add(mat); return; }
From source file:com.kotcrab.vis.editor.assets.transaction.generator.AtlasRegionAssetTransactionGenerator.java
License:Apache License
@Override public AssetTransaction analyze(ModuleInjector injector, AssetProviderResult providerResult, FileHandle source, FileHandle target, String relativeTargetPath) { Array<FileHandle> sourcePngs = new Array<>(); Array<FileHandle> targetPngs = new Array<>(); TextureAtlasData data = new TextureAtlasData(source, source.parent(), false); for (int i = 0; i < data.getPages().size; i++) { Page page = data.getPages().get(i); sourcePngs.add(page.textureFile); if (i == 0) { targetPngs.add(target.parent().child(target.nameWithoutExtension() + ".png")); } else {// www .j a v a2 s. c o m targetPngs.add(target.parent().child(target.nameWithoutExtension() + i + ".png")); } } AssetTransaction transaction = new AssetTransaction(); transaction.add(new CopyFileAction(source, target)); for (int i = 0; i < sourcePngs.size; i++) { transaction.add(new CopyFileAction(sourcePngs.get(i), targetPngs.get(i))); } transaction.add(new UpdateReferencesAction(injector, providerResult, new AtlasRegionAsset(relativeTargetPath, null))); transaction.add(new DeleteFileAction(source, transactionStorage)); transaction.add(new UndoableAction() { //update references in atlas file boolean updatingRefs = true; @Override public void execute() { try { BufferedReader file = new BufferedReader(new FileReader(target.file())); String line; String output = ""; while ((line = file.readLine()) != null) { if (updatingRefs && line.contains(":")) updatingRefs = false; if (updatingRefs) { for (int i = 0; i < sourcePngs.size; i++) { if (line.equals(sourcePngs.get(i).name())) line = targetPngs.get(i).name(); } } output += line + '\n'; } file.close(); FileOutputStream fileOut = new FileOutputStream(target.file()); fileOut.write(output.getBytes()); fileOut.close(); } catch (IOException e) { Log.exception(e); } } @Override public void undo() { //do nothing, file will deleted when CopyFileAction will be undone } }); for (int i = 0; i < sourcePngs.size; i++) { transaction.add(new DeleteFileAction(sourcePngs.get(i), transactionStorage)); } transaction.finalizeGroup(); return transaction; }
From source file:com.kotcrab.vis.editor.assets.transaction.generator.BmpFontAssetTransactionGenerator.java
License:Apache License
@Override public AssetTransaction analyze(ModuleInjector injector, AssetProviderResult providerResult, FileHandle source, FileHandle target, String relativeTargetPath) { AssetTransaction transaction = new AssetTransaction(); BitmapFontData data = new BitmapFontData(source, false); Array<FileHandle> sourcePngs = new Array<>(); Array<FileHandle> targetPngs = new Array<>(); for (int i = 0; i < data.imagePaths.length; i++) { String path = data.imagePaths[i]; FileHandle file = Gdx.files.absolute(path); sourcePngs.add(file);/* w w w . ja v a 2 s .c o m*/ if (i == 0) targetPngs.add(target.parent().child(target.nameWithoutExtension() + ".png")); else targetPngs.add(target.parent().child(target.nameWithoutExtension() + i + ".png")); } transaction.add(new CopyFileAction(source, target)); for (int i = 0; i < sourcePngs.size; i++) transaction.add(new CopyFileAction(sourcePngs.get(i), targetPngs.get(i))); transaction.add( new UpdateReferencesAction(injector, providerResult, new BmpFontAsset(relativeTargetPath, null))); transaction.add(new DeleteFileAction(source, transactionStorage)); transaction.add(new UndoableAction() { //update references in font file boolean updatingRefs = true; @Override public void execute() { try { BufferedReader file = new BufferedReader(new FileReader(target.file())); String line; String output = ""; while ((line = file.readLine()) != null) { if (updatingRefs && line.startsWith("chars count=")) updatingRefs = false; if (updatingRefs) { for (int i = 0; i < sourcePngs.size; i++) { String prefix = "page id=" + i + " file=\""; if (line.startsWith(prefix + sourcePngs.get(i).name())) { line = line.replace(prefix + sourcePngs.get(i).name(), prefix + targetPngs.get(i).name()); } } } output += line + '\n'; } file.close(); FileOutputStream fileOut = new FileOutputStream(target.file()); fileOut.write(output.getBytes()); fileOut.close(); } catch (IOException e) { Log.exception(e); } } @Override public void undo() { //do nothing, file will deleted when CopyFileAction will be undone } }); for (int i = 0; i < sourcePngs.size; i++) transaction.add(new DeleteFileAction(sourcePngs.get(i), transactionStorage)); transaction.finalizeGroup(); return transaction; }