Skip to content
This repository has been archived by the owner on Dec 28, 2021. It is now read-only.

Commit

Permalink
add async functions for loading project and levels
Browse files Browse the repository at this point in the history
  • Loading branch information
LeHaine committed Mar 20, 2021
1 parent f3e5d27 commit 961a19f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
19 changes: 17 additions & 2 deletions ldtk-api/src/commonMain/kotlin/com/lehaine/ldtk/Level.kt
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,23 @@ open class Level(val project: Project, val definition: LevelDefinition) {
}
val relPath = externalRelPath ?: return false
val jsonString = project.getAsset(relPath).toString(Charsets.UTF8)

initJson(jsonString)
return true
}

suspend fun loadAsync(): Boolean {
if (isLoaded()) {
return true
}
val relPath = externalRelPath ?: return false
val jsonString = project.getAssetAsync(relPath).toString(Charsets.UTF8)

initJson(jsonString)
return true
}

private fun initJson(jsonString: String) {
val json =
LDtkApi.parseLDtkLevelFile(jsonString) ?: error("Unable to parse Level JSON")

Expand Down Expand Up @@ -142,8 +159,6 @@ open class Level(val project: Project, val definition: LevelDefinition) {
json.neighbours?.forEach {
_neighbors.add(Neighbor(it.levelUid, NeighborDirection.fromDir(it.dir)))
}

return true
}

fun resolveLayer(id: String): Layer {
Expand Down
20 changes: 20 additions & 0 deletions ldtk-api/src/commonMain/kotlin/com/lehaine/ldtk/Project.kt
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,17 @@ open class Project(val projectFilePath: String) {
}
}

suspend fun loadAsync() {
val jsonString = loadLDtkJsonAsync()
initJson(jsonString)
}

fun load() {
val jsonString = loadLDtkJson()
initJson(jsonString)
}

private fun initJson(jsonString: String) {
if (jsonString.isEmpty()) {
error("An empty file was passed in.")
}
Expand Down Expand Up @@ -71,6 +79,10 @@ open class Project(val projectFilePath: String) {
}
}

protected open suspend fun loadLDtkJsonAsync(): String {
return resourcesVfs[projectFilePath].readString()
}

open fun getAsset(assetPath: String): ByteArray {
if (assetCache.contains(assetPath)) {
return assetCache[assetPath] ?: error("Unable to load asset from asset cache!")
Expand All @@ -81,6 +93,14 @@ open class Project(val projectFilePath: String) {
}
}

open suspend fun getAssetAsync(assetPath: String): ByteArray {
if (assetCache.contains(assetPath)) {
return assetCache[assetPath] ?: error("Unable to load asset from asset cache!")
}

return resourcesVfs[assetPath].readBytes()
}

fun getLayerDef(uid: Int?, identifier: String? = ""): LayerDefinition? {
if (uid == null && identifier == null) {
return null
Expand Down

0 comments on commit 961a19f

Please sign in to comment.