Files
spellforge/scripts/autoloads/spell_context_pool.gd
T
2026-07-20 10:56:52 +08:00

55 lines
1.6 KiB
GDScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
## SpellContextPool — SpellContext 对象池(Autoload: SpellContextPool
## 权威来源:implementation_plan.md §2.1、S1 验收 P-S1-04
extends Node
const POOL_SIZE: int = 32 # P-S1-04: pool size 不超过 32
var _pool: Array = [] # Array[SpellContext]
var _in_use: PackedByteArray = PackedByteArray()
var _slots: Array = [] # Array[SpellContext] 固定槽位
func _ready() -> void:
_slots.resize(POOL_SIZE)
_in_use.resize(POOL_SIZE)
for i in POOL_SIZE:
_slots[i] = SpellContext.new()
_in_use[i] = 0
_pool.append(i) # 空闲 ID 表
## 取出一个 SpellContext。若 has_persistent_memory=true 则保留 registers
func acquire(caster_id: int, has_persistent_memory: bool = false) -> SpellContext:
if _pool.is_empty():
push_warning("SpellContextPool: 池已耗尽,动态创建 SpellContext(建议上调 POOL_SIZE=%d" % POOL_SIZE)
var ctx_dyn := SpellContext.new()
ctx_dyn.caster_id = caster_id
if not has_persistent_memory:
ctx_dyn.clear_registers()
return ctx_dyn
var slot_id: int = _pool[_pool.size() - 1]
_pool.resize(_pool.size() - 1)
var ctx: SpellContext = _slots[slot_id]
_in_use[slot_id] = int(1)
ctx.reset()
ctx.caster_id = caster_id
if not has_persistent_memory:
ctx.clear_registers()
return ctx
func release(ctx: SpellContext) -> void:
for i in _slots.size():
if _slots[i] == ctx:
if _in_use[i] != 0:
_in_use[i] = 0
_pool.append(i)
return
# 动态分配的(池已耗尽时)直接丢弃
func get_available_count() -> int:
return _pool.size()
func reset() -> void:
_pool.clear()
for i in _slots.size():
_in_use[i] = 0
_pool.append(i)