world

package
v0.7.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 7, 2022 License: MIT Imports: 25 Imported by: 234

Documentation

Index

Constants

This section is empty.

Variables

View Source
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
)
View Source
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
)
View Source
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
)

Functions

func BlockRuntimeID

func 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 ItemRuntimeID

func ItemRuntimeID(i Item) (rid int32, meta int16, ok bool)

ItemRuntimeID attempts to return the runtime ID of the Item passed. False is returned if the Item is not registered.

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. 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 RegisterEntity added in v0.2.0

func RegisterEntity(e SaveableEntity)

RegisterEntity registers a SaveableEntity to the map so that it can be saved and loaded with the world.

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 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
	// 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 colors.

func BiomeByID added in v0.5.0

func BiomeByID(id int) (Biome, bool)

BiomeByID looks up a biome by the ID and returns it if found.

func Biomes added in v0.5.0

func Biomes() []Biome

Biomes returns a slice of all registered biomes.

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 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.
	Hash() 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

func BlockByName(name string, properties map[string]any) (Block, bool)

BlockByName attempts to return a Block by its name and properties. If not found, the bool returned is false.

func BlockByRuntimeID

func 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.

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, w *World) []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, w *World) 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 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.

func (ChunkPos) String added in v0.6.0

func (p ChunkPos) String() string

String implements fmt.Stringer and returns (x, z).

func (ChunkPos) X

func (p ChunkPos) X() int32

X returns the X coordinate of the chunk position.

func (ChunkPos) Z

func (p ChunkPos) Z() int32

Z returns the Z coordinate of the chunk position.

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, a Logrus logger will be
	// used.
	Log 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 Provider
	// 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
	// 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, `rand.NewSource(time.Now().Unix())` will be used
	// to generate a new source.
	RandSource rand.Source
}

Config may be used to create a new World. It holds a variety of fields that influence the World.

func (Config) New added in v0.7.0

func (conf Config) New() *World

New creates a new World using the Config conf. The World returned will start ticking as soon as a viewer is added to it and is otherwise ready for use.

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 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.

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
	EncodeDimension() int
	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.

type Entity

type Entity interface {
	io.Closer

	// Name returns a human-readable name for the entity. This is not unique for an entity, but generally
	// unique for an entity type.
	Name() string
	// 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 the Entity.
	BBox() cube.BBox

	// Position returns the current position of the entity in the world.
	Position() mgl64.Vec3
	// Rotation returns the yaw and pitch of the entity in degrees. Yaw is horizontal rotation (rotation around the
	// vertical axis, 0 when facing forward), pitch is vertical rotation (rotation around the horizontal axis, also 0
	// when facing forward).
	Rotation() (yaw, pitch float64)
	// World returns the current world of the entity. This is always the world that the entity can actually be
	// found in.
	World() *World
}

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 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
}

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.

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)
}

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 replaced is also passed.
	HandleLiquidFlow(ctx *event.Context, from, into cube.Pos, liquid, replaced Block)
	// 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 *event.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 *event.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 *event.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 event.Context is not cancelled in HandleBlockBurn.
	HandleBlockBurn(ctx *event.Context, pos cube.Pos)
	// HandleEntitySpawn handles an entity being spawned into a World through a call to World.AddEntity.
	HandleEntitySpawn(e Entity)
	// HandleEntityDespawn handles an entity being despawned from a World through a call to World.RemoveEntity.
	HandleEntityDespawn(e Entity)
	// 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()
}

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 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

func ItemByName(name string, meta int16) (Item, bool)

ItemByName attempts to return an item by a name and a metadata value.

func ItemByRuntimeID

func ItemByRuntimeID(rid int32, meta int16) (Item, bool)

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.

func Items

func Items() []Item

Items returns a slice of all registered items.

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
	// 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, w *World, flownIntoBy *cube.Pos) bool
}

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, w *World) 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

func NewLoader(chunkRadius int, world *World, v Viewer) *Loader

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

func (l *Loader) ChangeRadius(new int)

ChangeRadius changes the maximum chunk radius of the Loader.

