fixture will drop itself when mined

This commit is contained in:
minjaesong
2022-01-21 16:35:37 +09:00
parent 75afcaede3
commit fa68a1c377
15 changed files with 92 additions and 84 deletions

View File

@@ -126,6 +126,9 @@ open class IngameInstance(val batch: SpriteBatch, val isMultiplayer: Boolean = f
val actorContainerActive = SortedArrayList<Actor>(ACTORCONTAINER_INITIAL_SIZE)
val actorContainerInactive = SortedArrayList<Actor>(ACTORCONTAINER_INITIAL_SIZE)
val actorAdditionQueue = ArrayList<Actor>()
val actorRemovalQueue = ArrayList<Actor>()
/**
* ## BIG NOTE: Calculated actor distance is the **Euclidean distance SQUARED**
*
@@ -158,7 +161,7 @@ open class IngameInstance(val batch: SpriteBatch, val isMultiplayer: Boolean = f
// add blockmarking_actor into the actorlist
(CommonResourcePool.get("blockmarking_actor") as BlockMarkerActor).let {
it.isVisible = false // make sure the actor is invisible on new instance
try { addNewActor(it) } catch (e: ReferencedActorAlreadyExistsException) {}
if (actorContainerActive.searchFor(it.referenceID) { it.referenceID } != null) actorContainerActive.add(it)
}
gameInitialised = true
@@ -300,7 +303,7 @@ open class IngameInstance(val batch: SpriteBatch, val isMultiplayer: Boolean = f
//fun SortedArrayList<*>.binarySearch(actor: Actor) = this.toArrayList().binarySearch(actor.referenceID)
//fun SortedArrayList<*>.binarySearch(ID: Int) = this.toArrayList().binarySearch(ID)
open fun removeActor(ID: Int) = removeActor(getActorByID(ID))
open fun queueActorRemoval(ID: Int) = queueActorRemoval(getActorByID(ID))
/**
* get index of the actor and delete by the index.
* we can do this as the list is guaranteed to be sorted
@@ -309,13 +312,12 @@ open class IngameInstance(val batch: SpriteBatch, val isMultiplayer: Boolean = f
* Any values behind the index will be automatically pushed to front.
* This is how remove function of [java.util.ArrayList] is defined.
*/
open fun removeActor(actor: Actor?) {
open fun queueActorRemoval(actor: Actor?) {
if (actor == null) return
forceRemoveActor(actor)
actorRemovalQueue.add(actor)
}
open fun forceRemoveActor(actor: Actor) {
protected open fun forceRemoveActor(actor: Actor) {
arrayOf(actorContainerActive, actorContainerInactive).forEach { actorContainer ->
val indexToDelete = actorContainer.searchFor(actor.referenceID) { it.referenceID }
if (indexToDelete != null) {
@@ -325,20 +327,25 @@ open class IngameInstance(val batch: SpriteBatch, val isMultiplayer: Boolean = f
}
}
/**
* Check for duplicates, append actor and sort the list
*/
open fun addNewActor(actor: Actor?) {
protected open fun forceAddActor(actor: Actor?) {
if (actor == null) return
if (theGameHasActor(actor.referenceID)) {
throw ReferencedActorAlreadyExistsException(actor)
}
else {
actorContainerActive.add(actor)
actorAdditionQueue.add(actor)
}
}
/**
* Check for duplicates, append actor and sort the list
*/
open fun queueActorAddition(actor: Actor?) {
if (actor == null) return
actorAdditionQueue.add(actor)
}
fun isActive(ID: Int): Boolean =
if (actorContainerActive.size == 0)
false

View File

@@ -1736,7 +1736,7 @@ open class ActorWithBody : Actor {
assertPrinted = true
}
internal fun flagDespawn() {
internal open fun flagDespawn() {
flagDespawn = true
}

View File

@@ -223,7 +223,7 @@ class BuildingMaker(batch: SpriteBatch) : IngameInstance(batch) {
internal fun addBlockMarker(x: Int, y: Int) {
try {
val a = generateNewBlockMarkerVisible(x, y)
addNewActor(a)
queueActorAddition(a)
actorsRenderOverlay.add(a)
selection.add(Point2i(x, y))
}
@@ -233,7 +233,7 @@ class BuildingMaker(batch: SpriteBatch) : IngameInstance(batch) {
internal fun removeBlockMarker(x: Int, y: Int) {
try {
val a = getActorByID(blockPosToRefID(x, y))
removeActor(a)
queueActorAddition(a)
actorsRenderOverlay.remove(a)
selection.remove(Point2i(x, y))
}

View File

@@ -316,7 +316,7 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
try {
val actor = ReadActor(codices.disk, LoadSavegame.getFileReader(codices.disk, it.toLong()))
if (actor !is IngamePlayer) { // actor list should not contain IngamePlayers (see WriteWorld.preWrite) but just in case...
addNewActor(actor)
forceAddActor(actor)
}
}
catch (e: NullPointerException) {
@@ -329,7 +329,7 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
// assign new random referenceID for player
codices.player.referenceID = Terrarum.generateUniqueReferenceID(Actor.RenderOrder.MIDDLE)
addNewActor(codices.player)
forceAddActor(codices.player)
// overwrite player's props with world's for multiplayer
@@ -460,7 +460,7 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
actorNowPlaying = player
actorGamer = player
addNewActor(player)
forceAddActor(player)
}
@@ -767,12 +767,19 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
///////////////////////////
repossessActor()
// process actor addition requests
actorAdditionQueue.forEach { forceAddActor(it) }
actorAdditionQueue.clear()
// determine whether the inactive actor should be activated
wakeDormantActors()
// update NOW; allow one last update for the actors flagged to despawn
updateActors(delta)
// determine whether the actor should keep being activated or be dormant
killOrKnockdownActors()
// process actor removal requests
actorRemovalQueue.forEach { forceRemoveActor(it) }
actorRemovalQueue.clear()
// update particles
particlesContainer.forEach { if (!it.flagDespawn) particlesActive++; it.update(delta) }
// TODO thread pool(?)
CollisionSolver.process()
@@ -880,7 +887,7 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
private val maxRenderableWires = ReferencingRanges.ACTORS_WIRES.endInclusive - ReferencingRanges.ACTORS_WIRES.first + 1
private val wireActorsContainer = Array(maxRenderableWires) { WireActor(ReferencingRanges.ACTORS_WIRES.first + it).let {
addNewActor(it)
forceAddActor(it)
/*^let*/ it
} }
@@ -949,12 +956,9 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
}
internal fun changePossession(newActor: ActorHumanoid) {
if (!theGameHasActor(actorNowPlaying)) {
throw NoSuchActorWithRefException(newActor)
}
if (!theGameHasActor(actorNowPlaying)) { throw NoSuchActorWithRefException(newActor) }
actorNowPlaying = newActor
//WorldSimulator(actorNowPlaying, AppLoader.getSmoothDelta().toFloat())
}
internal fun changePossession(refid: Int) {
@@ -994,7 +998,7 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
val actorIndex = i
// kill actors flagged to despawn
if (actor.flagDespawn) {
removeActor(actor)
queueActorRemoval(actor)
actorContainerSize -= 1
i-- // array removed 1 elem, so we also decrement counter by 1
}
@@ -1111,23 +1115,6 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
}
}
override fun removeActor(ID: Int) = removeActor(getActorByID(ID))
/**
* get index of the actor and delete by the index.
* we can do this as the list is guaranteed to be sorted
* and only contains unique values.
*
* Any values behind the index will be automatically pushed to front.
* This is how remove function of [java.util.ArrayList] is defined.
*/
override fun removeActor(actor: Actor?) {
if (actor == null) return
// if (actor.referenceID == actorGamer.referenceID || actor.referenceID == 0x51621D) // do not delete this magic
// throw ProtectedActorRemovalException("Player")
forceRemoveActor(actor)
}
override fun forceRemoveActor(actor: Actor) {
arrayOf(actorContainerActive, actorContainerInactive).forEach { actorContainer ->
@@ -1173,18 +1160,13 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
/**
* Check for duplicates, append actor and sort the list
*/
override fun addNewActor(actor: Actor?) {
override fun forceAddActor(actor: Actor?) {
if (actor == null) return
if (theGameHasActor(actor.referenceID)) {
throw ReferencedActorAlreadyExistsException(actor)
}
else {
if (actor.referenceID !in ReferencingRanges.ACTORS_WIRES && actor.referenceID !in ReferencingRanges.ACTORS_WIRES_HELPER) {
// printdbg(this, "Adding actor $actor")
// printStackTrace(this)
}
actorContainerActive.add(actor)
if (actor is ActorWithBody) actorToRenderQueue(actor).add(actor)
}
@@ -1250,7 +1232,7 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
}
// pickup a fixture
if (fixturesUnderHand.size > 0) {
if (fixturesUnderHand.size > 0 && fixturesUnderHand[0].canBeDespawned) {
val fixture = fixturesUnderHand[0]
val fixtureItem = ItemCodex.fixtureToItemID(fixture)
printdbg(this, "Fixture pickup: ${fixture.javaClass.canonicalName} -> $fixtureItem")

View File

@@ -16,7 +16,7 @@ internal object KillActor : ConsoleCommand {
if (args.size == 2) {
try {
val actorid = args[1].toInt()
INGAME.removeActor(actorid)
INGAME.queueActorRemoval(actorid)
}
catch (e: NumberFormatException) {
EchoError("Wrong number input.")

View File

@@ -27,7 +27,7 @@ internal object SpawnPhysTestBall : ConsoleCommand {
ball.elasticity = elasticity
ball.applyForce(Vector2(xvel, yvel))
INGAME.addNewActor(ball)
INGAME.queueActorAddition(ball)
}
else if (args.size == 2) {
val elasticity = args[1].toDouble()
@@ -36,7 +36,7 @@ internal object SpawnPhysTestBall : ConsoleCommand {
ball.setPosition(mouseX, mouseY)
ball.elasticity = elasticity
INGAME.addNewActor(ball)
INGAME.queueActorAddition(ball)
}
else {
printUsage()

View File

@@ -17,7 +17,7 @@ internal object SpawnPhysTestLunarLander : ConsoleCommand {
lander.setPosition(mouseX, mouseY)
INGAME.addNewActor(lander)
INGAME.queueActorAddition(lander)
}
override fun printUsage() {

View File

@@ -17,7 +17,7 @@ internal object SpawnTapestry : ConsoleCommand {
}
val tapestry = DecodeTapestry(File(args[1]))
INGAME.addNewActor(tapestry)
INGAME.queueActorAddition(tapestry)
}
override fun printUsage() {

View File

@@ -16,7 +16,7 @@ internal object SpawnTikiTorch : ConsoleCommand {
val torch = FixtureTikiTorch()
torch.setPosition(Terrarum.mouseX, Terrarum.mouseY)
INGAME.addNewActor(torch)
INGAME.queueActorAddition(torch)
}
override fun printUsage() {

View File

@@ -36,7 +36,11 @@ open class DroppedItem : ActorWithBody {
fun canBePickedUp() = timeSinceSpawned > NO_PICKUP_TIME && !flagDespawn
constructor(itemID: ItemID, topLeftX: Int, topLeftY: Int) : super(RenderOrder.MIDTOP, PhysProperties.PHYSICS_OBJECT) {
/**
* @param topLeftX world-wise coord
* @param topLeftY world-wise coord
*/
constructor(itemID: ItemID, topLeftX: Double, topLeftY: Double) : super(RenderOrder.MIDTOP, PhysProperties.PHYSICS_OBJECT) {
this.itemID = itemID
if (itemID.startsWith("actor@"))

View File

@@ -66,7 +66,7 @@ open class FixtureBase : ActorWithBody, CuedByTerrainChange {
private set
fun forEachBlockbox(action: (Int, Int) -> Unit) {
worldBlockPos!!.let { (posX, posY) ->
worldBlockPos?.let { (posX, posY) ->
for (y in posY until posY + blockBox.height) {
for (x in posX until posX + blockBox.width) {
action(x, y)
@@ -76,20 +76,20 @@ open class FixtureBase : ActorWithBody, CuedByTerrainChange {
}
override fun updateForTerrainChange(cue: IngameInstance.BlockChangeQueueItem) {
fillFillerBlock()
}
private fun fillFillerBlock(bypassEvent: Boolean = false) {
private fun fillFillerBlock() {
forEachBlockbox { x, y ->
//printdbg(this, "fillerblock ${blockBox.collisionType} at ($x, $y)")
if (blockBox.collisionType == BlockBox.ALLOW_MOVE_DOWN) {
// if the collision type is allow_move_down, only the top surface tile should be "the platform"
// lower part must not have such property (think of the table!)
// TODO does this ACTUALLY work ?!
world!!.setTileTerrain(x, y, if (y == worldBlockPos!!.y) BlockBox.ALLOW_MOVE_DOWN else BlockBox.NO_COLLISION, bypassEvent)
world!!.setTileTerrain(x, y, if (y == worldBlockPos!!.y) BlockBox.ALLOW_MOVE_DOWN else BlockBox.NO_COLLISION, true)
}
else
world!!.setTileTerrain(x, y, blockBox.collisionType, bypassEvent)
world!!.setTileTerrain(x, y, blockBox.collisionType, true)
}
}
@@ -144,38 +144,45 @@ open class FixtureBase : ActorWithBody, CuedByTerrainChange {
this.hitbox.setFromWidthHeight(posX * TILE_SIZED, posY * TILE_SIZED, blockBox.width * TILE_SIZED, blockBox.height * TILE_SIZED)
// actually add this actor into the world
INGAME.addNewActor(this)
INGAME.queueActorAddition(this)
return true
}
val canBeDespawned: Boolean get() = inventory?.isEmpty() ?: true
/**
* Removes this instance of the fixture from the world
*/
open fun despawn() {
printdbg(this, "despawn ${nameFun()}")
if (canBeDespawned) {
printdbg(this, "despawn ${nameFun()}")
// remove filler block
forEachBlockbox { x, y ->
world!!.setTileTerrain(x, y, Block.AIR, true)
// remove filler block
forEachBlockbox { x, y ->
world!!.setTileTerrain(x, y, Block.AIR, true)
}
worldBlockPos = null
mainUI?.dispose()
this.isVisible = false
if (this is Electric) {
wireEmitterTypes.clear()
wireEmission.clear()
wireConsumption.clear()
}
val drop = ItemCodex.fixtureToItemID(this)
INGAME.queueActorAddition(DroppedItem(drop, hitbox.startX, hitbox.startY - 1.0))
}
worldBlockPos = null
mainUI?.dispose()
this.isVisible = false
if (this is Electric) {
wireEmitterTypes.clear()
wireEmission.clear()
wireConsumption.clear()
else {
printdbg(this, "cannot despawn a fixture with non-empty inventory")
}
// TODO drop self as an item (instance of DroppedItem)
}
override fun update(delta: Float) {
// if not flagged to despawn and not actually despawned (which sets worldBlockPos as null), always fill up fillerBlock
if (!flagDespawn && worldBlockPos != null) {
@@ -187,11 +194,15 @@ open class FixtureBase : ActorWithBody, CuedByTerrainChange {
}
}
if (flagDespawn) despawn()
if (!canBeDespawned) flagDespawn = false
else if (flagDespawn) despawn()
// actual actor removal is performed by the TerrarumIngame.killOrKnockdownActors
super.update(delta)
}
override fun flagDespawn() {
if (canBeDespawned) flagDespawn = true
}
}
interface CuedByTerrainChange {

View File

@@ -34,7 +34,10 @@ open class FixtureInventory() {
*/
val itemList = ArrayList<InventoryPair>()
var wallet = BigInteger("0") // unified currency for whole civs; Dwarf Fortress approach seems too complicated
fun isEmpty() = getTotalCount() == 0
fun isNotEmpty() = getTotalCount() > 0
open fun add(itemID: ItemID, count: Int = 1) {
if (ItemCodex[itemID] == null)
throw NullPointerException("Item not found: $itemID")
@@ -136,12 +139,12 @@ open class FixtureInventory() {
else
getTotalCount().toDouble()
fun getTotalWeight(): Double = itemList.map { ItemCodex[it.itm]!!.mass * it.qty }.sum()
fun getTotalWeight(): Double = itemList.sumOf { ItemCodex[it.itm]!!.mass * it.qty }
/**
* Real amount
*/
fun getTotalCount(): Int = itemList.map { it.qty }.sum()
fun getTotalCount(): Int = itemList.sumOf { it.qty }
/**
* Unique amount, multiple items are calculated as one

View File

@@ -54,7 +54,7 @@ open class HumanoidNPC : ActorHumanoid, AIControlled, CanBeAnItem {
try {
// place the actor to the world
this@HumanoidNPC.setPosition(Terrarum.mouseX, Terrarum.mouseY)
INGAME.addNewActor(this@HumanoidNPC)
INGAME.queueActorAddition(this@HumanoidNPC)
// successful
return true
}

View File

@@ -84,7 +84,7 @@ object PickaxeCore {
if (Math.random() < dropProbability) {
val drop = BlockCodex[tileBroken].drop
if (drop.isNotBlank()) {
INGAME.addNewActor(DroppedItem(drop, x * TILE_SIZE, y * TILE_SIZE))
INGAME.queueActorAddition(DroppedItem(drop, x * TILE_SIZED, y * TILE_SIZED))
}
}
}

View File

@@ -5,6 +5,7 @@ import net.torvald.terrarum.CommonResourcePool
import net.torvald.terrarum.Point2i
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.TerrarumAppConfiguration.TILE_SIZE
import net.torvald.terrarum.TerrarumAppConfiguration.TILE_SIZED
import net.torvald.terrarum.gameactors.ActorWithBody
import net.torvald.terrarum.gameitems.GameItem
import net.torvald.terrarum.gameitems.ItemID
@@ -43,7 +44,7 @@ class WireCutterAll(originalID: ItemID) : GameItem(originalID) {
wires?.forEach {
ingame.world.removeTileWire(mouseTile.x, mouseTile.y, it, false)
ingame.addNewActor(DroppedItem(it, mouseTile.x * TILE_SIZE, mouseTile.y * TILE_SIZE))
ingame.queueActorAddition(DroppedItem(it, mouseTile.x * TILE_SIZED, mouseTile.y * TILE_SIZED))
} ?: return@mouseInInteractableRange false
true