Documentation
¶
Index ¶
- Constants
- Variables
- func BiomeDefinitions() ([]protocol.BiomeDefinition, []string)
- func BlockHash(b Block) uint64
- func BlockRuntimeID(b Block) uint32
- func Call[T any](ctx context.Context, w *World, f func(tx *Tx) (T, error)) (T, error)
- func CallEntity[T any](ctx context.Context, h *EntityHandle, f func(tx *Tx, e Entity) (T, error)) (T, error)
- func CallRef[T any, E Entity](ctx context.Context, ref EntityRef[E], f func(tx *Tx, e E) (T, error)) (T, error)
- func ClampRedstonePower(power int) int
- func CustomBlocks() map[string]CustomBlock
- func DifficultyID(diff Difficulty) (int, bool)
- func DimensionID(dim Dimension) (int, bool)
- func GameModeID(mode GameMode) (int, bool)
- func ItemRuntimeID(i Item) (rid int32, meta int16, ok bool)
- func RedstoneFullPowerConductor(pos cube.Pos, b Block, tx *Tx) bool
- func RegisterBiome(b Biome)
- func RegisterBlock(b Block)
- func RegisterItem(item Item)
- type ArrowSpawnConfig
- type BasicBlockRegistry
- func (br *BasicBlockRegistry) Air() Block
- func (br *BasicBlockRegistry) AirRuntimeID() uint32
- func (br *BasicBlockRegistry) BitSize() int
- func (br *BasicBlockRegistry) BlockByName(name string, properties map[string]any) (Block, bool)
- func (br *BasicBlockRegistry) BlockByRuntimeID(rid uint32) (Block, bool)
- func (br *BasicBlockRegistry) BlockByRuntimeIDOrAir(rid uint32) Block
- func (br *BasicBlockRegistry) BlockCount() int
- func (br *BasicBlockRegistry) BlockHash(b Block) uint64
- func (br *BasicBlockRegistry) BlockRuntimeID(b Block) uint32
- func (br *BasicBlockRegistry) Blocks() []Block
- func (br *BasicBlockRegistry) Clone() *BasicBlockRegistry
- func (br *BasicBlockRegistry) CustomBlocks() map[string]CustomBlock
- func (br *BasicBlockRegistry) FilteringBlock(rid uint32) uint8
- func (br *BasicBlockRegistry) Finalize()
- func (br *BasicBlockRegistry) HashToRuntimeID(hash uint32) (rid uint32, ok bool)
- func (br *BasicBlockRegistry) LightBlock(rid uint32) uint8
- func (br *BasicBlockRegistry) LiquidBlock(rid uint32) bool
- func (br *BasicBlockRegistry) LiquidDisplacingBlock(rid uint32) bool
- func (br *BasicBlockRegistry) NBTBlock(rid uint32) bool
- func (br *BasicBlockRegistry) RandomTickBlock(rid uint32) bool
- func (br *BasicBlockRegistry) RegisterBlock(b Block)
- func (br *BasicBlockRegistry) RegisterBlockState(s BlockState)
- func (br *BasicBlockRegistry) RuntimeIDToHash(runtimeID uint32) (hash uint32, ok bool)
- func (br *BasicBlockRegistry) RuntimeIDToState(runtimeID uint32) (name string, properties map[string]any, found bool)
- func (br *BasicBlockRegistry) StateToRuntimeID(name string, properties map[string]any) (runtimeID uint32, found bool)
- type Biome
- type Block
- type BlockAction
- type BlockModel
- type BlockRegistry
- type BlockSource
- type BlockState
- type ChunkPos
- type Column
- type Config
- type Context
- type CustomBlock
- type CustomBlockBuildable
- type CustomItem
- type DamageSource
- type Difficulty
- type Dimension
- type Entity
- type EntityAction
- type EntityAnimation
- func (a EntityAnimation) Controller() string
- func (a EntityAnimation) Name() string
- func (a EntityAnimation) NextState() string
- func (a EntityAnimation) StopCondition() string
- func (a EntityAnimation) WithController(controller string) EntityAnimation
- func (a EntityAnimation) WithNextState(state string) EntityAnimation
- func (a EntityAnimation) WithStopCondition(condition string) EntityAnimation
- type EntityConfig
- type EntityData
- type EntityHandle
- func (e *EntityHandle) Close() error
- func (e *EntityHandle) Closed() bool
- func (e *EntityHandle) Do(f func(tx *Tx, e Entity)) *Task
- func (e *EntityHandle) DoAfter(delay time.Duration, f func(tx *Tx, e Entity)) *Task
- func (e *EntityHandle) Entity(tx *Tx) (Entity, bool)
- func (e *EntityHandle) Type() EntityType
- func (e *EntityHandle) UUID() uuid.UUID
- type EntityRef
- type EntityRegistry
- type EntityRegistryConfig
- type EntitySpawnOpts
- type EntityType
- type GameMode
- type Generator
- type Handler
- type HealingSource
- type Item
- type Liquid
- type LiquidDisplacer
- type Loader
- type NBTer
- type NeighbourUpdateTicker
- type NopGenerator
- type NopHandler
- func (NopHandler) HandleBlockBurn(*Context, cube.Pos)
- func (NopHandler) HandleClose(*Tx)
- func (NopHandler) HandleCropTrample(*Context, cube.Pos)
- func (NopHandler) HandleEntityDespawn(*Tx, Entity)
- func (NopHandler) HandleEntitySpawn(*Tx, Entity)
- func (NopHandler) HandleExplosion(*Context, mgl64.Vec3, *[]Entity, *[]cube.Pos, *float64, *bool)
- func (NopHandler) HandleFireSpread(*Context, cube.Pos, cube.Pos)
- func (NopHandler) HandleLeavesDecay(*Context, cube.Pos)
- func (NopHandler) HandleLiquidDecay(*Context, cube.Pos, Liquid, Liquid)
- func (NopHandler) HandleLiquidFlow(*Context, cube.Pos, cube.Pos, Liquid, Block)
- func (NopHandler) HandleLiquidHarden(*Context, cube.Pos, Block, Block, Block)
- func (NopHandler) HandleRedstoneUpdate(*Context, RedstoneUpdate)
- func (NopHandler) HandleSound(*Context, Sound, mgl64.Vec3)
- type NopProvider
- func (NopProvider) Close() error
- func (NopProvider) LoadColumn(ChunkPos, Dimension) (*chunk.Column, error)
- func (NopProvider) LoadPlayerSpawnPosition(uuid.UUID) (cube.Pos, bool, error)
- func (NopProvider) SavePlayerSpawnPosition(uuid.UUID, cube.Pos) error
- func (NopProvider) SaveSettings(*Settings)
- func (n NopProvider) Settings() *Settings
- func (NopProvider) StoreColumn(ChunkPos, Dimension, *chunk.Column) error
- type NopViewer
- func (NopViewer) HideEntity(Entity)
- func (NopViewer) ViewBlockAction(cube.Pos, BlockAction)
- func (NopViewer) ViewBlockUpdate(cube.Pos, Block, int)
- func (NopViewer) ViewBrewingUpdate(time.Duration, time.Duration, int32, int32, int32, int32)
- func (NopViewer) ViewChunk(ChunkPos, Dimension, map[cube.Pos]Block, *chunk.Chunk)
- func (NopViewer) ViewEmote(Entity, uuid.UUID)
- func (NopViewer) ViewEntity(Entity)
- func (NopViewer) ViewEntityAction(Entity, EntityAction)
- func (NopViewer) ViewEntityAnimation(Entity, EntityAnimation)
- func (NopViewer) ViewEntityArmour(Entity)
- func (NopViewer) ViewEntityDisplacement(Entity, mgl64.Vec3, cube.Rotation, bool)
- func (NopViewer) ViewEntityGameMode(Entity)
- func (NopViewer) ViewEntityItems(Entity)
- func (NopViewer) ViewEntityMovement(Entity, mgl64.Vec3, cube.Rotation, bool)
- func (NopViewer) ViewEntityState(Entity)
- func (NopViewer) ViewEntityTeleport(Entity, mgl64.Vec3)
- func (NopViewer) ViewEntityVelocity(Entity, mgl64.Vec3)
- func (NopViewer) ViewEntityWake(Entity)
- func (NopViewer) ViewFurnaceUpdate(time.Duration, time.Duration, time.Duration, time.Duration, time.Duration, ...)
- func (NopViewer) ViewParticle(mgl64.Vec3, Particle)
- func (NopViewer) ViewSkin(Entity)
- func (NopViewer) ViewSound(mgl64.Vec3, Sound)
- func (NopViewer) ViewTime(int)
- func (NopViewer) ViewTimeCycle(bool)
- func (NopViewer) ViewWeather(bool, bool)
- func (NopViewer) ViewWorldSpawn(cube.Pos)
- type PanicError
- type Particle
- type Provider
- type RandomTicker
- type RedstoneNonConductive
- type RedstonePowerAction
- type RedstonePowerConsumer
- type RedstonePowerContextAction
- type RedstonePowerPostUpdater
- type RedstonePowerRelayer
- type RedstonePowerRelayerNeighbourer
- type RedstonePowerSource
- type RedstoneStrongPowerSource
- type RedstoneTorchTransaction
- func (t RedstoneTorchTransaction) BurnoutStatus() (burnedOut, recoverable bool)
- func (t RedstoneTorchTransaction) ClearBurnout()
- func (t RedstoneTorchTransaction) ConsumeSelfTriggered() bool
- func (t RedstoneTorchTransaction) MarkSelfTriggered()
- func (t RedstoneTorchTransaction) RecordTurnOff() (burnsOut bool)
- type RedstoneTransaction
- type RedstoneUpdate
- type RedstoneUpdateCause
- type RedstoneWeakBlockPowerer
- type ScheduledTicker
- type SetOpts
- type Settings
- type Sleeper
- type Sound
- type Structure
- type SubChunkPos
- type Task
- type TickerBlock
- type TickerEntity
- type Tx
- func (tx *Tx) AddEntity(e *EntityHandle) Entity
- func (tx *Tx) AddEntityAt(e *EntityHandle, pos mgl64.Vec3) Entity
- func (tx *Tx) AddParticle(pos mgl64.Vec3, p Particle)
- func (tx *Tx) Biome(pos cube.Pos) Biome
- func (tx *Tx) Block(pos cube.Pos) Block
- func (tx *Tx) BlockLoaded(pos cube.Pos) (Block, bool)
- func (tx *Tx) BlocksWithin(pos cube.Pos, radius int, blocks ...Block) iter.Seq[cube.Pos]
- func (tx *Tx) BroadcastSleepingIndicator()
- func (tx *Tx) BroadcastSleepingReminder(sleeper Sleeper)
- func (tx *Tx) BuildStructure(pos cube.Pos, s Structure)
- func (tx *Tx) CurrentTick() int64
- func (tx *Tx) Defer(f func(tx *Tx)) *Task
- func (tx *Tx) DeferErr(f func(tx *Tx) error) *Task
- func (tx *Tx) Entities() iter.Seq[Entity]
- func (tx *Tx) EntitiesWithin(box cube.BBox) iter.Seq[Entity]
- func (tx *Tx) Event() *Context
- func (tx *Tx) HighestBlock(x, z int) int
- func (tx *Tx) HighestLightBlocker(x, z int) int
- func (tx *Tx) Light(pos cube.Pos) uint8
- func (tx *Tx) Liquid(pos cube.Pos) (Liquid, bool)
- func (tx *Tx) PlayEntityAnimation(e Entity, a EntityAnimation)
- func (tx *Tx) PlaySound(pos mgl64.Vec3, s Sound)
- func (tx *Tx) Players() iter.Seq[Entity]
- func (tx *Tx) Raining() bool
- func (tx *Tx) RainingAt(pos cube.Pos) bool
- func (tx *Tx) Range() cube.Range
- func (tx *Tx) Redstone() RedstoneTransaction
- func (tx *Tx) RedstoneConductivePower(pos cube.Pos) int
- func (tx *Tx) RedstoneDirectPower(pos cube.Pos) int
- func (tx *Tx) RedstoneDirectPowerFrom(pos cube.Pos, face cube.Face) int
- func (tx *Tx) RedstonePower(pos cube.Pos) int
- func (tx *Tx) RedstonePowerFrom(pos cube.Pos, face cube.Face) int
- func (tx *Tx) RedstoneStrongPower(pos cube.Pos) int
- func (tx *Tx) RedstoneStrongPowerFrom(pos cube.Pos, face cube.Face) int
- func (tx *Tx) RemoveEntity(e Entity) *EntityHandle
- func (tx *Tx) ScheduleBlockUpdate(pos cube.Pos, b Block, delay time.Duration)
- func (tx *Tx) SetBiome(pos cube.Pos, b Biome)
- func (tx *Tx) SetBlock(pos cube.Pos, b Block, opts *SetOpts)
- func (tx *Tx) SetLiquid(pos cube.Pos, b Liquid)
- func (tx *Tx) SkyLight(pos cube.Pos) uint8
- func (tx *Tx) Sleepers() iter.Seq[Sleeper]
- func (tx *Tx) SnowingAt(pos cube.Pos) bool
- func (tx *Tx) Temperature(pos cube.Pos) float64
- func (tx *Tx) Thundering() bool
- func (tx *Tx) ThunderingAt(pos cube.Pos) bool
- func (tx *Tx) Viewers(pos mgl64.Vec3) []Viewer
- func (tx *Tx) World() *World
- type ViewLayer
- func (v *ViewLayer) Close() error
- func (v *ViewLayer) Entities() []*EntityHandle
- func (v *ViewLayer) NameTag(entity Entity) (string, bool)
- func (v *ViewLayer) Remove(entity Entity)
- func (v *ViewLayer) ScoreTag(entity Entity) (string, bool)
- func (v *ViewLayer) ViewNameTag(entity Entity, nameTag string)
- func (v *ViewLayer) ViewPublicNameTag(entity Entity)
- func (v *ViewLayer) ViewPublicScoreTag(entity Entity)
- func (v *ViewLayer) ViewScoreTag(entity Entity, scoreTag string)
- func (v *ViewLayer) ViewVisibility(entity Entity, level VisibilityLevel)
- func (v *ViewLayer) Visibility(entity Entity) VisibilityLevel
- type ViewLayerUpdater
- type Viewer
- type VisibilityLevel
- type World
- func (w *World) AdvanceTick()
- func (w *World) BlockRegistry() BlockRegistry
- func (w *World) Close() error
- func (w *World) DefaultGameMode() GameMode
- func (w *World) Difficulty() Difficulty
- func (w *World) Dimension() Dimension
- func (w *World) Do(f func(tx *Tx)) *Task
- func (w *World) DoAfter(delay time.Duration, f func(tx *Tx)) *Task
- func (w *World) EntityRegistry() EntityRegistry
- func (w *World) Handle(h Handler)
- func (w *World) Handler() Handler
- func (w *World) HighestLightBlocker(x, z int) int
- func (w *World) Name() string
- func (w *World) PlayerSpawn(id uuid.UUID) cube.Pos
- func (w *World) PortalDestination(dim Dimension) *World
- func (w *World) Range() cube.Range
- func (w *World) Save()
- func (w *World) SetDefaultGameMode(mode GameMode)
- func (w *World) SetDifficulty(d Difficulty)
- func (w *World) SetPlayerSpawn(id uuid.UUID, pos cube.Pos)
- func (w *World) SetRequiredSleepDuration(duration time.Duration)
- func (w *World) SetSpawn(pos cube.Pos)
- func (w *World) SetTickRange(v int)
- func (w *World) SetTime(new int)
- func (w *World) Spawn() cube.Pos
- func (w World) StartRaining(dur time.Duration)
- func (w World) StartThundering(dur time.Duration)
- func (w *World) StartTime()
- func (w World) StartWeatherCycle()
- func (w World) StopRaining()
- func (w World) StopThundering()
- func (w *World) StopTime()
- func (w World) StopWeatherCycle()
- func (w *World) Time() int
- func (w *World) TimeCycle() bool
Constants ¶
const ( TimeSleep = 12542 TimeWake = 23459 TimeSleepWithRain = 12010 TimeWakeWithRain = 23991 TimeFull = 24000 )
Time constants for sleep usage.
Variables ¶
var ( // DifficultyPeaceful prevents most hostile mobs from spawning and makes // players rapidly regenerate health and food. DifficultyPeaceful difficultyPeaceful // DifficultyEasy has mobs that deal less damage to players than normal and // starvation won't occur if a player has less than 5 hearts of health. DifficultyEasy difficultyEasy // DifficultyNormal has mobs that deal normal damage to players. Starvation // will occur until the player is down to a single heart. DifficultyNormal difficultyNormal // DifficultyHard has mobs that deal above average damage to players. // Starvation will kill players with too little food and monsters will get // additional effects. DifficultyHard difficultyHard )
var ( // Overworld is the Dimension implementation of a normal overworld. It has a // blue sky under normal circumstances and has a sun, clouds, stars and a // moon. Overworld has a building range of [-64, 320). Overworld overworld // Nether is a Dimension implementation with a lower base light level and a // darker sky without sun/moon. It has a building range of [0, 128). Nether nether // End is a Dimension implementation with a dark sky. It has a building // range of [0, 256). End end )
var ( // GameModeSurvival is the survival game mode: Players with this game mode have limited supplies and can break blocks // after taking some time. GameModeSurvival survival // GameModeCreative represents the creative game mode: Players with this game mode have infinite blocks and // items and can break blocks instantly. Players with creative mode can also fly. GameModeCreative creative // GameModeAdventure represents the adventure game mode: Players with this game mode cannot edit the world // (placing or breaking blocks). GameModeAdventure adventure // GameModeSpectator represents the spectator game mode: Players with this game mode cannot interact with the // world and cannot be seen by other players. spectator players can fly, like creative mode, and can // move through blocks. GameModeSpectator spectator )
var ( // ErrWorldClosed means the task's world closed before the task could run. ErrWorldClosed = errors.New("world: world closed") // ErrEntityClosed means the entity closed before the task could run. ErrEntityClosed = errors.New("world: entity closed") // ErrEntityNotInWorld means an entity was not in the transaction's world. ErrEntityNotInWorld = errors.New("world: entity not in this world") // ErrTaskCancelled means the task was cancelled before it started. ErrTaskCancelled = errors.New("world: scheduled task cancelled") // ErrTaskPanicked means the task's callback panicked; see PanicError. ErrTaskPanicked = errors.New("world: scheduled task panicked") // ErrEntityType means the entity no longer had the type expected by a // typed EntityRef when the task ran. ErrEntityType = errors.New("world: unexpected entity type") )
var DefaultBlockRegistry = &BasicBlockRegistry{ blockProperties: make(map[string]map[string]any), stateRuntimeIDs: make(map[stateHash]uint32), customBlocks: make(map[string]CustomBlock), }
DefaultBlockRegistry is the default (vanilla) block registry used by Dragonfly when no custom registry is provided.
The registry is populated during package init (block states + block implementations) and is finalized on first use by `server.Config.New()`, `world.Config.New()`, or `mcdb.Config.Open()`. Callers that need custom blocks should create a new registry using `NewBlockRegistry()` and pass it through config instead of mutating this value.
Functions ¶
func BiomeDefinitions ¶ added in v0.10.4
func BiomeDefinitions() ([]protocol.BiomeDefinition, []string)
BiomeDefinitions returns the list of biome definitions along with the associated StringList.
func BlockHash ¶ added in v0.9.18
BlockHash returns a unique identifier of the block including the block states using the DefaultBlockRegistry. This function is used internally to convert a block to a single integer which can be used in map lookups. The hash produced therefore does not need to match anything in the game, but it must be unique among all registered blocks. The tool in `/cmd/blockhash` may be used to automatically generate block hashes of blocks in a package.
If you use a non-default registry (NewBlockRegistry), use your registry instance's BlockHash(...) instead so the hash is consistent with that registry.
func BlockRuntimeID ¶
BlockRuntimeID attempts to return a runtime ID of a block previously registered using RegisterBlock() on the DefaultBlockRegistry. If the runtime ID cannot be found because the Block wasn't registered, BlockRuntimeID will panic. If you use a non-default registry (NewBlockRegistry), use your registry instance's BlockRuntimeID(...) instead.
func Call ¶ added in v0.11.0
Call runs f on w's owner and waits for its typed result. It is for off-owner code such as tests, startup and background goroutines; if you already have a *world.Tx, just use it directly. Calling it from the owner itself (any scheduled callback or Handler event) deadlocks. If f panics, Call re-panics with the original value on the waiting goroutine after logging the original stack through the World's Logger. Context cancellation stops pending work, but Call waits for a callback that has already started.
func CallEntity ¶ added in v0.11.0
func CallEntity[T any](ctx context.Context, h *EntityHandle, f func(tx *Tx, e Entity) (T, error)) (T, error)
CallEntity runs f with the EntityHandle's entity on its current world owner and waits for the typed result. Off-owner code only, like Call. If f panics, CallEntity re-panics with the original value on the waiting goroutine.
func CallRef ¶ added in v0.11.0
func CallRef[T any, E Entity](ctx context.Context, ref EntityRef[E], f func(tx *Tx, e E) (T, error)) (T, error)
CallRef runs f with the ref's entity on its current world owner and waits for the typed result. Off-owner code only, like Call. If f panics, CallRef re-panics with the original value on the waiting goroutine. Context cancellation stops pending work, but CallRef waits for a callback that has already started.
func ClampRedstonePower ¶ added in v0.11.0
ClampRedstonePower clamps power to the vanilla 0-15 redstone range.
func CustomBlocks ¶ added in v0.9.12
func CustomBlocks() map[string]CustomBlock
CustomBlocks returns a map of all custom blocks registered with their names as keys in the DefaultBlockRegistry. If you use a non-default registry (NewBlockRegistry), use your registry instance's CustomBlocks() instead.
func DifficultyID ¶ added in v0.9.5
func DifficultyID(diff Difficulty) (int, bool)
DifficultyID looks up the ID that a Difficulty was registered with. If not found, false is returned.
func DimensionID ¶ added in v0.9.5
DimensionID looks up the ID that a Dimension was registered with. If not found, false is returned.
func GameModeID ¶ added in v0.9.5
GameModeID looks up the ID that a GameMode was registered with. If not found, false is returned.
func ItemRuntimeID ¶
ItemRuntimeID attempts to return the runtime ID of the Item passed. False is returned if the Item is not registered.
func RedstoneFullPowerConductor ¶ added in v0.11.0
RedstoneFullPowerConductor reports whether b is a full solid redstone conductor according to the default redstone conductivity rules.
func RegisterBiome ¶ added in v0.5.0
func RegisterBiome(b Biome)
RegisterBiome registers a biome to the map so that it can be saved and loaded with the world.
func RegisterBlock ¶
func RegisterBlock(b Block)
RegisterBlock registers the Block passed in the DefaultBlockRegistry.
This function exists for backwards compatibility and works well for the common "single server per process" setup, where all worlds share the global default registry.
If you run multiple servers/registries in a single process, prefer creating a registry using NewBlockRegistry() and registering blocks on that instance (e.g. conf.Blocks.RegisterBlock(...)) before calling Finalize().
func RegisterItem ¶
func RegisterItem(item Item)
RegisterItem registers an item with the ID and meta passed. Once registered, items may be obtained from an ID and metadata value using itemByID(). If an item with the ID and meta passed already exists, RegisterItem panics.
Types ¶
type ArrowSpawnConfig ¶ added in v0.10.14
type ArrowSpawnConfig struct {
// Damage specifies the base damage dealt by the arrow.
Damage float64
// Owner is the entity that fired the arrow.
Owner Entity
// Critical specifies if the arrow should deal critical damage.
Critical bool
// DisablePickup specifies if picking up the arrow should be disabled.
DisablePickup bool
// ObtainArrowOnPickup specifies if the arrow should be returned as an item when picked up.
ObtainArrowOnPickup bool
// PunchLevel specifies the level of punch knockback applied to the arrow.
PunchLevel int
// PiercingLevel is the crossbow Piercing enchantment level. The arrow passes
// through PiercingLevel entities and damages PiercingLevel+1 in total. A
// value of 0 means no piercing.
PiercingLevel int
// Tip specifies the potion tip carried by the arrow.
Tip any
}
ArrowSpawnConfig holds the options used to spawn an arrow entity.
type BasicBlockRegistry ¶ added in v0.10.14
type BasicBlockRegistry struct {
// contains filtered or unexported fields
}
BasicBlockRegistry is the default BlockRegistry implementation used by Dragonfly.
func (*BasicBlockRegistry) Air ¶ added in v0.10.14
func (br *BasicBlockRegistry) Air() Block
Air returns an air block.
func (*BasicBlockRegistry) AirRuntimeID ¶ added in v0.10.14
func (br *BasicBlockRegistry) AirRuntimeID() uint32
AirRuntimeID returns the runtime ID of the air block.
func (*BasicBlockRegistry) BitSize ¶ added in v0.10.14
func (br *BasicBlockRegistry) BitSize() int
func (*BasicBlockRegistry) BlockByName ¶ added in v0.10.14
BlockByName attempts to return a Block by its name and properties. If not found, the bool returned is false.
func (*BasicBlockRegistry) BlockByRuntimeID ¶ added in v0.10.14
func (br *BasicBlockRegistry) BlockByRuntimeID(rid uint32) (Block, bool)
BlockByRuntimeID attempts to return a Block by its runtime ID. If not found, the bool returned is false. If found, the block is non-nil and the bool true.
func (*BasicBlockRegistry) BlockByRuntimeIDOrAir ¶ added in v0.10.14
func (br *BasicBlockRegistry) BlockByRuntimeIDOrAir(rid uint32) Block
func (*BasicBlockRegistry) BlockCount ¶ added in v0.10.14
func (br *BasicBlockRegistry) BlockCount() int
func (*BasicBlockRegistry) BlockHash ¶ added in v0.10.14
func (br *BasicBlockRegistry) BlockHash(b Block) uint64
BlockHash returns a unique identifier of the block including the block states. This function is used internally to convert a block to a single integer which can be used in map lookups. The hash produced therefore does not need to match anything in the game, but it must be unique among all registered blocks. The tool in `/cmd/blockhash` may be used to automatically generate block hashes of blocks in a package.
func (*BasicBlockRegistry) BlockRuntimeID ¶ added in v0.10.14
func (br *BasicBlockRegistry) BlockRuntimeID(b Block) uint32
BlockRuntimeID attempts to return a runtime ID of a block previously registered using RegisterBlock(). If the runtime ID cannot be found because the Block wasn't registered, BlockRuntimeID will panic.
func (*BasicBlockRegistry) Blocks ¶ added in v0.10.14
func (br *BasicBlockRegistry) Blocks() []Block
func (*BasicBlockRegistry) Clone ¶ added in v0.10.14
func (br *BasicBlockRegistry) Clone() *BasicBlockRegistry
Clone returns an independent copy of the registry. If the source registry is finalized, the clone is also finalized. If the source is not finalized, the clone remains mutable.
func (*BasicBlockRegistry) CustomBlocks ¶ added in v0.10.14
func (br *BasicBlockRegistry) CustomBlocks() map[string]CustomBlock
CustomBlocks returns a map of all custom blocks registered with their names as keys.
func (*BasicBlockRegistry) FilteringBlock ¶ added in v0.10.14
func (br *BasicBlockRegistry) FilteringBlock(rid uint32) uint8
func (*BasicBlockRegistry) Finalize ¶ added in v0.10.14
func (br *BasicBlockRegistry) Finalize()
func (*BasicBlockRegistry) HashToRuntimeID ¶ added in v0.10.14
func (br *BasicBlockRegistry) HashToRuntimeID(hash uint32) (rid uint32, ok bool)
func (*BasicBlockRegistry) LightBlock ¶ added in v0.10.14
func (br *BasicBlockRegistry) LightBlock(rid uint32) uint8
func (*BasicBlockRegistry) LiquidBlock ¶ added in v0.10.14
func (br *BasicBlockRegistry) LiquidBlock(rid uint32) bool
func (*BasicBlockRegistry) LiquidDisplacingBlock ¶ added in v0.10.14
func (br *BasicBlockRegistry) LiquidDisplacingBlock(rid uint32) bool
func (*BasicBlockRegistry) NBTBlock ¶ added in v0.10.14
func (br *BasicBlockRegistry) NBTBlock(rid uint32) bool
func (*BasicBlockRegistry) RandomTickBlock ¶ added in v0.10.14
func (br *BasicBlockRegistry) RandomTickBlock(rid uint32) bool
func (*BasicBlockRegistry) RegisterBlock ¶ added in v0.10.14
func (br *BasicBlockRegistry) RegisterBlock(b Block)
RegisterBlock registers the Block passed. The EncodeBlock method will be used to encode and decode the block passed. RegisterBlock panics if the block properties returned were not valid, existing properties.
func (*BasicBlockRegistry) RegisterBlockState ¶ added in v0.10.14
func (br *BasicBlockRegistry) RegisterBlockState(s BlockState)
RegisterBlockState registers a BlockState to the registry. The function panics if the properties the BlockState holds are invalid or if the BlockState was already registered.
func (*BasicBlockRegistry) RuntimeIDToHash ¶ added in v0.10.14
func (br *BasicBlockRegistry) RuntimeIDToHash(runtimeID uint32) (hash uint32, ok bool)
func (*BasicBlockRegistry) RuntimeIDToState ¶ added in v0.10.14
func (br *BasicBlockRegistry) RuntimeIDToState(runtimeID uint32) (name string, properties map[string]any, found bool)
RuntimeIDToState returns the name and state properties of a block by its runtime ID.
func (*BasicBlockRegistry) StateToRuntimeID ¶ added in v0.10.14
func (br *BasicBlockRegistry) StateToRuntimeID(name string, properties map[string]any) (runtimeID uint32, found bool)
StateToRuntimeID returns the runtime ID of a block by its name and state properties.
type Biome ¶ added in v0.5.0
type Biome interface {
// Temperature returns the temperature of the biome.
Temperature() float64
// Rainfall returns the rainfall of the biome.
Rainfall() float64
// Depth returns the depth of the biome.
Depth() float64
// Scale returns the scale of the biome.
Scale() float64
// WaterColour returns the water colour of the biome.
WaterColour() color.RGBA
// Tags returns the tags for the biome.
Tags() []string
// String returns the biome name as a string.
String() string
// EncodeBiome encodes the biome into an int value that is used to identify the biome over the network.
EncodeBiome() int
}
Biome is a region in a world with distinct geographical features, flora, temperatures, humidity ratings, and sky, water, grass and foliage colours.
func BiomeByName ¶ added in v0.8.10
BiomeByName looks up a biome by the name and returns it if found.
type Block ¶
type Block interface {
// EncodeBlock encodes the block to a string ID such as 'minecraft:grass' and properties associated
// with the block.
EncodeBlock() (string, map[string]any)
// Hash returns two different identifiers for the block. The first is the base hash which is unique for
// each type of block at runtime. For vanilla blocks, this is an auto-incrementing constant and for custom
// blocks, you can call block.NextHash() to get a unique identifier. The second is the hash of the block's
// own state and does not need to worry about colliding with other types of blocks. This is later combined
// with the base hash to create a unique identifier for the full block.
Hash() (uint64, uint64)
// Model returns the BlockModel of the Block.
Model() BlockModel
}
Block is a block that may be placed or found in a world. In addition, the block may also be added to an inventory: It is also an item. Every Block implementation must be able to be hashed as key in a map.
func BlockByName ¶
BlockByName attempts to return a Block by its name and properties using the DefaultBlockRegistry. If not found, the bool returned is false. If you use a non-default registry (NewBlockRegistry), use your registry instance's BlockByName(...) instead.
func BlockByRuntimeID ¶
BlockByRuntimeID attempts to return a Block by its runtime ID using the DefaultBlockRegistry. If not found, the bool returned is false. If found, the block is non-nil and the bool true. If you use a non-default registry (NewBlockRegistry), use your registry instance's BlockByRuntimeID(...) instead.
type BlockAction ¶ added in v0.6.0
type BlockAction interface {
BlockAction()
}
BlockAction represents an action that may be performed by a block. Typically, these actions are sent to viewers in a world so that they can see these actions.
type BlockModel ¶
type BlockModel interface {
// BBox returns the bounding boxes that a block with this model can be collided with.
BBox(pos cube.Pos, s BlockSource) []cube.BBox
// FaceSolid checks if a specific face of a block at the position in a world passed is solid. Blocks may
// be attached to these faces.
FaceSolid(pos cube.Pos, face cube.Face, s BlockSource) bool
}
BlockModel represents the model of a block. These models specify the ways a block can be collided with and whether specific faces are solid wrt. being able to, for example, place torches onto those sides.
type BlockRegistry ¶ added in v0.10.14
type BlockRegistry interface {
chunk.BlockRegistry
// BlockByRuntimeID looks up a Block by runtime ID. If the runtime ID is unknown/out of range, ok is false.
BlockByRuntimeID(rid uint32) (Block, bool)
// BlockByRuntimeIDOrAir looks up a Block by runtime ID. If not found, an air block is returned.
BlockByRuntimeIDOrAir(rid uint32) Block
// BlockRuntimeID looks up the runtime ID of a previously registered Block.
BlockRuntimeID(block Block) (rid uint32)
// RegisterBlock registers a Block implementation for a previously registered block state.
RegisterBlock(block Block)
// RegisterBlockState registers a block state that blocks may encode to.
RegisterBlockState(blockState BlockState)
// CustomBlocks returns custom blocks registered in this registry, keyed by identifier.
CustomBlocks() map[string]CustomBlock
// BlockByName looks up a Block by full identifier and properties.
BlockByName(name string, properties map[string]any) (Block, bool)
// Blocks returns all blocks registered in the registry, indexed by runtime ID.
Blocks() []Block
// Air returns the air block registered in the registry.
Air() Block
// Finalize finalizes the registry, building derived lookup tables required for runtime usage. Finalize is
// idempotent.
Finalize()
// BitSize returns the number of bits used by BlockHash (depends on the number of registered blocks).
BitSize() int
// BlockHash returns a unique identifier of the block including the block states. The hash is internal to Dragonfly
// and is used for fast map lookups; it does not need to match any in-game identifiers.
BlockHash(b Block) uint64
// RuntimeIDToHash resolves a runtime ID to its network block hash.
RuntimeIDToHash(runtimeID uint32) (hash uint32, ok bool)
}
BlockRegistry converts between runtime IDs and block states/implementations.
A BlockRegistry has a build/finalize lifecycle:
- During setup, blocks and block states may be registered using RegisterBlockState/RegisterBlock.
- After calling Finalize, the registry becomes immutable and is ready for use in chunk encoding/decoding and network serialization. RegisterBlock/RegisterBlockState will panic after finalization.
The interface is split because the chunk package cannot import world.Block.
func NewBlockRegistry ¶ added in v0.10.14
func NewBlockRegistry() BlockRegistry
NewBlockRegistry returns a mutable registry seeded with all vanilla block states and block implementations. Callers may RegisterBlockState/RegisterBlock and must call Finalize() before using the registry for world/chunk serialization. The returned registry is independent from DefaultBlockRegistry.
type BlockSource ¶ added in v0.9.19
type BlockSource interface {
// Block returns the block at the given position in the block source.
Block(cube.Pos) Block
}
BlockSource represents a source for obtaining blocks.
type BlockState ¶ added in v0.10.14
type BlockState struct {
Name string `nbt:"name"`
Properties map[string]any `nbt:"states"`
Version int32 `nbt:"version"`
}
BlockState holds a combination of a name and properties, together with a version.
type ChunkPos ¶
type ChunkPos [2]int32
ChunkPos holds the position of a chunk. The type is provided as a utility struct for keeping track of a chunk's position. Chunks do not themselves keep track of that. Chunk positions are different from block positions in the way that increasing the X/Z by one means increasing the absolute value on the X/Z axis in terms of blocks by 16.
type Column ¶ added in v0.9.5
type Column struct {
*chunk.Chunk
Entities []*EntityHandle
BlockEntities map[cube.Pos]Block
// contains filtered or unexported fields
}
Column represents the data of a chunk including the (block) entities and viewers and loaders.
type Config ¶ added in v0.7.0
type Config struct {
// Log is the Logger that will be used to log errors and debug messages to.
// If set to nil, slog.Default() is set.
Log *slog.Logger
// Dim is the Dimension of the World. If set to nil, the World will use
// Overworld as its dimension. The dimension set here influences, among
// others, the sky colour, weather/time and liquid behaviour in that World.
Dim Dimension
// PortalDestination is a function that returns the destination World for a
// portal of a specific Dimension type. If set to nil, no portals will
// function. If the function returns a nil world for a Dimension, only
// portals of that specific Dimension type will not function.
PortalDestination func(dim Dimension) *World
// Provider is the Provider implementation used to read and write World
// data. If set to nil, the Provider used will be NopProvider, which does
// not store any data to disk.
Provider Provider
// Generator is the Generator implementation used to generate new areas of
// the World. If set to nil, the Generator used will be NopGenerator, which
// generates completely empty chunks.
Generator Generator
// ReadOnly specifies if the World should be read-only, meaning no new data
// will be written to the Provider.
ReadOnly bool
// SaveInterval specifies how often a World should be automatically saved to
// disk. This includes chunks, entities and level.dat data. If ReadOnly is
// set to false, changing SaveInterval will have no effect.
// By default, SaveInterval is set to 10 minutes. Setting SaveInterval to
// a negative number disables automatic saving entirely.
SaveInterval time.Duration
// ChunkUnloadInterval specifies how often unused chunks should be unloaded
// from memory when no longer in use. By default, this is set to 2 minutes.
// ChunkUnloadInterval should not be used to prevent chunks from unloading
// altogether. This should be done using a Loader with a custom Viewer.
ChunkUnloadInterval time.Duration
// RandomTickSpeed specifies the rate at which blocks should be ticked in
// the World. By default, each sub chunk has 3 blocks randomly ticked per
// sub chunk, so the default value is 3. Setting this value to -1 or lower
// will stop random ticking altogether, while setting it higher results in
// faster ticking.
RandomTickSpeed int
// RandSource is the rand.Source used for generation of random numbers in a
// World, such as when selecting blocks to tick or when deciding where to
// strike lightning. If set to nil, RandSource defaults to a `rand.PCG`
// source seeded with `time.Now().UnixNano()`. PCG is significantly faster
// than `rand.ChaCha8` on 64-bit systems at the expense of poorer
// statistical distribution, which is acceptable here.
// See https://go.dev/blog/chacha8rand.
RandSource rand.Source
// Entities is an EntityRegistry with all Entity types registered that may
// be added to the World.
Entities EntityRegistry
// Blocks is the BlockRegistry used by the World.
// If left nil, DefaultBlockRegistry is used. For a non-default registry,
// use NewBlockRegistry(), register blocks/states, and call Finalize().
Blocks BlockRegistry
// Synchronous removes the World's own background goroutines. Immediate tasks
// from World.Do and Call run on the calling goroutine, the World is not saved
// or unloaded automatically, and time only passes on explicit
// World.AdvanceTick calls. World.DoAfter and entity work scheduled before an
// entity enters a world still use background goroutines and wall-clock
// delays; callers must synchronise on the returned Task. This makes
// Synchronous Worlds well suited to unit tests that need a World to interact
// with.
// A Synchronous World must be driven from one goroutine. Do, Call and
// AdvanceTick are not safe to call concurrently, including from delayed
// item or death callbacks.
Synchronous bool
}
Config may be used to create a new World. It holds a variety of fields that influence the World.
type Context ¶ added in v0.10.0
type Context struct {
*Tx
// contains filtered or unexported fields
}
Context is a cancellable event scope passed to Handler events. It embeds the owner transaction, so world operations are available directly on it.
type CustomBlock ¶ added in v0.9.12
type CustomBlock interface {
Block
Properties() customblock.Properties
}
CustomBlock represents a block that is non-vanilla and requires a resource pack and extra steps to show it to the client.
type CustomBlockBuildable ¶ added in v0.9.12
type CustomBlockBuildable interface {
CustomBlock
// Name is the name displayed to clients using the block.
Name() string
// Geometry is the geometries for the block that define the shape of the block. If false is returned, no custom
// geometry will be applied. Permutation-specific geometry can be defined by returning a map of permutations to
// geometry.
Geometry() []byte
// Textures is a map of images indexed by their target, used to map textures on to the block. Permutation-specific
// textures can be defined by returning a map of permutations to textures.
Textures() map[string]image.Image
}
type CustomItem ¶ added in v0.6.0
type CustomItem interface {
Item
// Name is the name that will be displayed on the item to all clients.
Name() string
// Texture is the Image of the texture for this item.
Texture() image.Image
// Category is the category the item will be listed under in the creative inventory.
Category() category.Category
}
CustomItem represents an item that is non-vanilla and requires a resource pack and extra steps to show it to the client.
func CustomItems ¶ added in v0.6.0
func CustomItems() []CustomItem
CustomItems returns a slice of all registered custom items.
type DamageSource ¶ added in v0.8.6
type DamageSource interface {
// ReducedByArmour checks if the source of damage may be reduced if the
// receiver of the damage is wearing armour.
ReducedByArmour() bool
// ReducedByResistance specifies if the Source is affected by the resistance
// effect. If false, damage dealt to an Entity with this source will not be
// lowered if the Entity has the resistance effect.
ReducedByResistance() bool
// Fire specifies if the Source is fire related and should be ignored when
// an Entity has the fire resistance effect.
Fire() bool
// IgnoreTotem specifies whether the totem will be ignored if the damage is lethal.
IgnoreTotem() bool
}
DamageSource represents the source of the damage dealt to an Entity. This source may be passed to the Hurt() method of an Entity in order to deal damage to an Entity with a specific source.
type Difficulty ¶
type Difficulty interface {
// FoodRegenerates specifies if players' food levels should automatically
// regenerate with this difficulty.
FoodRegenerates() bool
// StarvationHealthLimit specifies the amount of health at which a player
// will no longer receive damage from starvation.
StarvationHealthLimit() float64
// FireSpreadIncrease returns a number that increases the rate at which fire
// spreads.
FireSpreadIncrease() int
}
Difficulty represents the difficulty of a Minecraft world. The difficulty of a world influences all kinds of aspects of the world, such as the damage enemies deal to players, the way hunger depletes, whether hostile monsters spawn or not and more.
func DifficultyByID ¶ added in v0.9.5
func DifficultyByID(id int) (Difficulty, bool)
DifficultyByID looks up a Difficulty for the ID passed, returning DifficultyPeaceful for 0, DifficultyEasy for 1, DifficultyNormal for 2 and DifficultyHard for 3. If the ID is unknown, the bool returned is false. In this case the Difficulty returned is DifficultyNormal.
type Dimension ¶ added in v0.5.0
type Dimension interface {
// Range returns the lowest and highest valid Y coordinates of a block
// in the Dimension.
Range() cube.Range
WaterEvaporates() bool
LavaSpreadDuration() time.Duration
WeatherCycle() bool
TimeCycle() bool
}
Dimension is a dimension of a World. It influences a variety of properties of a World such as the building range, the sky colour and the behaviour of liquid blocks.
func DimensionByID ¶ added in v0.9.5
DimensionByID looks up a Dimension for the ID passed, returning Overworld for 0, Nether for 1 and End for 2. If the ID is unknown, the bool returned is false. In this case the Dimension returned is Overworld.
type Entity ¶
type Entity interface {
io.Closer
// H returns the EntityHandle that points to the entity.
H() *EntityHandle
// Position returns the current position of the Entity in the world.
Position() mgl64.Vec3
// Rotation returns the yaw (horizontal rotation) and pitch (vertical
// rotation) of the entity in degrees.
Rotation() cube.Rotation
}
Entity represents an Entity in the world, typically an object that may be moved around and can be interacted with by other entities. Viewers of a world may view an Entity when near it.
type EntityAction ¶ added in v0.6.0
type EntityAction interface {
EntityAction()
}
EntityAction represents an action that may be performed by an Entity. Typically, these actions are sent to viewers in a world so that they can see these actions.
type EntityAnimation ¶ added in v0.10.0
type EntityAnimation struct {
// contains filtered or unexported fields
}
EntityAnimation represents an animation that may be played on an entity from an active resource pack on the client.
func NewEntityAnimation ¶ added in v0.10.0
func NewEntityAnimation(name string) EntityAnimation
NewEntityAnimation returns a new animation that can be played on an entity. If no controller or stop condition is set, the animation will play for its full duration, including looping. Controllers can be set to manage multiple states of animations. It is also possible to use vanilla animations/controllers if they work for your entity, i.e. "animation.pig.baby_transform".
func (EntityAnimation) Controller ¶ added in v0.10.0
func (a EntityAnimation) Controller() string
Controller returns the name of the controller to be used for the animation.
func (EntityAnimation) Name ¶ added in v0.10.0
func (a EntityAnimation) Name() string
Name returns the name of the animation to be played.
func (EntityAnimation) NextState ¶ added in v0.10.0
func (a EntityAnimation) NextState() string
NextState returns the state to transition to after the animation has finished playing within the animation controller.
func (EntityAnimation) StopCondition ¶ added in v0.10.0
func (a EntityAnimation) StopCondition() string
StopCondition returns the condition that must be met for the animation to stop playing. This is often a Molang expression that can be used to query various entity properties to determine when the animation should stop playing.
func (EntityAnimation) WithController ¶ added in v0.10.0
func (a EntityAnimation) WithController(controller string) EntityAnimation
WithController returns a copy of the EntityAnimation with the provided animation controller. An animation controller with the same name must be defined in a resource pack for it to work.
func (EntityAnimation) WithNextState ¶ added in v0.10.0
func (a EntityAnimation) WithNextState(state string) EntityAnimation
WithNextState returns a copy of the EntityAnimation with the provided state to transition to after the animation has finished playing within the animation controller.
func (EntityAnimation) WithStopCondition ¶ added in v0.10.0
func (a EntityAnimation) WithStopCondition(condition string) EntityAnimation
WithStopCondition returns a copy of the EntityAnimation with the provided stop condition. The stop condition is a Molang expression that can be used to query various entity properties to determine when the animation should stop playing.
type EntityConfig ¶ added in v0.10.0
type EntityConfig interface {
Apply(data *EntityData)
}
EntityConfig is used to configure the initial settings of an Entity upon creation using NewEntity.
type EntityData ¶ added in v0.10.0
type EntityData struct {
Pos, Vel mgl64.Vec3
Rot cube.Rotation
Name string
FireDuration time.Duration
Age time.Duration
Data any
}
EntityData holds data shared by every entity. It is kept in an EntityHandle.
type EntityHandle ¶ added in v0.10.0
type EntityHandle struct {
// contains filtered or unexported fields
}
EntityHandle is a persistent identifier of an entity. It holds data of the entity that can be transformed into an Entity implementation in the context of a transaction.
func NewEntity ¶ added in v0.10.0
func NewEntity(t EntityType, conf EntityConfig) *EntityHandle
NewEntity creates an EntityHandle using an EntityType and EntityConfig passed. The EntityHandle may be added to a world by calling Tx.AddEntity(). NewEntity uses the zero value for EntitySpawnOpts.
func (*EntityHandle) Close ¶ added in v0.10.0
func (e *EntityHandle) Close() error
Close closes the EntityHandle. Any subsequently scheduled work will fail with ErrEntityClosed without the transaction function being called. Close always returns nil.
func (*EntityHandle) Closed ¶ added in v0.11.0
func (e *EntityHandle) Closed() bool
Closed reports whether the EntityHandle has been closed.
func (*EntityHandle) Do ¶ added in v0.11.0
func (e *EntityHandle) Do(f func(tx *Tx, e Entity)) *Task
Do schedules f to run with the entity on its current world owner and returns immediately. If the entity is in no world yet, the task waits until it enters one or the handle closes. The entity passed to f is only valid inside f. On a synchronous World, f runs before Do returns.
func (*EntityHandle) DoAfter ¶ added in v0.11.0
DoAfter schedules f to run with the entity after delay, following the entity if it changes worlds in the meantime.
func (*EntityHandle) Entity ¶ added in v0.10.0
func (e *EntityHandle) Entity(tx *Tx) (Entity, bool)
Entity attempts to convert an EntityHandle to an Entity using the Tx passed. A non-nil Entity is returned only if the entity's world matches the world of the Tx. If they do not match, false is returned.
func (*EntityHandle) Type ¶ added in v0.10.0
func (e *EntityHandle) Type() EntityType
Type returns the EntityType of the EntityHandle.
func (*EntityHandle) UUID ¶ added in v0.10.0
func (e *EntityHandle) UUID() uuid.UUID
UUID returns the identifier of the EntityHandle.
type EntityRef ¶ added in v0.11.0
type EntityRef[T Entity] struct { // contains filtered or unexported fields }
EntityRef is a stable, typed reference to an entity. The entity value T is only handed to scheduled owner callbacks, where it is safe to use.
func NewEntityRef ¶ added in v0.11.0
func NewEntityRef[T Entity](h *EntityHandle) EntityRef[T]
NewEntityRef creates a typed reference from an EntityHandle.
func (EntityRef[T]) Do ¶ added in v0.11.0
Do schedules f on the entity's current world owner, like EntityHandle.Do, but hands f the entity as T. If the entity is no longer a T when the task runs, the task fails with ErrEntityType.
func (EntityRef[T]) DoAfter ¶ added in v0.11.0
DoAfter schedules f on the entity's world owner after delay, typed like Do.
func (EntityRef[T]) Handle ¶ added in v0.11.0
func (r EntityRef[T]) Handle() *EntityHandle
Handle returns the underlying stable entity handle.
type EntityRegistry ¶ added in v0.9.0
type EntityRegistry struct {
// contains filtered or unexported fields
}
EntityRegistry is a mapping that EntityTypes may be registered to. It is used for loading entities from disk in a World's Provider.
func (EntityRegistry) Config ¶ added in v0.9.0
func (reg EntityRegistry) Config() EntityRegistryConfig
Config returns the EntityRegistryConfig that was used to create the EntityRegistry.
func (EntityRegistry) Lookup ¶ added in v0.9.0
func (reg EntityRegistry) Lookup(name string) (EntityType, bool)
Lookup looks up an EntityType by its name. If found, the EntityType is returned and the bool is true. The bool is false otherwise.
func (EntityRegistry) Types ¶ added in v0.9.0
func (reg EntityRegistry) Types() []EntityType
Types returns all EntityTypes passed upon construction of the EntityRegistry.
type EntityRegistryConfig ¶ added in v0.9.0
type EntityRegistryConfig struct {
Item func(opts EntitySpawnOpts, it any) *EntityHandle
FallingBlock func(opts EntitySpawnOpts, bl Block) *EntityHandle
TNT func(opts EntitySpawnOpts, fuse time.Duration) *EntityHandle
BottleOfEnchanting func(opts EntitySpawnOpts, owner Entity) *EntityHandle
Arrow func(opts EntitySpawnOpts, conf ArrowSpawnConfig) *EntityHandle
Egg func(opts EntitySpawnOpts, owner Entity) *EntityHandle
EnderPearl func(opts EntitySpawnOpts, owner Entity) *EntityHandle
Firework func(opts EntitySpawnOpts, firework Item, owner Entity, sidewaysVelocityMultiplier, upwardsAcceleration float64, attached bool) *EntityHandle
LingeringPotion func(opts EntitySpawnOpts, t any, owner Entity) *EntityHandle
Snowball func(opts EntitySpawnOpts, owner Entity) *EntityHandle
SplashPotion func(opts EntitySpawnOpts, t any, owner Entity) *EntityHandle
Lightning func(opts EntitySpawnOpts) *EntityHandle
}
EntityRegistryConfig holds functions used by the block and item packages to create entities as a result of their behaviour. ALL functions of EntityRegistryConfig must be filled out for the behaviour of these blocks and items not to fail.
func (EntityRegistryConfig) New ¶ added in v0.9.0
func (conf EntityRegistryConfig) New(ent []EntityType) EntityRegistry
New creates an EntityRegistry using conf and the EntityTypes passed.
type EntitySpawnOpts ¶ added in v0.10.0
type EntitySpawnOpts struct {
// Position is the position that an Entity should be spawned at.
Position mgl64.Vec3
// Rotation is the rotation that an Entity should be spawned with.
Rotation cube.Rotation
// Velocity specifies the initial velocity of the Entity.
Velocity mgl64.Vec3
// ID specifies the UUID of an entity. This field should usually be left
// empty, as a valid UUID is generated when not set. Non-player entities
// only have the last 8 bytes of the UUID set.
ID uuid.UUID
// NameTag is the name tag that the entity is spawned with.
NameTag string
}
EntitySpawnOpts holds spawning related options for entities created.
func (EntitySpawnOpts) New ¶ added in v0.10.0
func (opts EntitySpawnOpts) New(t EntityType, conf EntityConfig) *EntityHandle
New creates an EntityHandle using an EntityType and EntityConfig passed. The EntityHandle may be added to a world by calling Tx.AddEntity(). The spawn conditions depend on the options set in opts.
type EntityType ¶ added in v0.8.7
type EntityType interface {
// Open returns an Entity implementation in a transaction.
Open(tx *Tx, handle *EntityHandle, data *EntityData) Entity
// EncodeEntity converts the Entity to its encoded representation: It
// returns the type of the Minecraft Entity, for example
// 'minecraft:falling_block'.
EncodeEntity() string
// BBox returns the bounding box of an Entity with this EntityType.
BBox(e Entity) cube.BBox
// DecodeNBT reads the fields from the NBT data map passed and converts it
// to an Entity of the same EntityType.
DecodeNBT(m map[string]any, data *EntityData)
// EncodeNBT encodes the Entity of the same EntityType passed to a map of
// properties that can be encoded to NBT.
EncodeNBT(data *EntityData) map[string]any
}
EntityType is the type of Entity. It specifies the name, encoded Entity ID and bounding box of an Entity.
type GameMode ¶
type GameMode interface {
// AllowsEditing specifies if a player with this GameMode can edit the World it's in.
AllowsEditing() bool
// AllowsTakingDamage specifies if a player with this GameMode can take damage from other entities.
AllowsTakingDamage() bool
// CreativeInventory specifies if a player with this GameMode has access to the creative inventory.
CreativeInventory() bool
// HasCollision specifies if a player with this GameMode can collide with blocks or entities in the world.
HasCollision() bool
// AllowsFlying specifies if a player with this GameMode can fly freely.
AllowsFlying() bool
// AllowsInteraction specifies if a player with this GameMode can interact with the world through entities or if it
// can use items in the world.
AllowsInteraction() bool
// Visible specifies if a player with this GameMode can be visible to other players. If false, the player will be
// invisible under any circumstance.
Visible() bool
// InstantPortalTravel specifies if a player with this GameMode travels through nether portals instantly,
// without the four second wait.
InstantPortalTravel() bool
}
GameMode represents a game mode that may be assigned to a player. Upon joining the world, players will be given the default game mode that the world holds. Game modes specify the way that a player interacts with and plays in the world.
func GameModeByID ¶ added in v0.9.5
GameModeByID looks up a GameMode for the ID passed, returning GameModeSurvival for 0, GameModeCreative for 1, GameModeAdventure for 2 and GameModeSpectator for 3. If the ID is unknown, the bool returned is false. In this case the GameMode returned is GameModeSurvival.
type Generator ¶
type Generator interface {
// GenerateChunk generates a chunk at a chunk position passed. The generator sets blocks in the chunk that
// is passed to the method.
GenerateChunk(pos ChunkPos, chunk *chunk.Chunk)
// DefaultSpawn returns the default spawn position for worlds using this generator in the dimension passed.
DefaultSpawn(dim Dimension) cube.Pos
}
Generator handles the generating of newly created chunks. Worlds have one generator which is used to generate chunks when the provider of the world cannot find a chunk at a given chunk position.
type Handler ¶
type Handler interface {
// HandleLiquidFlow handles the flowing of a liquid from one block position
// from into another block position into. The liquid that will replace the
// block is also passed. This replaced block might also be a Liquid. The
// Liquid's depth and falling state can be checked to see if the resulting
// liquid is a new source block (in the case of water).
HandleLiquidFlow(ctx *Context, from, into cube.Pos, liquid Liquid, replaced Block)
// HandleLiquidDecay handles the decaying of a Liquid block at a position.
// Liquid decaying happens when there is no Liquid that can serve as the
// source block neighbouring it. The state of the Liquid before and after
// the decaying is passed. The Liquid after is nil if the liquid is
// completely removed as a result of the decay.
HandleLiquidDecay(ctx *Context, pos cube.Pos, before, after Liquid)
// HandleLiquidHarden handles the hardening of a liquid at hardenedPos. The
// liquid that was hardened, liquidHardened, and the liquid that caused it
// to harden, otherLiquid, are passed. The block created as a result is also
// passed.
HandleLiquidHarden(ctx *Context, hardenedPos cube.Pos, liquidHardened, otherLiquid, newBlock Block)
// HandleSound handles a Sound being played in the World at a specific
// position. ctx.Cancel() may be called to stop the Sound from playing to
// viewers of the position.
HandleSound(ctx *Context, s Sound, pos mgl64.Vec3)
// HandleFireSpread handles when a fire block spreads from one block to
// another block. When this event handler gets called, both the position of
// the original fire will be passed, and the position where it will spread
// to after the event. The age of the fire may also be altered by changing
// the underlying value of the newFireAge pointer, which decides how long
// the fire will stay before burning out.
HandleFireSpread(ctx *Context, from, to cube.Pos)
// HandleBlockBurn handles a block at a cube.Pos being burnt by fire. This
// event may be called for blocks such as wood, that can be broken by fire.
// HandleBlockBurn is often succeeded by HandleFireSpread, when fire spreads
// to the position of the original block and the Context is not cancelled in
// HandleBlockBurn.
HandleBlockBurn(ctx *Context, pos cube.Pos)
// HandleCropTrample handles an Entity trampling a crop.
HandleCropTrample(ctx *Context, pos cube.Pos)
// HandleLeavesDecay handles the decaying of a Leaves block at a position.
// Leaves decaying happens when there is no wood block neighbouring it.
// ctx.Cancel() may be called to prevent leaves from decaying.
HandleLeavesDecay(ctx *Context, pos cube.Pos)
// HandleEntitySpawn handles an Entity being spawned into a World through a
// call to Tx.AddEntity or Tx.AddEntityAt.
HandleEntitySpawn(tx *Tx, e Entity)
// HandleEntityDespawn handles an Entity being despawned from a World
// through a call to Tx.RemoveEntity.
HandleEntityDespawn(tx *Tx, e Entity)
// HandleExplosion handles an explosion in the world. ctx.Cancel() may be called
// to cancel the explosion.
// The affected entities, affected blocks, item drop chance, and whether the
// explosion spawns fire may be altered.
HandleExplosion(ctx *Context, position mgl64.Vec3, entities *[]Entity, blocks *[]cube.Pos, itemDropChance *float64, spawnFire *bool)
// HandleRedstoneUpdate handles a redstone update proposed by the World redstone engine. ctx.Cancel() may be
// called to suppress the proposed redstone mutation and any propagation from that mutation.
HandleRedstoneUpdate(ctx *Context, update RedstoneUpdate)
// HandleClose handles the World being closed. HandleClose may be used as a
// moment to finish code running on other goroutines that operates on the
// World specifically. HandleClose is called directly before the World stops
// ticking and before any chunks are saved to disk.
HandleClose(tx *Tx)
}
Handler handles events that are called by a world. Implementations of Handler may be used to listen to specific events such as when an Entity is added to the world.
type HealingSource ¶ added in v0.8.6
type HealingSource interface {
HealingSource()
}
HealingSource represents a source of healing for an Entity. This source may be passed to the Heal() method of a living Entity.
type Item ¶
type Item interface {
// EncodeItem encodes the item to its Minecraft representation, which consists of a numerical ID and a
// metadata value.
EncodeItem() (name string, meta int16)
}
Item represents an item that may be added to an inventory. It has a method to encode the item to an ID and a metadata value.
func ItemByName ¶
ItemByName attempts to return an item by a name and a metadata value.
func ItemByRuntimeID ¶
ItemByRuntimeID attempts to return an Item by the runtime ID passed. If no item with that runtime ID exists, false is returned. ItemByRuntimeID also tries to find the item with a metadata value of 0.
type Liquid ¶
type Liquid interface {
Block
// LiquidDepth returns the current depth of the liquid.
LiquidDepth() int
// SpreadDecay returns the amount of depth that is subtracted from the liquid's depth when it spreads to
// a next block.
SpreadDecay() int
// WithDepth returns the liquid with the depth passed.
WithDepth(depth int, falling bool) Liquid
// LiquidFalling checks if the liquid is currently considered falling down.
LiquidFalling() bool
// BlastResistance is the blast resistance of the liquid, which influences the liquid's ability to withstand an
// explosive blast.
BlastResistance() float64
// LiquidType returns an int unique for the liquid, used to check if two liquids are considered to be
// of the same type.
LiquidType() string
// Harden checks if the block should harden when looking at the surrounding blocks and sets the position
// to the hardened block when adequate. If the block was hardened, the method returns true.
Harden(pos cube.Pos, tx *Tx, flownIntoBy *cube.Pos) bool
// LiquidRemoveBlock is called when the liquid flows into and removes the block passed.
LiquidRemoveBlock(pos cube.Pos, tx *Tx, removed Block)
}
Liquid represents a block that can be moved through and which can flow in the world after placement. There are two liquids in vanilla, which are lava and water.
type LiquidDisplacer ¶
type LiquidDisplacer interface {
// CanDisplace specifies if the block is able to displace the liquid passed.
CanDisplace(b Liquid) bool
// SideClosed checks if a position on the side of the block placed in the world at a specific position is
// closed. When this returns true (for example, when the side is below the position and the block is a
// slab), liquid inside the displacer won't flow from pos into side.
SideClosed(pos, side cube.Pos, tx *Tx) bool
}
LiquidDisplacer represents a block that is able to displace a liquid to a different world layer, without fully removing the liquid.
type Loader ¶
type Loader struct {
// contains filtered or unexported fields
}
Loader implements the loading of the world. A loader can typically be moved around the world to load different parts of the world. An example usage is the player, which uses a loader to load chunks around it so that it can view them.
func NewLoader ¶
NewLoader creates a new loader using the chunk radius passed. Chunks beyond this radius from the position of the loader will never be loaded. The Viewer passed will handle the loading of chunks, including the viewing of entities that were loaded in those chunks.
func (*Loader) ChangeRadius ¶
ChangeRadius changes the maximum chunk radius of the Loader.
func (*Loader) ChangeWorld ¶
ChangeWorld changes the World of the Loader. The currently loaded chunks are reset and any future loading is done from the new World.
func (*Loader) Chunk ¶ added in v0.7.0
Chunk attempts to return a chunk at the given ChunkPos. If the chunk is not loaded, the second return value will be false.
func (*Loader) Close ¶
Close closes the loader. It unloads all chunks currently loaded for the viewer, and hides all entities that are currently shown to it.
func (*Loader) Load ¶
Load loads n chunks around the centre of the chunk, starting with the middle and working outwards. For every chunk loaded, the Viewer passed through construction in New has its ViewChunk method called. Load does nothing for n <= 0.
type NBTer ¶
type NBTer interface {
// DecodeNBT returns the (new) item, block or Entity, depending on which of those the NBTer was, with the NBT data
// decoded into it.
DecodeNBT(data map[string]any) any
// EncodeNBT encodes the Entity into a map which can then be encoded as NBT to be written.
EncodeNBT() map[string]any
}
NBTer represents either an item or a block which may decode NBT data and encode to NBT data. Typically, this is done to store additional data.
type NeighbourUpdateTicker ¶
type NeighbourUpdateTicker interface {
// NeighbourUpdateTick handles a neighbouring block being updated. The position of that block and the
// position of this block is passed.
NeighbourUpdateTick(pos, changedNeighbour cube.Pos, tx *Tx)
}
NeighbourUpdateTicker represents a block that is updated when a block adjacent to it is updated, either through placement or being broken.
type NopGenerator ¶
type NopGenerator struct{}
NopGenerator is the default generator a world. It places no blocks in the world which results in a void world.
func (NopGenerator) DefaultSpawn ¶ added in v0.10.14
func (NopGenerator) DefaultSpawn(Dimension) cube.Pos
DefaultSpawn ...
func (NopGenerator) GenerateChunk ¶
func (NopGenerator) GenerateChunk(ChunkPos, *chunk.Chunk)
GenerateChunk ...
type NopHandler ¶
type NopHandler struct{}
NopHandler implements the Handler interface but does not execute any code when an event is called. The default Handler of worlds is set to NopHandler. Users may embed NopHandler to avoid having to implement each method.
func (NopHandler) HandleBlockBurn ¶ added in v0.6.0
func (NopHandler) HandleBlockBurn(*Context, cube.Pos)
func (NopHandler) HandleClose ¶ added in v0.6.0
func (NopHandler) HandleClose(*Tx)
func (NopHandler) HandleCropTrample ¶ added in v0.9.18
func (NopHandler) HandleCropTrample(*Context, cube.Pos)
func (NopHandler) HandleEntityDespawn ¶ added in v0.6.0
func (NopHandler) HandleEntityDespawn(*Tx, Entity)
func (NopHandler) HandleEntitySpawn ¶ added in v0.6.0
func (NopHandler) HandleEntitySpawn(*Tx, Entity)
func (NopHandler) HandleExplosion ¶ added in v0.10.2
func (NopHandler) HandleFireSpread ¶ added in v0.6.0
func (NopHandler) HandleLeavesDecay ¶ added in v0.10.0
func (NopHandler) HandleLeavesDecay(*Context, cube.Pos)
func (NopHandler) HandleLiquidDecay ¶ added in v0.8.6
func (NopHandler) HandleLiquidFlow ¶
func (NopHandler) HandleLiquidHarden ¶
func (NopHandler) HandleRedstoneUpdate ¶ added in v0.10.14
func (NopHandler) HandleRedstoneUpdate(*Context, RedstoneUpdate)
func (NopHandler) HandleSound ¶ added in v0.5.0
func (NopHandler) HandleSound(*Context, Sound, mgl64.Vec3)
type NopProvider ¶ added in v0.6.0
type NopProvider struct {
Set *Settings
}
NopProvider implements a Provider that does not perform any disk I/O. It generates values on the run and dynamically, instead of reading and writing data, and otherwise returns empty values. A Settings struct can be passed to initialise a world with specific settings. Since Settings is a pointer, using the same NopProvider for multiple worlds means those worlds will share the same settings.
func (NopProvider) Close ¶ added in v0.6.0
func (NopProvider) Close() error
func (NopProvider) LoadColumn ¶ added in v0.9.5
func (NopProvider) LoadPlayerSpawnPosition ¶ added in v0.7.0
func (NopProvider) SavePlayerSpawnPosition ¶ added in v0.7.0
func (NopProvider) SaveSettings ¶ added in v0.6.0
func (NopProvider) SaveSettings(*Settings)
func (NopProvider) Settings ¶ added in v0.6.0
func (n NopProvider) Settings() *Settings
func (NopProvider) StoreColumn ¶ added in v0.9.5
type NopViewer ¶ added in v0.4.1
type NopViewer struct{}
NopViewer is a Viewer implementation that does not implement any behaviour. It may be embedded by other structs to prevent having to implement all of Viewer's methods.
func (NopViewer) HideEntity ¶ added in v0.4.1
func (NopViewer) ViewBlockAction ¶ added in v0.4.1
func (NopViewer) ViewBlockAction(cube.Pos, BlockAction)
func (NopViewer) ViewBlockUpdate ¶ added in v0.4.1
func (NopViewer) ViewBrewingUpdate ¶ added in v0.9.19
func (NopViewer) ViewEntity ¶ added in v0.4.1
func (NopViewer) ViewEntityAction ¶ added in v0.4.1
func (NopViewer) ViewEntityAction(Entity, EntityAction)
func (NopViewer) ViewEntityAnimation ¶ added in v0.9.8
func (NopViewer) ViewEntityAnimation(Entity, EntityAnimation)
func (NopViewer) ViewEntityArmour ¶ added in v0.4.1
func (NopViewer) ViewEntityDisplacement ¶ added in v0.11.0
func (NopViewer) ViewEntityGameMode ¶ added in v0.9.0
func (NopViewer) ViewEntityItems ¶ added in v0.4.1
func (NopViewer) ViewEntityMovement ¶ added in v0.4.1
func (NopViewer) ViewEntityState ¶ added in v0.4.1
func (NopViewer) ViewEntityTeleport ¶ added in v0.4.1
func (NopViewer) ViewEntityVelocity ¶ added in v0.4.1
func (NopViewer) ViewEntityWake ¶ added in v0.10.11
func (NopViewer) ViewFurnaceUpdate ¶ added in v0.8.0
func (NopViewer) ViewTimeCycle ¶ added in v0.10.10
func (NopViewer) ViewWeather ¶ added in v0.4.1
func (NopViewer) ViewWorldSpawn ¶ added in v0.4.1
type PanicError ¶ added in v0.11.0
type PanicError struct {
// Value is the recovered panic value.
Value any
// Stack is the stack of the panicking goroutine.
Stack []byte
}
PanicError is the Task error for a fire-and-forget callback that panicked. It matches errors.Is(err, ErrTaskPanicked) and keeps the original panic value and stack. Synchronous Call functions re-panic with Value automatically.
func (*PanicError) Error ¶ added in v0.11.0
func (e *PanicError) Error() string
Error implements the error interface.
func (*PanicError) Unwrap ¶ added in v0.11.0
func (e *PanicError) Unwrap() error
Unwrap returns ErrTaskPanicked so errors.Is works.
type Particle ¶
type Particle interface {
// Spawn spawns the particle at the position passed. Particles may execute any additional actions here,
// such as spawning different particles.
Spawn(w *World, pos mgl64.Vec3)
}
Particle represents a particle that may be added to the world. These particles are then rendered client- side, with the server having no control over it after sending.
type Provider ¶
type Provider interface {
io.Closer
// Settings loads the settings for a World and returns them.
Settings() *Settings
// SaveSettings saves the settings of a World.
SaveSettings(*Settings)
// LoadPlayerSpawnPosition loads the player spawn point if found, otherwise an error will be returned.
LoadPlayerSpawnPosition(uuid uuid.UUID) (pos cube.Pos, exists bool, err error)
// SavePlayerSpawnPosition saves the player spawn point. In vanilla, this can be done with beds in the overworld
// or respawn anchors in the nether.
SavePlayerSpawnPosition(uuid uuid.UUID, pos cube.Pos) error
// LoadColumn reads a world.Column from the DB at a position and dimension
// in the DB. If no column at that position exists, errors.Is(err,
// leveldb.ErrNotFound) equals true.
LoadColumn(pos ChunkPos, dim Dimension) (*chunk.Column, error)
// StoreColumn stores a world.Column at a position and dimension in the DB.
// An error is returned if storing was unsuccessful.
StoreColumn(pos ChunkPos, dim Dimension, col *chunk.Column) error
}
Provider represents a value that may provide world data to a World value. It usually does the reading and writing of the world data so that the World may use it.
type RandomTicker ¶
type RandomTicker interface {
// RandomTick handles a random tick of the block at the position passed. Additionally, a rand.RandSource
// instance is passed which may be used to generate values randomly without locking.
RandomTick(pos cube.Pos, tx *Tx, r *rand.Rand)
}
RandomTicker represents a block that executes an action when it is ticked randomly. Every 20th of a second, one random block in each sub chunk are picked to receive a random tick.
type RedstoneNonConductive ¶ added in v0.11.0
type RedstoneNonConductive interface {
RedstoneNonConductive()
}
RedstoneNonConductive may be implemented by solid redstone blocks that should not conduct strong power.
type RedstonePowerAction ¶ added in v0.11.0
type RedstonePowerAction interface {
RedstonePowerAction(pos cube.Pos, tx *Tx, oldPower, newPower int)
}
RedstonePowerAction is implemented by blocks that perform a side effect when their input power changes, such as TNT priming on a rising edge. The action is run only if the redstone update event is not cancelled.
type RedstonePowerConsumer ¶ added in v0.11.0
type RedstonePowerConsumer interface {
RedstonePowerUpdate(pos cube.Pos, tx *Tx, power int) (after Block, changed bool)
}
RedstonePowerConsumer is implemented by blocks whose block state changes when their input power changes. The returned block is written to the world if changed is true and the redstone update event is not cancelled.
type RedstonePowerContextAction ¶ added in v0.11.0
type RedstonePowerContextAction interface {
RedstonePowerActionUpdate(pos cube.Pos, tx *Tx, update RedstoneUpdate)
}
RedstonePowerContextAction may be implemented by action blocks that need the proposed update metadata to distinguish self-caused redstone changes from external block updates.
type RedstonePowerPostUpdater ¶ added in v0.11.0
type RedstonePowerPostUpdater interface {
RedstonePowerPostUpdate(pos cube.Pos, tx *Tx, before, after Block, oldPower, newPower int)
}
RedstonePowerPostUpdater may be implemented by consumers that need to apply side effects after an uncancelled redstone state update, such as syncing the other half of a door.
type RedstonePowerRelayer ¶ added in v0.10.14
RedstonePowerRelayer is implemented by redstone wire-like blocks that relay power through a compiled redstone network. The returned value is the signal loss when power crosses one relayer edge.
type RedstonePowerRelayerNeighbourer ¶ added in v0.11.0
type RedstonePowerRelayerNeighbourer interface {
RedstoneRelayerNeighbours(pos cube.Pos, tx *Tx) []cube.Pos
}
RedstonePowerRelayerNeighbourer may be implemented by relayers with non-adjacent connections, such as redstone wire stepping up and down block edges.
type RedstonePowerSource ¶ added in v0.11.0
RedstonePowerSource is implemented by blocks that emit redstone power. The face passed is the face of the source block that power is being read from.
type RedstoneStrongPowerSource ¶ added in v0.11.0
type RedstoneStrongPowerSource interface {
RedstoneStrongPower(pos cube.Pos, tx *Tx, face cube.Face) int
}
RedstoneStrongPowerSource is implemented by sources that strongly power blocks from specific faces. Strong power may pass through solid blocks, unlike weak redstone wire power.
type RedstoneTorchTransaction ¶ added in v0.11.0
type RedstoneTorchTransaction struct {
// contains filtered or unexported fields
}
RedstoneTorchTransaction provides access to transient redstone torch state within a transaction.
func (RedstoneTorchTransaction) BurnoutStatus ¶ added in v0.11.0
func (t RedstoneTorchTransaction) BurnoutStatus() (burnedOut, recoverable bool)
BurnoutStatus returns the transient burnout state for the redstone torch.
func (RedstoneTorchTransaction) ClearBurnout ¶ added in v0.11.0
func (t RedstoneTorchTransaction) ClearBurnout()
ClearBurnout removes transient burnout state for the redstone torch.
func (RedstoneTorchTransaction) ConsumeSelfTriggered ¶ added in v0.11.0
func (t RedstoneTorchTransaction) ConsumeSelfTriggered() bool
ConsumeSelfTriggered reports and clears whether the next turn-off was self-triggered.
func (RedstoneTorchTransaction) MarkSelfTriggered ¶ added in v0.11.0
func (t RedstoneTorchTransaction) MarkSelfTriggered()
MarkSelfTriggered records that the next turn-off was caused by the torch's own output.
func (RedstoneTorchTransaction) RecordTurnOff ¶ added in v0.11.0
func (t RedstoneTorchTransaction) RecordTurnOff() (burnsOut bool)
RecordTurnOff records that the redstone torch was forced off.
type RedstoneTransaction ¶ added in v0.11.0
type RedstoneTransaction struct {
// contains filtered or unexported fields
}
RedstoneTransaction provides access to redstone engine operations within a transaction.
func (RedstoneTransaction) ScheduleUpdate ¶ added in v0.11.0
func (r RedstoneTransaction) ScheduleUpdate(pos cube.Pos)
ScheduleUpdate marks pos and its neighbours for re-evaluation during the next redstone phase.
func (RedstoneTransaction) Torch ¶ added in v0.11.0
func (r RedstoneTransaction) Torch(pos cube.Pos) RedstoneTorchTransaction
Torch returns a transaction-scoped handle for transient redstone torch state at pos.
type RedstoneUpdate ¶ added in v0.11.0
type RedstoneUpdate struct {
// Pos is the block position that will receive the update.
Pos cube.Pos
// ChangedNeighbour is the neighbouring block that caused the update, if any.
ChangedNeighbour cube.Pos
// HasChangedNeighbour reports whether ChangedNeighbour is set. A zero block position is valid, so callers must not
// use ChangedNeighbour == cube.Pos{} as an absence check.
HasChangedNeighbour bool
// ChangedRedstoneRelevant reports whether ChangedNeighbour was a redstone component before or after the change.
ChangedRedstoneRelevant bool
// Source is the original block position that caused this redstone propagation, if known.
Source cube.Pos
// HasSource reports whether Source is set.
HasSource bool
// Before is the block currently at Pos.
Before Block
// After is the block that will replace Before, if the update is a block-state update. After is nil for updates
// that perform side effects instead of replacing the block.
After Block
// OldPower is the last redstone power observed by the engine at Pos.
OldPower int
// NewPower is the redstone power observed by the engine at Pos for this update.
NewPower int
// CurrentTick is the world tick during which the update was evaluated.
CurrentTick int64
// Cause identifies why the update was evaluated.
Cause RedstoneUpdateCause
}
RedstoneUpdate represents a redstone state transition proposed by the world redstone engine. Handlers may cancel the event to suppress the proposed mutation and any propagation from that mutation.
type RedstoneUpdateCause ¶ added in v0.11.0
type RedstoneUpdateCause uint8
RedstoneUpdateCause describes the world event that caused a redstone update to be evaluated.
const ( // RedstoneUpdateCauseBlockUpdate means a block or liquid change invalidated nearby redstone. RedstoneUpdateCauseBlockUpdate RedstoneUpdateCause = iota // RedstoneUpdateCauseScheduledTick means a scheduled redstone tick invalidated a component. RedstoneUpdateCauseScheduledTick // RedstoneUpdateCauseCompilerRebuild means a redstone compiler rebuild invalidated a component. RedstoneUpdateCauseCompilerRebuild )
type RedstoneWeakBlockPowerer ¶ added in v0.11.0
type RedstoneWeakBlockPowerer interface {
RedstoneWeaklyPowersBlocks() bool
}
RedstoneWeakBlockPowerer may be implemented by sources whose weak output can make an adjacent conductive block weakly powered. Weakly powered blocks activate adjacent mechanisms, but do not power adjacent redstone dust.
type ScheduledTicker ¶
type ScheduledTicker interface {
// ScheduledTick handles a scheduled tick initiated by an event in one of the neighbouring blocks, such as
// when a block is placed or broken. Additionally, a rand.RandSource instance is passed which may be used to
// generate values randomly without locking.
ScheduledTick(pos cube.Pos, tx *Tx, r *rand.Rand)
}
ScheduledTicker represents a block that executes an action when it has a block update scheduled, such as when a block adjacent to it is broken.
type SetOpts ¶ added in v0.6.0
type SetOpts struct {
// DisableBlockUpdates makes SetBlock not update any neighbouring blocks as
// a result of the SetBlock call.
DisableBlockUpdates bool
// DisableLiquidDisplacement disables the displacement of liquid blocks to
// the second layer (or back to the first layer, if it already was on the
// second layer). Disabling this is not widely recommended unless
// performance is very important, or where it is known no liquid can be
// present anyway.
DisableLiquidDisplacement bool
// DisableRedstoneUpdates makes SetBlock not invalidate the redstone engine
// around the changed block. This is used by the redstone engine while
// applying its own block-state updates to avoid duplicate same-tick work.
DisableRedstoneUpdates bool
}
SetOpts holds several parameters that may be set to disable updates in the World of different kinds as a result of a call to SetBlock.
type Settings ¶ added in v0.1.0
type Settings struct {
sync.Mutex
// Name is the display name of the World.
Name string
// Spawn is the spawn position of the World. New players that join the world will be spawned here.
Spawn cube.Pos
// Time is the current time of the World. It advances every tick if TimeCycle is set to true.
Time int64
// TimeCycle specifies if the time should advance every tick. If set to false, time won't change.
TimeCycle bool
// RainTime is the current rain time of the World. It advances every tick if WeatherCycle is set to true.
RainTime int64
// Raining is the current rain level of the World.
Raining bool
// ThunderTime is the current thunder time of the World. It advances every tick if WeatherCycle is set to true.
ThunderTime int64
// Thunder is the current thunder level of the World.
Thundering bool
// WeatherCycle specifies if weather should be enabled in this world. If set to false, weather will be disabled.
WeatherCycle bool
// RequiredSleepTicks is the number of ticks that players must sleep for in order for the time to change to day.
RequiredSleepTicks int64
// CurrentTick is the current tick of the world. This is similar to the Time, except that it has no visible effect
// to the client. It can also not be changed through commands and will only ever go up.
CurrentTick int64
// DefaultGameMode is the GameMode assigned to players that join the World for the first time.
DefaultGameMode GameMode
// Difficulty is the difficulty of the World. Behaviour of hunger, regeneration and monsters differs based on the
// difficulty of the world.
Difficulty Difficulty
// TickRange is the radius in chunks around a Viewer that has its blocks and entities ticked when the world is
// ticked. If set to 0, blocks and entities will never be ticked.
TickRange int32
// contains filtered or unexported fields
}
Settings holds the settings of a World. These are typically saved to a level.dat file. It is safe to pass the same Settings to multiple worlds created using New, in which case the Settings are synchronised between the worlds.
type Sleeper ¶ added in v0.10.11
type Sleeper interface {
Entity
Name() string
UUID() uuid.UUID
Messaget(t chat.Translation, a ...any)
SendSleepingIndicator(sleeping, max int)
Sleep(pos cube.Pos)
Sleeping() (cube.Pos, bool)
Wake()
}
Sleeper represents an entity that can sleep.
type Sound ¶
type Sound interface {
// Play plays the sound. This function may play other sounds too. It is always called when World.PlaySound
// is called with the sound.
Play(w *World, pos mgl64.Vec3)
}
Sound represents a sound that may be added to the world. When done, viewers of the world may be able to hear the sound.
type Structure ¶
type Structure interface {
// Dimensions returns the dimensions of the structure. It returns an int array with the width, height and
// length respectively.
Dimensions() [3]int
// At returns the block at a specific location in the structure. When the structure is placed in the
// world, this method is called for every location within the dimensions of the structure. Additionally,
// At can return a Liquid to be placed in the same place as the block.
// At can return nil to not place any block at the position. Returning Air will set any block at that
// position to air, but returning nil will not do anything.
// In addition to the coordinates, At will have a function passed that may be used to get a block at a
// specific position. In scope of At(), structures should use this over World.Block(), due to the way
// chunks are locked.
At(x, y, z int, blockAt func(x, y, z int) Block) (Block, Liquid)
}
Structure represents a structure which may be placed in the world. It has fixed dimensions.
type SubChunkPos ¶ added in v0.7.0
type SubChunkPos [3]int32
SubChunkPos holds the position of a sub-chunk. The type is provided as a utility struct for keeping track of a sub-chunk's position. Sub-chunks do not themselves keep track of that. Sub-chunk positions are different from block positions in the way that increasing the X/Y/Z by one means increasing the absolute value on the X/Y/Z axis in terms of blocks by 16.
func (SubChunkPos) String ¶ added in v0.7.0
func (p SubChunkPos) String() string
String implements fmt.Stringer and returns (x, y, z).
func (SubChunkPos) X ¶ added in v0.7.0
func (p SubChunkPos) X() int32
X returns the X coordinate of the sub-chunk position.
func (SubChunkPos) Y ¶ added in v0.7.0
func (p SubChunkPos) Y() int32
Y returns the Y coordinate of the sub-chunk position.
func (SubChunkPos) Z ¶ added in v0.7.0
func (p SubChunkPos) Z() int32
Z returns the Z coordinate of the sub-chunk position.
type Task ¶ added in v0.11.0
type Task struct {
// contains filtered or unexported fields
}
Task tracks work scheduled onto a world or entity owner. Tasks are usually fire-and-forget: Done, Err and Wait are for code running off the owner, such as tests and shutdown paths. A zero-value Task behaves like a cancelled task.
func NewFinishedTask ¶ added in v0.11.0
NewFinishedTask returns a Task that already completed with err.
func (*Task) Cancel ¶ added in v0.11.0
Cancel stops a task that has not started yet, reporting whether it did: true means the task will never run.
func (*Task) Done ¶ added in v0.11.0
func (t *Task) Done() <-chan struct{}
Done returns a channel that closes once the task has run, failed or been cancelled.
func (*Task) Err ¶ added in v0.11.0
Err returns the task's error, or nil while the task is still pending or after it succeeded.
type TickerBlock ¶
TickerBlock is an implementation of NBTer with an additional Tick method that is called on every world tick for loaded blocks that implement this interface.
type TickerEntity ¶
type TickerEntity interface {
Entity
// Tick ticks the Entity with the current World and tick passed.
Tick(tx *Tx, current int64)
}
TickerEntity represents an Entity that has a Tick method which should be called every time the Entity is ticked every 20th of a second.
type Tx ¶ added in v0.10.0
type Tx struct {
// contains filtered or unexported fields
}
Tx is the owner transaction handle passed to world callbacks. It is the only way to perform world operations and is valid only during its callback.
func (*Tx) AddEntity ¶ added in v0.10.0
func (tx *Tx) AddEntity(e *EntityHandle) Entity
AddEntity adds an EntityHandle to a World. The Entity will be visible to all viewers of the World that have the chunk at the EntityHandle's position. If the chunk that the EntityHandle is in is not yet loaded, it will first be loaded. AddEntity panics if the EntityHandle is already in a world. AddEntity returns the Entity created by the EntityHandle.
func (*Tx) AddEntityAt ¶ added in v0.11.0
func (tx *Tx) AddEntityAt(e *EntityHandle, pos mgl64.Vec3) Entity
AddEntityAt adds an EntityHandle to a World at the position passed. The Entity will be visible to all viewers of the World that have the chunk at the position passed. AddEntityAt panics if the EntityHandle is already in a world. AddEntityAt returns the Entity created by the EntityHandle.
func (*Tx) AddParticle ¶ added in v0.10.0
AddParticle spawns a Particle at a given position in the World. Viewers that are viewing the chunk will be shown the particle.
func (*Tx) Biome ¶ added in v0.10.0
Biome reads the Biome at the position passed. If a chunk is not yet loaded at that position, the chunk is loaded, or generated if it could not be found in the world save, and the Biome returned.
func (*Tx) Block ¶ added in v0.10.0
Block reads a block from the position passed. If a chunk is not yet loaded at that position, the chunk is loaded, or generated if it could not be found in the world save, and the block returned.
func (*Tx) BlockLoaded ¶ added in v0.11.0
BlockLoaded returns the block at the position passed if the chunk containing it is already loaded. It returns false without loading or generating the chunk when the block is unavailable.
func (*Tx) BlocksWithin ¶ added in v0.11.0
BlocksWithin returns an iterator over the positions of blocks matching any of the block states passed, within a horizontal square radius around pos. Chunks not in memory are read from the world save; missing chunks are skipped, not generated. Only the primary block layer is searched and blocks are matched by their state alone.
func (*Tx) BroadcastSleepingIndicator ¶ added in v0.10.11
func (tx *Tx) BroadcastSleepingIndicator()
BroadcastSleepingIndicator broadcasts a sleeping indicator to all sleepers in the world.
func (*Tx) BroadcastSleepingReminder ¶ added in v0.10.11
BroadcastSleepingReminder broadcasts a sleeping reminder message to all sleepers in the world, excluding the sleeper passed.
func (*Tx) BuildStructure ¶ added in v0.10.0
BuildStructure builds a Structure passed at a specific position in the world. Unlike SetBlock, it takes a Structure implementation, which provides blocks to be placed at a specific location. BuildStructure is specifically optimised to be able to process a large batch of chunks simultaneously and will do so within much less time than separate SetBlock calls would. The method operates on a per-chunk basis, setting all blocks within a single chunk part of the Structure before moving on to the next chunk.
func (*Tx) CurrentTick ¶ added in v0.10.14
CurrentTick returns the current tick of the transaction's world.
func (*Tx) Defer ¶ added in v0.11.0
Defer schedules f to run on the owner after the current callback completes and before the parent Task completes. Deferred callbacks run FIFO in registration order, unlike Go defer's LIFO order.
func (*Tx) DeferErr ¶ added in v0.11.0
DeferErr schedules f to run on the owner after the current callback completes, recording any returned error on the Task.
func (*Tx) Entities ¶ added in v0.10.0
Entities returns an iterator that yields all entities in the World.
func (*Tx) EntitiesWithin ¶ added in v0.10.0
EntitiesWithin returns an iterator that yields all entities contained within the cube.BBox passed.
func (*Tx) Event ¶ added in v0.11.0
Event returns a fresh Context for dispatching one Handler event on this transaction, so cancelling one event cannot affect another.
func (*Tx) HighestBlock ¶ added in v0.10.0
HighestBlock looks up the highest non-air block in the World at a specific x and z. The y value of the highest block is returned, or 0 if no blocks were present in the column.
func (*Tx) HighestLightBlocker ¶ added in v0.10.0
HighestLightBlocker gets the Y value of the highest fully light blocking block at the x and z values passed in the World.
func (*Tx) Light ¶ added in v0.10.0
Light returns the light level at the position passed. This is the highest of the sky- and block light. The light value returned is a value in the range 0-15, where 0 means there is no light present, whereas 15 means the block is fully lit.
func (*Tx) Liquid ¶ added in v0.10.0
Liquid attempts to return a Liquid block at the position passed. This Liquid may be in the foreground or in any other layer. If found, the Liquid is returned. If not, the bool returned is false.
func (*Tx) PlayEntityAnimation ¶ added in v0.10.0
func (tx *Tx) PlayEntityAnimation(e Entity, a EntityAnimation)
PlayEntityAnimation plays an animation on an entity in the World. The animation is played for all viewers of the entity.
func (*Tx) PlaySound ¶ added in v0.10.0
PlaySound plays a sound at a specific position in the World. Viewers of that position will be able to hear the sound if they are close enough.
func (*Tx) Players ¶ added in v0.10.0
Players returns an iterator that yields all player entities in the World.
func (*Tx) RainingAt ¶ added in v0.10.0
RainingAt checks if it is raining at a specific cube.Pos in the World. True is returned if it is raining, if the temperature is high enough in the biome for it not to be snow and if the block is above the top-most obstructing block.
func (*Tx) Range ¶ added in v0.10.0
Range returns the lower and upper bounds of the World that the Tx is operating on.
func (*Tx) Redstone ¶ added in v0.10.14
func (tx *Tx) Redstone() RedstoneTransaction
Redstone returns a transaction-scoped handle for redstone engine operations.
func (*Tx) RedstoneConductivePower ¶ added in v0.11.0
RedstoneConductivePower returns the power held by pos as a conductive block, excluding direct component activation. Custom redstone block implementations may use this method to query the transaction's current redstone state.
func (*Tx) RedstoneDirectPower ¶ added in v0.11.0
RedstoneDirectPower returns the strongest direct redstone power currently applied to the position passed, excluding power conducted through solid blocks. Custom redstone block implementations may use this method to query the transaction's current redstone state.
func (*Tx) RedstoneDirectPowerFrom ¶ added in v0.11.0
RedstoneDirectPowerFrom returns the strongest direct redstone power reaching pos from the side passed. Custom redstone block implementations may use this method to query the transaction's current redstone state.
func (*Tx) RedstonePower ¶ added in v0.10.7
RedstonePower returns the strongest redstone power currently applied to the position passed. Custom redstone block implementations may use this method to query the transaction's current redstone state.
func (*Tx) RedstonePowerFrom ¶ added in v0.11.0
RedstonePowerFrom returns the strongest redstone power reaching pos from the side passed. Custom redstone block implementations may use this method to query the transaction's current redstone state.
func (*Tx) RedstoneStrongPower ¶ added in v0.11.0
RedstoneStrongPower returns the strongest strong redstone power currently applied to the position passed. Custom redstone block implementations may use this method to query the transaction's current redstone state.
func (*Tx) RedstoneStrongPowerFrom ¶ added in v0.11.0
RedstoneStrongPowerFrom returns the strongest strong redstone power reaching pos from the side passed. Custom redstone block implementations may use this method to query the transaction's current redstone state.
func (*Tx) RemoveEntity ¶ added in v0.10.0
func (tx *Tx) RemoveEntity(e Entity) *EntityHandle
RemoveEntity removes an Entity from the World that is currently present in it. Any viewers of the Entity will no longer be able to see it. RemoveEntity returns the EntityHandle of the Entity. After removing an Entity from the World, the Entity is no longer usable.
func (*Tx) ScheduleBlockUpdate ¶ added in v0.10.0
ScheduleBlockUpdate schedules a block update at the position passed for the block type passed after a specific delay. If the block at that position does not handle block updates, nothing will happen. Block updates are both block and position specific. A block update is only scheduled if no block update with the same position and block type is already scheduled at a later time than the newly scheduled update.
func (*Tx) SetBiome ¶ added in v0.10.0
SetBiome sets the Biome at the position passed. If a chunk is not yet loaded at that position, the chunk is first loaded or generated if it could not be found in the world save.
func (*Tx) SetBlock ¶ added in v0.10.0
SetBlock writes a block to the position passed. If a chunk is not yet loaded at that position, the chunk is first loaded or generated if it could not be found in the world save. SetBlock panics if the block passed has not yet been registered using RegisterBlock(). Nil may be passed as the block to set the block to air.
A SetOpts struct may be passed to additionally modify behaviour of SetBlock, specifically to improve performance under specific circumstances. Nil should be passed where performance is not essential, to make sure the world is updated adequately.
SetBlock should be avoided in situations where performance is critical when needing to set a lot of blocks to the world. BuildStructure may be used instead.
func (*Tx) SetLiquid ¶ added in v0.10.0
SetLiquid sets a Liquid at a specific position in the World. Unlike SetBlock, SetLiquid will not necessarily overwrite any existing blocks. It will instead be in the same position as a block currently there, unless there already is a Liquid at that position, in which case it will be overwritten. If nil is passed for the Liquid, any Liquid currently present will be removed.
func (*Tx) SkyLight ¶ added in v0.10.0
SkyLight returns the skylight level at the position passed. This light level is not influenced by blocks that emit light, such as torches. The light value, similarly to Light, is a value in the range 0-15, where 0 means no light is present.
func (*Tx) Sleepers ¶ added in v0.10.11
Sleepers returns an iterator that yields all sleeping entities currently added to the World.
func (*Tx) SnowingAt ¶ added in v0.10.0
SnowingAt checks if it is snowing at a specific cube.Pos in the World. True is returned if the temperature in the Biome at that position is sufficiently low, if it is raining and if it's above the top-most obstructing block.
func (*Tx) Temperature ¶ added in v0.10.0
Temperature returns the temperature in the World at a specific position. Higher altitudes and different biomes influence the temperature returned.
func (*Tx) Thundering ¶ added in v0.10.11
Thundering checks if it is thundering anywhere in the World.
func (*Tx) ThunderingAt ¶ added in v0.10.0
ThunderingAt checks if it is thundering at a specific cube.Pos in the World. True is returned if RainingAt returns true and if it is thundering in the world.
type ViewLayer ¶ added in v0.10.13
type ViewLayer struct {
// contains filtered or unexported fields
}
ViewLayer holds overrides for how entities are viewed by a single viewer. It allows entities to be viewed differently by different players, such as with a different name tag or visibility state.
func NewViewLayer ¶ added in v0.10.13
func NewViewLayer(updater ViewLayerUpdater) *ViewLayer
NewViewLayer returns a new ViewLayer.
func (*ViewLayer) Entities ¶ added in v0.10.13
func (v *ViewLayer) Entities() []*EntityHandle
Entities returns the handles of all entities with overrides in the view layer.
func (*ViewLayer) NameTag ¶ added in v0.10.13
NameTag returns the overwritten name tag of the entity and whether an override was set.
func (*ViewLayer) Remove ¶ added in v0.10.13
Remove removes all overrides for the entity from the ViewLayer.
func (*ViewLayer) ScoreTag ¶ added in v0.10.13
ScoreTag returns the overwritten score tag of the entity and whether an override was set.
func (*ViewLayer) ViewNameTag ¶ added in v0.10.13
ViewNameTag overwrites the public name tag of the entity and allows this ViewLayer to view a different name tag. Passing an empty name tag removes the name tag for this ViewLayer.
func (*ViewLayer) ViewPublicNameTag ¶ added in v0.10.13
ViewPublicNameTag removes the name tag override from the entity, causing the public name tag to be viewed again.
func (*ViewLayer) ViewPublicScoreTag ¶ added in v0.10.13
ViewPublicScoreTag removes the score tag override from the entity, causing the public score tag to be viewed again.
func (*ViewLayer) ViewScoreTag ¶ added in v0.10.13
ViewScoreTag overwrites the public score tag of the entity and allows this ViewLayer to view a different score tag. Passing an empty score tag removes the score tag for this ViewLayer.
func (*ViewLayer) ViewVisibility ¶ added in v0.10.13
func (v *ViewLayer) ViewVisibility(entity Entity, level VisibilityLevel)
ViewVisibility overwrites the public visibility of the entity and allows this ViewLayer to view this entity as (in)visible depending on the VisibilityLevel.
func (*ViewLayer) Visibility ¶ added in v0.10.13
func (v *ViewLayer) Visibility(entity Entity) VisibilityLevel
Visibility returns the visibility of the entity.
type ViewLayerUpdater ¶ added in v0.10.13
type ViewLayerUpdater interface {
// ViewLayerEntityChanged handles an entity whose view-layer overrides changed.
ViewLayerEntityChanged(entity Entity)
}
ViewLayerUpdater handles immediate updates after a ViewLayer changes how an entity is viewed.
type Viewer ¶
type Viewer interface {
// ViewEntity views the Entity passed. It is called for every Entity that the viewer may encounter in the
// world, either by moving entities or by moving the viewer using a world.Loader.
ViewEntity(e Entity)
// HideEntity stops viewing the Entity passed. It is called for every Entity that leaves the viewing range
// of the viewer, either by its movement or the movement of the viewer using a world.Loader.
HideEntity(e Entity)
// ViewEntityGameMode views the game mode of the Entity passed. This is necessary for game-modes like spectator,
// which may update how the Entity is viewed for others.
ViewEntityGameMode(e Entity)
// ViewEntityMovement views the movement of an Entity. The Entity is moved with a delta position, yaw and
// pitch, which, when applied to the respective values of the Entity, will result in the final values.
ViewEntityMovement(e Entity, pos mgl64.Vec3, rot cube.Rotation, onGround bool)
// ViewEntityDisplacement views server-authoritative movement of an Entity to an absolute position. Unlike regular
// movement, displacement must also be sent to the controlling session.
ViewEntityDisplacement(e Entity, pos mgl64.Vec3, rot cube.Rotation, onGround bool)
// ViewEntityVelocity views the velocity of an Entity. It is called right before a call to
// ViewEntityMovement so that the Viewer may interpolate the movement itself.
ViewEntityVelocity(e Entity, vel mgl64.Vec3)
// ViewEntityTeleport views the teleportation of an Entity. The Entity is immediately moved to a different
// target position.
ViewEntityTeleport(e Entity, pos mgl64.Vec3)
// ViewFurnaceUpdate updates a furnace for the associated session based on previous times.
ViewFurnaceUpdate(prevCookTime, cookTime, prevRemainingFuelTime, remainingFuelTime, prevMaxFuelTime, maxFuelTime time.Duration)
// ViewBrewingUpdate updates a brewing stand for the associated session based on previous times.
ViewBrewingUpdate(prevBrewTime, brewTime time.Duration, prevFuelAmount, fuelAmount, prevFuelTotal, fuelTotal int32)
// ViewChunk views the chunk passed at a particular position. It is called for every chunk loaded using
// the world.Loader.
ViewChunk(pos ChunkPos, dim Dimension, blockEntities map[cube.Pos]Block, c *chunk.Chunk)
// ViewTime views the time of the world. It is called every time the time is changed or otherwise every
// second.
ViewTime(t int)
// ViewTimeCycle controls the automatic time-of-day cycle (day and night) in the world for this viewer.
ViewTimeCycle(doDayLightCycle bool)
// ViewEntityItems views the items currently held by an Entity that is able to equip items.
ViewEntityItems(e Entity)
// ViewEntityArmour views the items currently equipped as armour by the Entity.
ViewEntityArmour(e Entity)
// ViewEntityAction views an action performed by an Entity. Available actions may be found in the `action`
// package, and include things such as swinging an arm.
ViewEntityAction(e Entity, a EntityAction)
// ViewEntityState views the current state of an Entity. It is called whenever an Entity changes its
// physical appearance, for example when sprinting.
ViewEntityState(e Entity)
// ViewEntityAnimation starts viewing an animation performed by an Entity.
ViewEntityAnimation(e Entity, a EntityAnimation)
// ViewParticle views a particle spawned at a given position in the world. It is called when a particle,
// for example a block breaking particle, is spawned near the player.
ViewParticle(pos mgl64.Vec3, p Particle)
// ViewSound is called when a sound is played in the world.
ViewSound(pos mgl64.Vec3, s Sound)
// ViewBlockUpdate views the updating of a block. It is called when a block is set at the position passed
// to the method.
ViewBlockUpdate(pos cube.Pos, b Block, layer int)
// ViewBlockAction views an action performed by a block. Available actions may be found in the `action`
// package, and include things such as a chest opening.
ViewBlockAction(pos cube.Pos, a BlockAction)
// ViewEmote views an emote being performed by another Entity.
ViewEmote(e Entity, emote uuid.UUID)
// ViewSkin views the current skin of a player.
ViewSkin(e Entity)
// ViewWorldSpawn views the current spawn location of the world.
ViewWorldSpawn(pos cube.Pos)
// ViewWeather views the weather of the world, including rain and thunder.
ViewWeather(raining, thunder bool)
// ViewEntityWake views an entity waking up from a bed.
ViewEntityWake(e Entity)
}
Viewer is a viewer in the world. It can view changes that are made in the world, such as the addition of entities and the changes of blocks.
type VisibilityLevel ¶ added in v0.10.13
type VisibilityLevel struct {
// contains filtered or unexported fields
}
VisibilityLevel controls whether a ViewLayer should use an entity's public visibility or force it visible or invisible for a viewer.
func EnforceInvisible ¶ added in v0.10.13
func EnforceInvisible() VisibilityLevel
EnforceInvisible is the visibility level where the entity is always invisible to the viewer.
func EnforceVisible ¶ added in v0.10.13
func EnforceVisible() VisibilityLevel
EnforceVisible is the visibility level where the entity is always visible to the viewer.
func PublicVisibility ¶ added in v0.10.13
func PublicVisibility() VisibilityLevel
PublicVisibility is the default visibility level where the entity is (in)visible depending on how it already is publicly viewed.
func (VisibilityLevel) EnforceVisibility ¶ added in v0.10.13
func (v VisibilityLevel) EnforceVisibility() bool
EnforceVisibility returns whether metadata should be changed.
type World ¶
type World struct {
// contains filtered or unexported fields
}
World implements a Minecraft world. It manages all aspects of what players can see, such as blocks, entities and particles. World generally provides a synchronised state: All entities, blocks and players usually operate in this world, so World ensures that all its methods will always be safe for simultaneous calls. A nil *World is safe to use but not functional.
func New ¶
func New() *World
New creates a new initialised world. The world may be used right away, but it will not be saved or loaded from files until it has been given a different provider than the default. (NopProvider) By default, the name of the world will be 'World'.
func (*World) AdvanceTick ¶ added in v0.11.0
func (w *World) AdvanceTick()
AdvanceTick advances the World by a single tick. It is generally only useful for Worlds created with Config.Synchronous set: other Worlds tick automatically 20 times per second. Synchronous Worlds tick loaded chunks even when no viewers are present.
func (*World) BlockRegistry ¶ added in v0.10.14
func (w *World) BlockRegistry() BlockRegistry
BlockRegistry returns the BlockRegistry used by the World.
func (*World) DefaultGameMode ¶
DefaultGameMode returns the default game mode of the world. When players join, they are given this game mode. The default game mode may be changed using SetDefaultGameMode().
func (*World) Difficulty ¶
func (w *World) Difficulty() Difficulty
Difficulty returns the difficulty of the world. Properties of mobs in the world and the player's hunger will depend on this difficulty.
func (*World) Dimension ¶ added in v0.5.0
Dimension returns the Dimension assigned to the World in world.New. The sky colour and behaviour of a variety of world features differ based on the Dimension.
func (*World) Do ¶ added in v0.11.0
Do schedules f to run on the world owner and returns immediately; it is safe to call from anywhere, including owner callbacks. Tasks usually run in submission order, but ordering is not guaranteed between tasks scheduled while the queue is saturated. Use one task or Tx.Defer for strictly ordered work. On a synchronous World, f runs before Do returns.
func (*World) DoAfter ¶ added in v0.11.0
DoAfter schedules f to run on the world owner after delay. Cancelling the task before delay elapses stops f from being queued at all.
func (*World) EntityRegistry ¶ added in v0.9.0
func (w *World) EntityRegistry() EntityRegistry
EntityRegistry returns the EntityRegistry that was passed to the World's Config upon construction.
func (*World) Handle ¶
Handle changes the current Handler of the world. As a result, events called by the world will call the methods of the Handler passed. Handle sets the world's Handler to NopHandler if nil is passed.
func (*World) HighestLightBlocker ¶
HighestLightBlocker gets the Y value of the highest fully light blocking block at the x and z values passed in the World.
func (*World) Name ¶
Name returns the display name of the world. Generally, this name is displayed at the top of the player list in the pause screen in-game. If a provider is set, the name will be updated according to the name that it provides.
func (*World) PlayerSpawn ¶ added in v0.7.0
PlayerSpawn returns the spawn position of a player with a UUID in this World.
func (*World) PortalDestination ¶ added in v0.7.0
PortalDestination returns the destination World for a portal of a specific Dimension. If no destination World could be found, the current World is returned. Calling PortalDestination(Nether) on an Overworld World returns Nether, while calling PortalDestination(Nether) on a Nether World will return the Overworld, for instance.
func (*World) Range ¶ added in v0.5.0
Range returns the range in blocks of the World (min and max). It is equivalent to calling World.Dimension().Range().
func (*World) SetDefaultGameMode ¶
SetDefaultGameMode changes the default game mode of the world. When players join, they are then given that game mode.
func (*World) SetDifficulty ¶
func (w *World) SetDifficulty(d Difficulty)
SetDifficulty changes the difficulty of a world.
func (*World) SetPlayerSpawn ¶ added in v0.7.0
SetPlayerSpawn sets the spawn position of a player with a UUID in this World. If the player has a spawn in the world, the player will be teleported to this location on respawn.
func (*World) SetRequiredSleepDuration ¶ added in v0.10.11
SetRequiredSleepDuration sets the duration of time players in the world must sleep for, in order to advance to the next day.
func (*World) SetSpawn ¶
SetSpawn sets the spawn of the world to a different position. The player will be spawned in the centre of this position when newly joining.
func (*World) SetTickRange ¶ added in v0.5.0
SetTickRange sets the range in chunks around each Viewer that will have the chunks (their blocks and entities) ticked when the World is ticked.
func (*World) SetTime ¶
SetTime sets the new time of the world. SetTime will always work, regardless of whether the time is stopped or not.
func (*World) Spawn ¶
Spawn returns the spawn of the world. Every new player will by default spawn on this position in the world when joining.
func (World) StartRaining ¶ added in v0.4.0
StartRaining makes it rain in the World. The time.Duration passed will determine how long it will rain.
func (World) StartThundering ¶ added in v0.4.0
StartThundering makes it thunder in the World. The time.Duration passed will determine how long it will thunder. StartThundering will also make it rain if it wasn't already raining. In this case the rain will, like the thunder, last for the time.Duration passed.
func (*World) StartTime ¶
func (w *World) StartTime()
StartTime restarts the time in the world. When called, the time will start cycling again and the day/night cycle will continue. The time may be stopped again by calling World.StopTime().
func (World) StartWeatherCycle ¶ added in v0.4.0
func (w World) StartWeatherCycle()
StartWeatherCycle enables weather cycle of the World.
func (World) StopRaining ¶ added in v0.4.0
func (w World) StopRaining()
StopRaining makes it stop raining in the World.
func (World) StopThundering ¶ added in v0.4.0
func (w World) StopThundering()
StopThundering makes it stop thundering in the current world.
func (*World) StopTime ¶
func (w *World) StopTime()
StopTime stops the time in the world. When called, the time will no longer cycle and the world will remain at the time when StopTime is called. The time may be restarted by calling World.StartTime().
func (World) StopWeatherCycle ¶ added in v0.4.0
func (w World) StopWeatherCycle()
StopWeatherCycle disables weather cycle of the World.
Source Files
¶
- biome.go
- biome_definition.go
- block.go
- block_model.go
- block_registry.go
- block_search.go
- block_source.go
- block_state.go
- conf.go
- difficulty.go
- dimension.go
- entity.go
- entity_animation.go
- entity_ref.go
- entity_schedule.go
- game_mode.go
- generator.go
- handler.go
- item.go
- loader.go
- network_block_hash.go
- particle.go
- position.go
- provider.go
- redstone.go
- settings.go
- sleep.go
- sound.go
- structure.go
- task.go
- tick.go
- tx.go
- tx_redstone.go
- view_layer.go
- viewer.go
- visibility_level.go
- weather.go
- world.go