func (*Loader) ChangeWorld

func (l *Loader) ChangeWorld(new *World)

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

func (l *Loader) Chunk(pos ChunkPos) (*chunkData, bool)

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

func (l *Loader) Close() error

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

func (l *Loader) Load(n int)

Load loads n chunks around the centre of the chunk, starting with the middle and working outwards. For every chunk loaded, the function f is called. The function f must not hold the chunk beyond the function scope. An error is returned if one of the chunks could not be loaded.

func (*Loader) Move

func (l *Loader) Move(pos mgl64.Vec3)

Move moves the loader to the position passed. The position is translated to a chunk position to load

func (*Loader) World

func (l *Loader) World() *World

World returns the World that the Loader is in.

type Logger added in v0.7.0

type Logger interface {
	Errorf(format string, a ...any)
	Debugf(format string, a ...any)
}

Logger is a logger implementation that may be passed to the Log field of Config. World will send errors and debug messages to this Logger when appropriate.

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, w *World)
}

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) 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(*event.Context, cube.Pos)

func (NopHandler) HandleClose added in v0.6.0

func (NopHandler) HandleClose()

func (NopHandler) HandleEntityDespawn added in v0.6.0

func (NopHandler) HandleEntityDespawn(Entity)

func (NopHandler) HandleEntitySpawn added in v0.6.0

func (NopHandler) HandleEntitySpawn(Entity)

func (NopHandler) HandleFireSpread added in v0.6.0

func (NopHandler) HandleFireSpread(*event.Context, cube.Pos, cube.Pos)

func (NopHandler) HandleLiquidFlow

func (NopHandler) HandleLiquidFlow(*event.Context, cube.Pos, cube.Pos, Block, Block)

func (NopHandler) HandleLiquidHarden

func (NopHandler) HandleLiquidHarden(*event.Context, cube.Pos, Block, Block, Block)

func (NopHandler) HandleSound added in v0.5.0

func (NopHandler) HandleSound(*event.Context, Sound, mgl64.Vec3)

type NopProvider added in v0.6.0

type NopProvider struct{}

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.

func (NopProvider) Close added in v0.6.0

func (NopProvider) Close() error

func (NopProvider) LoadBlockNBT added in v0.6.0

func (NopProvider) LoadBlockNBT(ChunkPos, Dimension) ([]map[string]any, error)

func (NopProvider) LoadChunk added in v0.6.0

func (NopProvider) LoadChunk(ChunkPos, Dimension) (*chunk.Chunk, bool, error)

func (NopProvider) LoadEntities added in v0.6.0

func (NopProvider) LoadEntities(ChunkPos, Dimension) ([]SaveableEntity, error)

func (NopProvider) LoadPlayerSpawnPosition added in v0.7.0

func (NopProvider) LoadPlayerSpawnPosition(uuid.UUID) (cube.Pos, bool, error)

func (NopProvider) SaveBlockNBT added in v0.6.0

func (NopProvider) SaveBlockNBT(ChunkPos, []map[string]any, Dimension) error

func (NopProvider) SaveChunk added in v0.6.0

func (NopProvider) SaveEntities added in v0.6.0

func (NopProvider) SavePlayerSpawnPosition added in v0.7.0

func (NopProvider) SavePlayerSpawnPosition(uuid.UUID, cube.Pos) error

func (NopProvider) SaveSettings added in v0.6.0

func (NopProvider) SaveSettings(*Settings)

func (NopProvider) Settings added in v0.6.0

func (NopProvider) Settings() *Settings

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) HideEntity(Entity)

func (NopViewer) ViewBlockAction added in v0.4.1

func (NopViewer) ViewBlockAction(cube.Pos, BlockAction)

func (NopViewer) ViewBlockUpdate added in v0.4.1

func (NopViewer) ViewBlockUpdate(cube.Pos, Block, int)

func (NopViewer) ViewChunk added in v0.4.1

func (NopViewer) ViewChunk(ChunkPos, *chunk.Chunk, map[cube.Pos]Block)

func (NopViewer) ViewEmote added in v0.4.1

