trying to load a world

This commit is contained in:
minjaesong
2021-08-25 15:18:05 +09:00
parent 8499746ad0
commit 9a8bd8d6ec
19 changed files with 164 additions and 167 deletions

View File

@@ -22,7 +22,6 @@ import net.torvald.terrarum.langpack.Lang
import net.torvald.terrarum.modulebasegame.IngameRenderer
import net.torvald.terrarum.modulebasegame.TerrarumIngame
import net.torvald.terrarum.modulebasegame.gameactors.HumanoidNPC
import net.torvald.terrarum.modulebasegame.gameworld.GameWorldExtension
import net.torvald.terrarum.gameworld.WorldTime
import net.torvald.terrarum.modulebasegame.ui.UIRemoCon
import net.torvald.terrarum.modulebasegame.ui.UITitleRemoConYaml
@@ -55,7 +54,7 @@ class TitleScreen(batch: SpriteBatch) : IngameInstance(batch) {
//private var loadDone = false // not required; draw-while-loading is implemented in the AppLoader
private lateinit var demoWorld: GameWorldExtension
private lateinit var demoWorld: GameWorld
private lateinit var cameraNodes: FloatArray // camera Y-pos
private val cameraAI = object : ActorAI {
private val axisMax = 1f
@@ -122,7 +121,7 @@ class TitleScreen(batch: SpriteBatch) : IngameInstance(batch) {
printdbg(this, "Intro pre-load")
demoWorld = GameWorldExtension(1, 64, 64, 0L, 0L, 0)
demoWorld = GameWorld(1, 64, 64, 0L, 0L, 0)
printdbg(this, "Demo world gen complete")

View File

@@ -62,7 +62,7 @@ object CommandDict {
/* !! */"exportmeta" to ExportMeta,
/* !! */"exportworld" to ExportWorld,
/* !! */"exportactor" to ExportActor,
/* !! */"importlayer" to ImportLayerData,
/* !! */"importworld" to ImportWorld,
/* !! */"exportfborgb" to ExportRendererFboRGB
)

View File

@@ -32,7 +32,7 @@ import kotlin.math.sign
typealias BlockAddress = Long
open class GameWorld : Disposable {
class GameWorld : Disposable {
var worldName: String = "New World"
/** Index start at 1 */
@@ -49,37 +49,37 @@ open class GameWorld : Disposable {
val width: Int
val height: Int
open val creationTime: Long
open var lastPlayTime: Long
var creationTime: Long
internal set
var lastPlayTime: Long
internal set // there's a case of save-and-continue-playing
open var totalPlayTime: Int
var totalPlayTime: Int
internal set
/** Used to calculate play time */
@Transient open val loadTime: Long = System.currentTimeMillis() / 1000L
//layers
val layerWall: BlockLayer
val layerTerrain: BlockLayer
//val layerWire: MapLayer
lateinit var layerWall: BlockLayer
lateinit var layerTerrain: BlockLayer
//val layerThermal: MapLayerHalfFloat // in Kelvins
//val layerFluidPressure: MapLayerHalfFloat // (milibar - 1000)
/** Tilewise spawn point */
open var spawnX: Int
var spawnX: Int
/** Tilewise spawn point */
open var spawnY: Int
var spawnY: Int
val wallDamages: HashMap<BlockAddress, Float>
val terrainDamages: HashMap<BlockAddress, Float>
val fluidTypes: HashMap<BlockAddress, FluidType>
val fluidFills: HashMap<BlockAddress, Float>
val wallDamages = HashMap<BlockAddress, Float>()
val terrainDamages = HashMap<BlockAddress, Float>()
val fluidTypes = HashMap<BlockAddress, FluidType>()
val fluidFills = HashMap<BlockAddress, Float>()
/**
* Single block can have multiple conduits, different types of conduits are stored separately.
*/
private val wirings: HashMap<BlockAddress, WiringNode>
private val wirings = HashMap<BlockAddress, WiringNode>()
private val wiringGraph = HashMap<BlockAddress, HashMap<ItemID, WiringSimCell>>()
@Transient private val WIRE_POS_MAP = intArrayOf(1,2,4,8)
@@ -111,9 +111,11 @@ open class GameWorld : Disposable {
)
val tileNumberToNameMap: HashMap<Int, ItemID>
val tileNumberToNameMap = HashMap<Int, ItemID>()
// does not go to the savefile
@Transient val tileNameToNumberMap: HashMap<ItemID, Int>
@Transient val tileNameToNumberMap = HashMap<ItemID, Int>()
val extraFields = HashMap<String, Any?>()
/**
* Create new world
@@ -130,15 +132,6 @@ open class GameWorld : Disposable {
layerTerrain = BlockLayer(width, height)
layerWall = BlockLayer(width, height)
//layerWire = MapLayer(width, height)
wallDamages = HashMap()
terrainDamages = HashMap()
fluidTypes = HashMap()
fluidFills = HashMap()
//wiringBlocks = HashMap()
wirings = HashMap()
// temperature layer: 2x2 is one cell
//layerThermal = MapLayerHalfFloat(width, height, averageTemperature)
@@ -151,9 +144,22 @@ open class GameWorld : Disposable {
lastPlayTime = lastPlayTIME_T
this.totalPlayTime = totalPlayTime
postLoad()
}
tileNumberToNameMap = HashMap<Int, ItemID>()
tileNameToNumberMap = HashMap<ItemID, Int>()
constructor() {
worldIndex = 1234567890
width = 999
height = 999
val time = AppLoader.getTIME_T()
creationTime = time
lastPlayTime = time
totalPlayTime = 0
spawnX = 0
spawnY = 0
}
fun postLoad() {
AppLoader.tileMaker.tags.forEach {
printdbg(this, "tileNumber ${it.value.tileNumber} <-> tileName ${it.key}")
@@ -211,7 +217,14 @@ open class GameWorld : Disposable {
*/
fun getTileFromWall(rawX: Int, rawY: Int): ItemID {
val (x, y) = coerceXY(rawX, rawY)
return tileNumberToNameMap[layerWall.unsafeGetTile(x, y)]!!
try {
return tileNumberToNameMap[layerWall.unsafeGetTile(x, y)]!!
}
catch (e: NullPointerException) {
System.err.println("NPE for wall ${layerWall.unsafeGetTile(x, y)} in ($x, $y)")
throw e
}
}
/**
@@ -224,7 +237,7 @@ open class GameWorld : Disposable {
return tileNumberToNameMap[layerTerrain.unsafeGetTile(x, y)]!!
}
catch (e: NullPointerException) {
System.err.println("NPE for tilenum ${layerTerrain.unsafeGetTile(x, y)}")
System.err.println("NPE for terrain ${layerTerrain.unsafeGetTile(x, y)} in ($x, $y)")
throw e
}
}
@@ -597,7 +610,7 @@ open class GameWorld : Disposable {
else -> throw IllegalArgumentException("Unsupported fluid type: $type")
}
data class FluidInfo(val type: FluidType, val amount: Float) {
data class FluidInfo(val type: FluidType = Fluid.NULL, val amount: Float = 0f) {
/** test if this fluid should be considered as one */
fun isFluid() = type != Fluid.NULL && amount >= WorldSimulator.FLUID_MIN_MASS
fun getProp() = BlockCodex[type]
@@ -611,8 +624,8 @@ open class GameWorld : Disposable {
* If the wire does not allow them (e.g. wire bridge, thicknet), connect top-bottom and left-right nodes.
*/
data class WiringNode(
val position: BlockAddress, // may seem redundant and it kinda is, but don't remove!
val wires: SortedArrayList<ItemID> // what could possibly go wrong bloating up the RAM footprint when it's practically infinite these days?
val position: BlockAddress = -1, // may seem redundant and it kinda is, but don't remove!
val wires: SortedArrayList<ItemID> = SortedArrayList<ItemID>() // what could possibly go wrong bloating up the RAM footprint when it's practically infinite these days?
) : Comparable<WiringNode> {
override fun compareTo(other: WiringNode): Int {
return (this.position - other.position).sign
@@ -620,8 +633,8 @@ open class GameWorld : Disposable {
}
data class WireRecvState(
var dist: Int, // how many tiles it took to traverse
var src: Point2i // xy position
var dist: Int = -1, // how many tiles it took to traverse
var src: Point2i = Point2i(0,0) // xy position
// to get the state, use the src to get the state of the source emitter directly, then use dist to apply attenuation
)

View File

@@ -12,8 +12,8 @@ import net.torvald.terrarum.blockproperties.Block
import net.torvald.terrarum.blockproperties.BlockPropUtil
import net.torvald.terrarum.gameactors.*
import net.torvald.terrarum.gameitem.ItemID
import net.torvald.terrarum.gameworld.GameWorld
import net.torvald.terrarum.modulebasegame.gameactors.ActorHumanoid
import net.torvald.terrarum.modulebasegame.gameworld.GameWorldExtension
import net.torvald.terrarum.gameworld.WorldTime
import net.torvald.terrarum.modulebasegame.ui.Notification
import net.torvald.terrarum.modulebasegame.ui.UIBuildingMakerBlockChooser
@@ -66,7 +66,7 @@ class BuildingMaker(batch: SpriteBatch) : IngameInstance(batch) {
private val timeNow = System.currentTimeMillis() / 1000
val gameWorld = GameWorldExtension(1, 1024, 256, timeNow, timeNow, 0)
val gameWorld = GameWorld(1, 1024, 256, timeNow, timeNow, 0)
init {
// ghetto world for building

View File

@@ -28,8 +28,8 @@ import net.torvald.terrarum.gameactors.WireActor
import net.torvald.terrarum.gameworld.GameWorld
import net.torvald.terrarum.modulebasegame.gameactors.*
import net.torvald.terrarum.modulebasegame.gameactors.physicssolver.CollisionSolver
import net.torvald.terrarum.modulebasegame.gameworld.GameWorldExtension
import net.torvald.terrarum.gameworld.WorldSimulator
import net.torvald.terrarum.modulebasegame.gameworld.GameEconomy
import net.torvald.terrarum.modulebasegame.ui.*
import net.torvald.terrarum.weather.WeatherMixer
import net.torvald.terrarum.modulebasegame.worldgenerator.RoguelikeRandomiser
@@ -209,7 +209,6 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
lateinit var gameLoadMode: GameLoadMode
lateinit var gameLoadInfoPayload: Any
lateinit var gameworld: GameWorldExtension
lateinit var theRealGamer: IngamePlayer
// get() = actorGamer as IngamePlayer
@@ -229,14 +228,14 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
GameLoadMode.LOAD_FROM -> enterLoadFromSave(gameLoadInfoPayload as GameSaveData)
}
IngameRenderer.setRenderedWorld(gameworld)
IngameRenderer.setRenderedWorld(world)
super.show() // gameInitialised = true
}
data class GameSaveData(
val world: GameWorldExtension,
val world: GameWorld,
val historicalFigureIDBucket: ArrayList<Int>,
val realGamePlayer: IngamePlayer,
val rogueS0: Long,
@@ -270,18 +269,7 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
printdbg(this, "loaded successfully.")
}
else {
AppLoader.getLoadScreen().addMessage("Loading world from save")
gameworld = gameSaveData.world
world = gameworld
historicalFigureIDBucket = gameSaveData.historicalFigureIDBucket
setTheRealGamerFirstTime(gameSaveData.realGamePlayer)
// set the randomisers right
RoguelikeRandomiser.loadFromSave(gameSaveData.rogueS0, gameSaveData.rogueS1)
WeatherMixer.loadFromSave(gameSaveData.weatherS0, gameSaveData.weatherS1)
TODO()
}
}
@@ -302,9 +290,9 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
// init map as chosen size
val timeNow = System.currentTimeMillis() / 1000
gameworld = GameWorldExtension(1, worldParams.width, worldParams.height, timeNow, timeNow, 0) // new game, so the creation time is right now
gameworldIndices.add(gameworld.worldIndex)
world = gameworld
world = GameWorld(1, worldParams.width, worldParams.height, timeNow, timeNow, 0) // new game, so the creation time is right now
gameworldIndices.add(world.worldIndex)
world.extraFields["basegame.economy"] = GameEconomy()
// generate terrain for the map
//WorldGenerator.attachMap(world)
@@ -558,7 +546,7 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
* Ingame (world) related updates; UI update must go to renderGame()
*/
protected fun updateGame(delta: Float) {
val world = this.world as GameWorldExtension
val world = this.world
worldWidth = world.width.toDouble() * TILE_SIZE
particlesActive = 0
@@ -652,7 +640,7 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
private fun renderGame() {
Gdx.graphics.setTitle(getCanonicalTitle())
WorldCamera.update(gameworld, actorNowPlaying)
WorldCamera.update(world, actorNowPlaying)
measureDebugTime("Ingame.FilterVisibleActors") {
filterVisibleActors()

View File

@@ -37,22 +37,26 @@ object ExportMeta : ConsoleCommand {
object ExportWorld : ConsoleCommand {
override fun execute(args: Array<String>) {
try {
val world = Terrarum.ingame!!.world
val str = WriteWorld(Terrarum.ingame!! as TerrarumIngame).invoke()
val writer = java.io.FileWriter(AppLoader.defaultDir + "/Exports/world${world.worldIndex}.json", false)
writer.write(str)
writer.close()
Echo("Exportworld: exported to world${world.worldIndex}.json")
if (args.size == 2) {
try {
val str = WriteWorld(Terrarum.ingame!! as TerrarumIngame).invoke()
val writer = java.io.FileWriter(AppLoader.defaultDir + "/Exports/${args[1]}", false)
writer.write(str)
writer.close()
Echo("Exportworld: exported to ${args[1]}")
}
catch (e: IOException) {
Echo("Exportworld: IOException raised.")
e.printStackTrace()
}
}
catch (e: IOException) {
Echo("Exportworld: IOException raised.")
e.printStackTrace()
else {
ImportWorld.printUsage()
}
}
override fun printUsage() {
Echo("Usage: Exportworld")
Echo("Usage: Exportworld filename.json")
}
}

View File

@@ -3,7 +3,6 @@ package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.modulebasegame.gameworld.GameWorldExtension
/**
* Created by minjaesong on 2016-03-20.
@@ -11,7 +10,7 @@ import net.torvald.terrarum.modulebasegame.gameworld.GameWorldExtension
internal object GetTime : ConsoleCommand {
override fun execute(args: Array<String>) {
val worldTime = (Terrarum.ingame!!.world as GameWorldExtension).worldTime
val worldTime = (Terrarum.ingame!!.world).worldTime
Echo(worldTime.getFormattedTime())
}

View File

@@ -1,10 +1,7 @@
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.TerrarumAppConfiguration.TILE_SIZED
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.modulebasegame.gameworld.GameWorldExtension
import java.io.File
/**

View File

@@ -0,0 +1,36 @@
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.AppLoader
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.modulebasegame.TerrarumIngame
import net.torvald.terrarum.serialise.ReadWorld
import net.torvald.terrarum.serialise.WriteMeta
import java.io.IOException
/**
* Created by minjaesong on 2021-08-25.
*/
object ImportWorld : ConsoleCommand {
override fun execute(args: Array<String>) {
if (args.size == 2) {
try {
val reader = java.io.FileReader(AppLoader.defaultDir + "/Exports/${args[1]}")
ReadWorld(Terrarum.ingame!! as TerrarumIngame).invoke(reader)
Echo("Importworld: imported a world from ${args[1]}")
}
catch (e: IOException) {
Echo("Importworld: IOException raised.")
e.printStackTrace()
}
}
else {
printUsage()
}
}
override fun printUsage() {
Echo("Usage: Importworld filename.json")
}
}

View File

@@ -11,7 +11,7 @@ import net.torvald.terrarum.modulebasegame.TerrarumIngame
*/
internal object SetTime : ConsoleCommand {
override fun execute(args: Array<String>) {
val world = (Terrarum.ingame!! as TerrarumIngame).gameworld
val world = (Terrarum.ingame!! as TerrarumIngame).world
if (args.size == 2) {

View File

@@ -13,7 +13,7 @@ internal object SetTimeDelta : ConsoleCommand {
val HARD_LIMIT = 60
override fun execute(args: Array<String>) {
val world = (Terrarum.ingame!! as TerrarumIngame).gameworld
val world = (Terrarum.ingame!! as TerrarumIngame).world
if (args.size == 2) {

View File

@@ -11,7 +11,7 @@ import net.torvald.terrarum.modulebasegame.TerrarumIngame
object PlayerBuilder {
operator fun invoke(): Actor {
val world = (Terrarum.ingame!! as TerrarumIngame).gameworld
val world = (Terrarum.ingame!! as TerrarumIngame).world
val p: Actor = IngamePlayer("lol", "lol_glow", world.worldTime.TIME_T)
InjectCreatureRaw(p.actorValue, "basegame", "CreatureHuman.json")

View File

@@ -1,48 +0,0 @@
package net.torvald.terrarum.modulebasegame.gameworld
import com.badlogic.gdx.utils.Json
import com.badlogic.gdx.utils.JsonWriter
import net.torvald.terrarum.gameworld.GameWorld
import net.torvald.terrarum.gameworld.WorldTime
/**
* Created by minjaesong on 2018-07-03.
*/
class GameWorldExtension : GameWorld {
constructor(worldIndex: Int, width: Int, height: Int, creationTIME_T: Long, lastPlayTIME_T: Long, totalPlayTime: Int) : super(worldIndex, width, height, creationTIME_T, lastPlayTIME_T, totalPlayTime)
//internal constructor(worldIndex: Int, layerData: ReadLayerDataZip.LayerData, creationTIME_T: Long, lastPlayTIME_T: Long, totalPlayTime: Int) : super(worldIndex, layerData, creationTIME_T, lastPlayTIME_T, totalPlayTime)
var economy = GameEconomy()
internal set
// delegated properties //
/*val layerWall: MapLayer; get() = baseworld.layerWall
val layerTerrain: MapLayer; get() = baseworld.layerTerrain
val layerWire: MapLayer; get() = baseworld.layerWire
val layerWallLowBits: PairedMapLayer; get() = baseworld.layerWallLowBits
val layerTerrainLowBits: PairedMapLayer; get() = baseworld.layerTerrainLowBits
val layerHalfThermal: MapLayerHalfFloat; get() = baseworld.layerHalfThermal
var spawnX: Int; get() = baseworld.spawnX; set(v) { baseworld.spawnX = v }
var spawnY: Int; get() = baseworld.spawnY; set(v) { baseworld.spawnY = v }
val wallDamages: HashMap<BlockAddress, BlockDamage>; get() = baseworld.wallDamages
val terrainDamages: HashMap<BlockAddress, BlockDamage>; get() = baseworld.terrainDamages
var globalLight: Color; get() = baseworld.globalLight; set(v) { baseworld.globalLight = v }
var averageTemperature: Float; get() = baseworld.averageTemperature; set(v) { baseworld.averageTemperature = v }
var generatorSeed: Long; get() = baseworld.generatorSeed; set(v) { baseworld.generatorSeed = v }
val terrainArray: ByteArray; get() = baseworld.terrainArray
val wallArray: ByteArray; get() = baseworld.wallArray
val wireArray: ByteArray; get() = baseworld.wireArray
val damageDataArray: ByteArray; get() = baseworld.damageDataArray*/
init {
}
override fun getJsonFields(): List<String> {
return super.getJsonFields() + arrayListOf(
""""basegame.economy": ${Json(JsonWriter.OutputType.json).toJson(economy)}"""
)
}
}

View File

@@ -6,7 +6,6 @@ import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import net.torvald.terrarum.*
import net.torvald.terrarum.modulebasegame.gameactors.ActorHumanoid
import net.torvald.terrarum.modulebasegame.gameworld.GameWorldExtension
import net.torvald.terrarum.gameworld.WorldTime
import net.torvald.terrarum.modulebasegame.imagefont.WatchFont
import net.torvald.terrarum.ui.UICanvas
@@ -39,7 +38,7 @@ class UITierOneWatch() : UICanvas() {
//get() = if (ELon) lcdLitColELon else lcdLitColELoff
private val worldTime: WorldTime
get() = (Terrarum.ingame!!.world as GameWorldExtension).worldTime
get() = Terrarum.ingame!!.world.worldTime
override fun updateUI(delta: Float) {

View File

@@ -1,28 +1,28 @@
package net.torvald.terrarum.serialise
import com.badlogic.gdx.utils.Json
import com.badlogic.gdx.utils.JsonValue
import net.torvald.terrarum.gameworld.GameWorld
import net.torvald.terrarum.modulebasegame.TerrarumIngame
import net.torvald.terrarum.modulebasegame.gameworld.GameEconomy
import net.torvald.terrarum.modulebasegame.gameworld.GameWorldExtension
import java.io.InputStream
import java.io.Reader
/**
* Created by minjaesong on 2021-08-25.
*/
open class ReadWorld(val ingame: TerrarumIngame) {
open fun invoke(worldIndex: Int, metadata: JsonValue, worlddata: JsonValue) {
val json = Json()
val world = GameWorldExtension(
worldIndex,
worlddata.getInt("width"),
worlddata.getInt("height"),
metadata.getLong("creation_t"),
metadata.getLong("lastplay_t"),
metadata.getInt("playtime_t")
)
open fun invoke(worldDataStream: InputStream) {
postRead(WriteWorld.jsoner.fromJson(GameWorld::class.java, worldDataStream))
}
//world.economy = json.fromJson(GameEconomy::class.java, worlddata.get("basegame.economy").)
open fun invoke(worldDataStream: Reader) {
postRead(WriteWorld.jsoner.fromJson(GameWorld::class.java, worldDataStream))
}
private fun postRead(world: GameWorld) {
world.postLoad()
ingame.world = world
//ingame.actorNowPlaying?.setPosition(3.0, 3.0)
}
}

View File

@@ -14,7 +14,6 @@ import net.torvald.terrarum.gameworld.GameWorld
import net.torvald.terrarum.imagefont.TinyAlphNum
import net.torvald.terrarum.modulebasegame.IngameRenderer
import net.torvald.terrarum.modulebasegame.TerrarumIngame
import net.torvald.terrarum.modulebasegame.gameworld.GameWorldExtension
import net.torvald.terrarum.modulebasegame.ui.ItemSlotImageFactory
import net.torvald.terrarum.worlddrawer.CreateTileAtlas
import net.torvald.terrarum.worlddrawer.LightmapRenderer
@@ -41,8 +40,6 @@ class BasicDebugInfoWindow : UICanvas() {
private val world: GameWorld?
get() = Terrarum.ingame?.world
private val world2: GameWorldExtension?
get() = Terrarum.ingame?.world as? GameWorldExtension?
override fun updateUI(delta: Float) {
@@ -188,8 +185,8 @@ class BasicDebugInfoWindow : UICanvas() {
//printLineColumn(batch, 2, 2, "Env colour temp $ccG" + FeaturesDrawer.colTemp)
if (world != null) {
printLineColumn(batch, 2, 5, "Time $ccG${world2?.worldTime?.todaySeconds.toString().padStart(5, '0')}" +
" (${world2?.worldTime?.getFormattedTime()})")
printLineColumn(batch, 2, 5, "Time $ccG${world?.worldTime?.todaySeconds.toString().padStart(5, '0')}" +
" (${world?.worldTime?.getFormattedTime()})")
}
if (player != null) {

View File

@@ -17,7 +17,6 @@ import net.torvald.terrarum.modulebasegame.IngameRenderer
import net.torvald.terrarum.modulebasegame.RNGConsumer
import net.torvald.terrarum.modulebasegame.TerrarumIngame
import net.torvald.terrarum.modulebasegame.gameactors.ParticleMegaRain
import net.torvald.terrarum.modulebasegame.gameworld.GameWorldExtension
import net.torvald.terrarum.utils.JsonFetcher
import net.torvald.terrarum.worlddrawer.WorldCamera
import java.io.File
@@ -88,7 +87,7 @@ internal object WeatherMixer : RNGConsumer {
/**
* Part of Ingame update
*/
fun update(delta: Float, player: ActorWithBody?, world: GameWorldExtension) {
fun update(delta: Float, player: ActorWithBody?, world: GameWorld) {
if (player == null) return
currentWeather = weatherList[WEATHER_GENERIC]!![0]

View File

@@ -13,7 +13,6 @@ import net.torvald.terrarum.blockproperties.BlockCodex
import net.torvald.terrarum.gameitem.ItemID
import net.torvald.terrarum.gameworld.GameWorld
import net.torvald.terrarum.gameworld.fmod
import net.torvald.terrarum.modulebasegame.gameworld.GameWorldExtension
import net.torvald.terrarum.gameworld.WorldSimulator
import net.torvald.terrarum.gameworld.WorldTime
import net.torvald.terrarumsansbitmap.gdx.TextureRegionPack
@@ -182,7 +181,7 @@ internal object BlocksDrawer {
internal fun renderData() {
try {
drawTIME_T = (world as GameWorldExtension).worldTime.TIME_T - (WorldTime.DAY_LENGTH * 15) // offset by -15 days
drawTIME_T = world.worldTime.TIME_T - (WorldTime.DAY_LENGTH * 15) // offset by -15 days
val seasonalMonth = (drawTIME_T.div(WorldTime.DAY_LENGTH) fmod WorldTime.YEAR_DAYS.toLong()).toInt() / WorldTime.MONTH_LENGTH + 1
tilesTerrain = weatherTerrains[seasonalMonth - 1]
@@ -620,7 +619,7 @@ internal object BlocksDrawer {
shader.setUniformf("tilesInAtlas", tileAtlas.horizontalCount.toFloat(), tileAtlas.verticalCount.toFloat()) //depends on the tile atlas
shader.setUniformf("atlasTexSize", tileAtlas.texture.width.toFloat(), tileAtlas.texture.height.toFloat()) //depends on the tile atlas
// set the blend value as world's time progresses, in linear fashion
shader.setUniformf("tilesBlend", if (world is GameWorldExtension && (mode == TERRAIN || mode == WALL))
shader.setUniformf("tilesBlend", if (mode == TERRAIN || mode == WALL)
drawTIME_T.fmod(SECONDS_IN_MONTH) / SECONDS_IN_MONTH.toFloat()
else
0f

View File

@@ -9,13 +9,13 @@ import java.util.function.Consumer
*
* Created by minjaesong on 2019-03-12.
*/
class SortedArrayList<T: Comparable<T>>(initialSize: Int = 10) : List<T> {
class SortedArrayList<T: Comparable<T>>(initialSize: Int = 10) : MutableCollection<T> {
val arrayList = ArrayList<T>(initialSize)
/**
*/
fun add(elem: Comparable<T>) {
override fun add(element: T): Boolean {
// don't append-at-tail-and-sort; just insert at right index
// this is a modified binary search to search the right "spot" where the insert elem fits
ReentrantLock().lock {
@@ -25,29 +25,44 @@ class SortedArrayList<T: Comparable<T>>(initialSize: Int = 10) : List<T> {
while (low < high) {
val mid = (low + high).ushr(1)
if ((arrayList[mid] as Comparable<T>).compareTo(elem as T) > 0)
if ((arrayList[mid] as Comparable<T>) > element)
high = mid
else
low = mid + 1
}
arrayList.add(low, elem as T)
arrayList.add(low, element)
}
return true
}
override fun addAll(elements: Collection<T>): Boolean {
ReentrantLock().lock {
arrayList.addAll(elements)
arrayList.sort()
}
return true
}
override val size: Int
get() = arrayList.size
override inline fun isEmpty() = arrayList.isEmpty()
override inline fun lastIndexOf(element: T) = arrayList.lastIndexOf(element)
inline fun lastIndexOf(element: T) = arrayList.lastIndexOf(element)
inline fun removeAt(index: Int) = arrayList.removeAt(index)
inline fun remove(element: T) = arrayList.remove(element) // don't mess up with your own half-assed implementation
override inline fun remove(element: T) = arrayList.remove(element) // don't mess up with your own half-assed implementation
override inline fun removeAll(elements: Collection<T>) = arrayList.removeAll(elements)
inline fun removeLast() = arrayList.removeAt(arrayList.size - 1)
override operator inline fun get(index: Int) = arrayList[index]
override fun retainAll(elements: Collection<T>) = arrayList.retainAll(elements)
operator inline fun get(index: Int) = arrayList[index]
fun getOrNull(index: Int?) = if (index == null) null else get(index)
override fun indexOf(element: T): Int = searchForIndex(element.hashCode()) { element.hashCode() } ?: -1
fun indexOf(element: T): Int = searchForIndex(element.hashCode()) { element.hashCode() } ?: -1
/**
* Searches for the element. Null if the element was not found
@@ -109,9 +124,9 @@ class SortedArrayList<T: Comparable<T>>(initialSize: Int = 10) : List<T> {
fun <R: Comparable<R>> searchFor(searchQuery: R, searchHow: (T) -> R = { it as R }): T? = getOrNull(searchForIndex(searchQuery, searchHow))
override inline fun iterator() = arrayList.iterator()
override inline fun listIterator() = arrayList.listIterator()
override inline fun listIterator(index: Int) = arrayList.listIterator(index)
override inline fun subList(fromIndex: Int, toIndex: Int) = arrayList.subList(fromIndex, toIndex)
inline fun listIterator() = arrayList.listIterator()
inline fun listIterator(index: Int) = arrayList.listIterator(index)
inline fun subList(fromIndex: Int, toIndex: Int) = arrayList.subList(fromIndex, toIndex)
override inline fun forEach(action: Consumer<in T>?) = arrayList.forEach(action)
inline fun forEachIndexed(action: (Int, T) -> Unit) = arrayList.forEachIndexed(action)
@@ -132,7 +147,7 @@ class SortedArrayList<T: Comparable<T>>(initialSize: Int = 10) : List<T> {
*/
fun toArrayList() = arrayList
fun clear() = arrayList.clear()
override fun clear() = arrayList.clear()
}
fun <T: Comparable<T>> sortedArrayListOf(vararg elements: T): SortedArrayList<T> {