func (NopViewer) ViewEmote(Entity, uuid.UUID)

func (NopViewer) ViewEntity added in v0.4.1

func (NopViewer) ViewEntity(Entity)

func (NopViewer) ViewEntityAction added in v0.4.1

func (NopViewer) ViewEntityAction(Entity, EntityAction)

func (NopViewer) ViewEntityArmour added in v0.4.1

func (NopViewer) ViewEntityArmour(Entity)

func (NopViewer) ViewEntityItems added in v0.4.1

func (NopViewer) ViewEntityItems(Entity)

func (NopViewer) ViewEntityMovement added in v0.4.1

func (NopViewer) ViewEntityMovement(Entity, mgl64.Vec3, float64, float64, bool)

func (NopViewer) ViewEntityState added in v0.4.1

func (NopViewer) ViewEntityState(Entity)

func (NopViewer) ViewEntityTeleport added in v0.4.1

func (NopViewer) ViewEntityTeleport(Entity, mgl64.Vec3)

func (NopViewer) ViewEntityVelocity added in v0.4.1

func (NopViewer) ViewEntityVelocity(Entity, mgl64.Vec3)

func (NopViewer) ViewParticle added in v0.4.1

func (NopViewer) ViewParticle(mgl64.Vec3, Particle)

func (NopViewer) ViewSkin added in v0.4.1

func (NopViewer) ViewSkin(Entity)

func (NopViewer) ViewSound added in v0.4.1

func (NopViewer) ViewSound(mgl64.Vec3, Sound)

func (NopViewer) ViewTime added in v0.4.1

func (NopViewer) ViewTime(int)

func (NopViewer) ViewWeather added in v0.4.1

func (NopViewer) ViewWeather(bool, bool)

func (NopViewer) ViewWorldSpawn added in v0.4.1

func (NopViewer) ViewWorldSpawn(cube.Pos)

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
	// LoadChunk attempts to load a chunk from the chunk position passed. If successful, a non-nil chunk is
	// returned and exists is true and err nil. If no chunk was saved at the chunk position passed, the chunk
	// returned is nil, and so is the error. If the chunk did exist, but if the data was invalid, nil is
	// returned for the chunk and true, with a non-nil error.
	// If exists ends up false, the chunk at the position is instead newly generated by the world.
	LoadChunk(position ChunkPos, dim Dimension) (c *chunk.Chunk, exists bool, err error)
	// SaveChunk saves a chunk at a specific position in the provider. If writing was not successful, an error
	// is returned.
	SaveChunk(position ChunkPos, c *chunk.Chunk, dim Dimension) error
	// LoadEntities loads all entities stored at a particular chunk position. If the entities cannot be read,
	// LoadEntities returns a non-nil error.
	LoadEntities(position ChunkPos, dim Dimension) ([]SaveableEntity, error)
	// SaveEntities saves a list of entities in a chunk position. If writing is not successful, an error is
	// returned.
	SaveEntities(position ChunkPos, entities []SaveableEntity, dim Dimension) error
	// LoadBlockNBT loads the block NBT, also known as block entities, at a specific chunk position. If the
	// NBT cannot be read, LoadBlockNBT returns a non-nil error.
	LoadBlockNBT(position ChunkPos, dim Dimension) ([]map[string]any, error)
	// SaveBlockNBT saves block NBT, or block entities, to a specific chunk position. If the NBT cannot be
	// stored, SaveBlockNBT returns a non-nil error.
	SaveBlockNBT(position ChunkPos, data []map[string]any, dim Dimension) 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.Rand
	// instance is passed which may be used to generate values randomly without locking.
	RandomTick(pos cube.Pos, w *World, 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 SaveableEntity added in v0.2.0

type SaveableEntity interface {
	Entity
	NBTer
}

SaveableEntity is an Entity that can be saved and loaded with the World it was added to. These entities can be registered on startup using RegisterEntity to allow loading them in a World.

func Entities added in v0.4.1

func Entities() []SaveableEntity

Entities returns all registered entities.

func EntityByName added in v0.2.0

func EntityByName(name string) (SaveableEntity, bool)

EntityByName looks up a SaveableEntity by the name (for example, 'minecraft:slime') and returns it if found. EntityByName can only return entities previously registered using RegisterEntity. If not found, the bool returned is false.

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.Rand instance is passed which may be used to
	// generate values randomly without locking.
	ScheduledTick(pos cube.Pos, w *World, 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 strongly recommended unless performance is
	// very important or where it is known no liquid can be present anyway.
	DisableLiquidDisplacement 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
	// 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 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 TickerBlock

type TickerBlock interface {
	NBTer
	Tick(currentTick int64, pos cube.Pos, w *World)
}

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 {
	// Tick ticks the entity with the current World and tick passed.
	Tick(w *World, 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 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)
	// 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, yaw, pitch float64, 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)
	// ViewChunk views the chunk passed at a particular position. It is called for every chunk loaded using
	// the world.Loader.
	ViewChunk(pos ChunkPos, c *chunk.Chunk, blockEntities map[cube.Pos]Block)
	// ViewTime views the time of the world. It is called every time the time is changed or otherwise every
	// second.
	ViewTime(t int)
	// 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)
	// 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)
}

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 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 OfEntity

func OfEntity(e Entity) (*World, bool)

OfEntity attempts to return a world that an entity is currently in. If the entity was not currently added to a world, the world returned is nil and the bool returned is false.

func (*World) AddEntity

func (w *World) AddEntity(e Entity)

AddEntity adds an entity to the world at the position that the entity has. The entity will be visible to all viewers of the world that have the chunk of the entity loaded. If the chunk that the entity is in is not yet loaded, it will first be loaded. If the entity passed to AddEntity is currently in a world, it is first removed from that world.

func (*World) AddParticle

func (w *World) AddParticle(pos mgl64.Vec3, p Particle)

AddParticle spawns a particle at a given position in the world. Viewers that are viewing the chunk will be shown the particle.

func (*World) Biome added in v0.5.0

func (w *World) Biome(pos cube.Pos) Biome

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. Chunks will be loaded synchronously.

func (*World) Block

func (w *World) Block(pos cube.Pos) Block

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. Chunks will be loaded synchronously.

func (*World) BuildStructure

func (w *World) BuildStructure(pos cube.Pos, s Structure)

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 tinkered 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 (*World) Close

func (w *World) Close() error

Close closes the world and saves all chunks currently loaded.

func (*World) DefaultGameMode

func (w *World) DefaultGameMode() GameMode

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

func (w *World) Dimension() Dimension

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 assigned to a World.

func (*World) Entities

func (w *World) Entities() []Entity

Entities returns a list of all entities currently added to the World.

func (*World) EntitiesWithin

func (w *World) EntitiesWithin(box cube.BBox, ignored func(Entity) bool) []Entity

EntitiesWithin does a lookup through the entities in the chunks touched by the BBox passed, returning all those which are contained within the BBox when it comes to their position.

func (*World) Handle

func (w *World) Handle(h Handler)

Handle changes the current Handler of the world. As a result, events called by the world will call handlers of the Handler passed. Handle sets the world's Handler to NopHandler if nil is passed.

func (*World) Handler

func (w *World) Handler() Handler

Handler returns the Handler of the world. It should always be used, rather than direct field access, in order to provide synchronisation safety.

func (*World) HighestBlock

func (w *World) HighestBlock(x, z int) int

HighestBlock looks up the highest non-air block in the world at a specific x and z in the world. The y value of the highest block is returned, or 0 if no blocks were present in the column.

func (*World) HighestLightBlocker

func (w *World) HighestLightBlocker(x, z int) int

HighestLightBlocker gets the Y value of the highest fully light blocking block at the x and z values passed in the world.

func (*World) Light

func (w *World) Light(pos cube.Pos) uint8

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 (*World) Liquid

func (w *World) Liquid(pos cube.Pos) (Liquid, bool)

Liquid attempts to return any 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 and the liquid is nil.

func (*World) Name

func (w *World) Name() string

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) PlaySound

func (w *World) PlaySound(pos mgl64.Vec3, s Sound)

PlaySound plays a sound at a specific position in the world. Viewers of that position will be able to hear the sound if they're close enough.

func (*World) PlayerSpawn added in v0.7.0

func (w *World) PlayerSpawn(uuid uuid.UUID) cube.Pos

PlayerSpawn returns the spawn position of a player with a UUID in this World.

func (*World) PortalDestination added in v0.7.0

func (w *World) PortalDestination(dim Dimension) *World

PortalDestination returns the destination world for a portal of a specific Dimension. If no destination World could be found, the current World is returned.

func (World) RainingAt added in v0.4.0

func (w World) RainingAt(pos cube.Pos) bool

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 (*World) Range added in v0.5.0

func (w *World) Range() cube.Range

Range returns the range in blocks of the World (min and max). It is equivalent to calling World.Dimension().Range().

func (*World) RemoveEntity

func (w *World) RemoveEntity(e Entity)

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 operates assuming the position of the entity is the same as where it is currently in the world. If it can not find it there, it will loop through all entities and try to find it. RemoveEntity assumes the entity is currently loaded and in a loaded chunk. If not, the function will not do anything.

func (*World) ScheduleBlockUpdate

func (w *World) ScheduleBlockUpdate(pos cube.Pos, delay time.Duration)

ScheduleBlockUpdate schedules a block update at the position passed after a specific delay. If the block at that position does not handle block updates, nothing will happen.

func (*World) SetBiome added in v0.5.0

func (w *World) SetBiome(pos cube.Pos, b Biome)

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 (*World) SetBlock

func (w *World) SetBlock(pos cube.Pos, b Block, opts *SetOpts)

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 (*World) SetDefaultGameMode

func (w *World) SetDefaultGameMode(mode GameMode)

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) SetLiquid

func (w *World) SetLiquid(pos cube.Pos, b Liquid)

SetLiquid sets the liquid at a specific position in the world. Unlike SetBlock, SetLiquid will not 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 (*World) SetPlayerSpawn added in v0.7.0

func (w *World) SetPlayerSpawn(uuid uuid.UUID, pos cube.Pos)

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) SetSpawn

func (w *World) SetSpawn(pos cube.Pos)

SetSpawn sets the spawn of the world to a different position. The player will be spawned in the center of this position when newly joining.

func (*World) SetTickRange added in v0.5.0

func (w *World) SetTickRange(v int)

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

func (w *World) SetTime(new int)

SetTime sets the new time of the world. SetTime will always work, regardless of whether the time is stopped or not.

func (*World) SkyLight

func (w *World) SkyLight(pos cube.Pos) uint8

SkyLight returns the skylight level at the position passed. This light level is not influenced by blocks that emit light, such as torches or glowstone. The light value, similarly to Light, is a value in the range 0-15, where 0 means no light is present.

func (World) SnowingAt added in v0.5.0

func (w World) SnowingAt(pos cube.Pos) bool

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 (*World) Spawn

func (w *World) Spawn() cube.Pos

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

func (w World) StartRaining(dur time.Duration)

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

func (w World) StartThundering(dur time.Duration)

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(). StartTime will not do anything if the time is already started.

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(). StopTime will not do anything if the time is already stopped.

func (World) StopWeatherCycle added in v0.4.0

func (w World) StopWeatherCycle()

StopWeatherCycle disables weather cycle of the World.

func (*World) Temperature added in v0.5.0

func (w *World) Temperature(pos cube.Pos) float64

Temperature returns the temperature in the World at a specific position. Higher altitudes and different biomes influence the temperature returned.

func (World) ThunderingAt added in v0.4.0

func (w World) ThunderingAt(pos cube.Pos) bool

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.

func (*World) Time

func (w *World) Time() int

Time returns the current time of the world. The time is incremented every 1/20th of a second, unless World.StopTime() is called.

func (*World) Viewers

func (w *World) Viewers(pos mgl64.Vec3) (viewers []Viewer)

Viewers returns a list of all viewers viewing the position passed. A viewer will be assumed to be watching if the position is within one of the chunks that the viewer is watching.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL